1 /*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "device_name_manager.h"
17
18 #include "iservice_registry.h"
19 #include "multiple_user_connector.h"
20 #include "system_ability_definition.h"
21 #include "device_manager_service.h"
22 #include "dm_anonymous.h"
23 #include "dm_constants.h"
24 #include "parameter.h"
25
26 namespace OHOS {
27 namespace DistributedHardware {
28 namespace {
29 constexpr int32_t USERID_HELPER_NUMBER = 100;
30 const std::string SETTING_URI_PROXY = "datashare:///com.ohos.settingsdata/entry/settingsdata/";
31 const std::string SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility";
32 const std::string URI_PROXY_SUFFIX = "?Proxy=true";
33 const std::string SETTINGSDATA_GLOBAL = "SETTINGSDATA";
34 const std::string SETTINGS_GENERAL_DEVICE_NAME = "settings.general.device_name";
35 const std::string SETTINGSDATA_SYSTEM = "USER_SETTINGSDATA_";
36 const std::string SETTINGSDATA_SECURE = "USER_SETTINGSDATA_SECURE_";
37 const std::string DISPLAY_DEVICE_NAME = "display_device_name";
38 const std::string SETTINGS_GENERAL_DISPLAY_DEVICE_NAME = "settings.general." + DISPLAY_DEVICE_NAME;
39 const std::string USER_DEFINED_DEVICE_NAME = "user_defined_device_name";
40 const std::string SETTINGS_GENERAL_USER_DEFINED_DEVICE_NAME = "settings.general." + USER_DEFINED_DEVICE_NAME;
41 const std::string SETTINGS_GENERAL_DISPLAY_DEVICE_NAME_STATE = "settings.general.display_device_name_state";
42 const std::string SETTING_COLUMN_VALUE = "VALUE";
43 const std::string SETTING_COLUMN_KEYWORD = "KEYWORD";
44 constexpr int32_t NUM1 = 1;
45 constexpr int32_t NUM2 = 2;
46 constexpr int32_t NUM3 = 3;
47 constexpr int32_t NUM4 = 4;
48 constexpr int32_t NUM18 = 18;
49 constexpr int32_t NUM21 = 21;
50 constexpr int32_t NUM24 = 24;
51 constexpr int32_t DEFAULT_DEVICE_NAME_MAX_LENGTH = 12;
52 constexpr int32_t NAME_LENGTH_MIN = 18;
53 constexpr int32_t NAME_LENGTH_MAX = 100;
54 const std::string DEFAULT_CONCATENATION_CHARACTER = "...";
55 const std::string NAME_SEPARATOR_ZH = "的";
56 const std::string NAME_SEPARATOR_OTHER = "-";
57 constexpr const char *SOFTBUS_NAME_RAW_JSON_KEY = "raw";
58 constexpr const char *SOFTBUS_NAME_18_JSON_KEY = "name18";
59 constexpr const char *SOFTBUS_NAME_21_JSON_KEY = "name21";
60 constexpr const char *SOFTBUS_NAME_24_JSON_KEY = "name24";
61 constexpr int32_t SYSPARA_SIZE = 128;
62 constexpr const char *PERSIST_GLOBAL_LANGUAGE = "persist.global.language";
63 constexpr const char *DEFAULT_LANGUAGE_KEY = "const.global.language";
64 const std::string LANGUAGE_ZH_HANS = "zh-Hans";
65 constexpr const char *PERSIST_GLOBAL_LOCALE = "persist.global.locale";
66 constexpr const char *DEFAULT_LOCALE_KEY = "const.global.locale";
67 const std::string LOCAL_ZH_HANS_CN = "zh-Hans-CN";
68 constexpr int32_t DEFAULT_USER_ID = -1;
69 }
70
71 IMPLEMENT_SINGLE_INSTANCE(DeviceNameManager);
72
DataShareReady()73 void DeviceNameManager::DataShareReady()
74 {
75 LOGI("In");
76 isDataShareReady_ = true;
77 if (DependsIsReady()) {
78 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
79 InitDeviceName(userId);
80 RegisterDeviceNameChangeMonitor(userId, DEFAULT_USER_ID);
81 }
82 }
83
AccountSysReady(int32_t userId)84 void DeviceNameManager::AccountSysReady(int32_t userId)
85 {
86 LOGI("In userId : %{public}d", userId);
87 isAccountSysReady_ = true;
88 if ((userId != -1) && DependsIsReady()) {
89 InitDeviceName(userId);
90 }
91 }
92
DependsIsReady()93 bool DeviceNameManager::DependsIsReady()
94 {
95 if (!isDataShareReady_) {
96 LOGE("data share not ready");
97 return false;
98 }
99 if (!isAccountSysReady_) {
100 LOGE("Account system not ready");
101 return false;
102 }
103 if (GetRemoteObj() == nullptr) {
104 LOGE("dm sa not publish");
105 return false;
106 }
107 return true;
108 }
109
InitDeviceNameWhenSoftBusReady()110 int32_t DeviceNameManager::InitDeviceNameWhenSoftBusReady()
111 {
112 LOGI("In");
113 if (DependsIsReady()) {
114 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
115 InitDeviceName(userId);
116 RegisterDeviceNameChangeMonitor(userId, DEFAULT_USER_ID);
117 }
118 return DM_OK;
119 }
120
UnInit()121 int32_t DeviceNameManager::UnInit()
122 {
123 {
124 std::lock_guard<std::mutex> lock(remoteObjMtx_);
125 remoteObj_ = nullptr;
126 }
127 {
128 std::lock_guard<std::mutex> lock(monitorMapMtx_);
129 monitorMap_.clear();
130 }
131 return DM_OK;
132 }
133
InitDeviceNameWhenUserSwitch(int32_t curUserId,int32_t preUserId)134 int32_t DeviceNameManager::InitDeviceNameWhenUserSwitch(int32_t curUserId, int32_t preUserId)
135 {
136 isAccountSysReady_ = true;
137 LOGI("In");
138 if (DependsIsReady()) {
139 InitDeviceName(curUserId);
140 RegisterDeviceNameChangeMonitor(curUserId, preUserId);
141 }
142 return DM_OK;
143 }
144
InitDeviceNameWhenLogout()145 int32_t DeviceNameManager::InitDeviceNameWhenLogout()
146 {
147 LOGI("In");
148 if (DependsIsReady()) {
149 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
150 InitDeviceName(userId);
151 }
152 return DM_OK;
153 }
154
InitDeviceNameWhenLogin()155 int32_t DeviceNameManager::InitDeviceNameWhenLogin()
156 {
157 LOGI("In");
158 if (DependsIsReady()) {
159 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
160 InitDeviceName(userId);
161 }
162 return DM_OK;
163 }
164
InitDeviceNameWhenNickChange()165 int32_t DeviceNameManager::InitDeviceNameWhenNickChange()
166 {
167 LOGI("In");
168 if (DependsIsReady()) {
169 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
170 InitDeviceName(userId);
171 }
172 return DM_OK;
173 }
174
InitDeviceNameWhenLanguageOrRegionChanged()175 int32_t DeviceNameManager::InitDeviceNameWhenLanguageOrRegionChanged()
176 {
177 LOGI("In");
178 if (DependsIsReady()) {
179 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
180 InitDeviceName(userId);
181 }
182 return DM_OK;
183 }
184
InitDeviceNameWhenNameChange(int32_t userId)185 int32_t DeviceNameManager::InitDeviceNameWhenNameChange(int32_t userId)
186 {
187 LOGI("In");
188 if (DependsIsReady()) {
189 InitDeviceName(userId);
190 }
191 return DM_OK;
192 }
193
RegisterDeviceNameChangeMonitor(int32_t curUserId,int32_t preUserId)194 void DeviceNameManager::RegisterDeviceNameChangeMonitor(int32_t curUserId, int32_t preUserId)
195 {
196 LOGI("In");
197 UnRegisterDeviceNameChangeMonitor(preUserId);
198 if (curUserId == DEFAULT_USER_ID) {
199 LOGW("userId invalid");
200 return;
201 }
202 sptr<DeviceNameChangeMonitor> monitor = nullptr;
203 {
204 std::lock_guard<std::mutex> lock(monitorMapMtx_);
205 auto iter = monitorMap_.find(curUserId);
206 if (iter != monitorMap_.end()) {
207 return;
208 }
209 monitor = sptr<DeviceNameChangeMonitor>(new DeviceNameChangeMonitor(curUserId));
210 if (monitor == nullptr) {
211 LOGE("monitor is nullptr");
212 return;
213 }
214 monitorMap_[curUserId] = monitor;
215 }
216 std::string proxyUri = GetProxyUriStr(SETTINGSDATA_SECURE, curUserId);
217 auto helper = CreateDataShareHelper(proxyUri);
218 if (helper == nullptr) {
219 LOGE("helper is nullptr");
220 {
221 std::lock_guard<std::mutex> lock(monitorMapMtx_);
222 auto iter = monitorMap_.find(curUserId);
223 if (iter != monitorMap_.end()) {
224 monitorMap_.erase(iter);
225 }
226 }
227 return;
228 }
229 Uri uri = MakeUri(proxyUri, SETTINGS_GENERAL_USER_DEFINED_DEVICE_NAME);
230 helper->RegisterObserver(uri, monitor);
231 ReleaseDataShareHelper(helper);
232 }
233
UnRegisterDeviceNameChangeMonitor(int32_t userId)234 void DeviceNameManager::UnRegisterDeviceNameChangeMonitor(int32_t userId)
235 {
236 LOGI("In");
237 if (userId == DEFAULT_USER_ID) {
238 LOGW("userId invalid");
239 return;
240 }
241 sptr<DeviceNameChangeMonitor> monitor = nullptr;
242 {
243 std::lock_guard<std::mutex> lock(monitorMapMtx_);
244 auto iter = monitorMap_.find(userId);
245 if (iter != monitorMap_.end()) {
246 monitor = iter->second;
247 monitorMap_.erase(iter);
248 }
249 }
250 if (monitor == nullptr) {
251 LOGW("monitor is nullptr");
252 return;
253 }
254 std::string proxyUri = GetProxyUriStr(SETTINGSDATA_SECURE, userId);
255 auto helper = CreateDataShareHelper(proxyUri);
256 if (helper == nullptr) {
257 LOGE("helper is nullptr");
258 return;
259 }
260 Uri uri = MakeUri(proxyUri, SETTINGS_GENERAL_USER_DEFINED_DEVICE_NAME);
261 helper->UnregisterObserver(uri, monitor);
262 ReleaseDataShareHelper(helper);
263 }
264
InitDeviceName(int32_t userId)265 void DeviceNameManager::InitDeviceName(int32_t userId)
266 {
267 LOGI("In userId:%{public}d", userId);
268 if (userId == -1) {
269 LOGI("userId:%{public}d is invalid", userId);
270 return;
271 }
272 std::string userDefinedDeviceName = "";
273 GetUserDefinedDeviceName(userId, userDefinedDeviceName);
274 if (!userDefinedDeviceName.empty()) {
275 LOGI("userDefinedDeviceName:%{public}s", GetAnonyString(userDefinedDeviceName).c_str());
276 InitDeviceNameToSoftBus("", userDefinedDeviceName);
277 InitDisplayDeviceNameToSettingsData("", userDefinedDeviceName, userId);
278 return;
279 }
280 std::string deviceName = GetLocalMarketName();
281 if (deviceName.empty()) {
282 LOGE("deviceName is empty");
283 return;
284 }
285 std::string nickName = MultipleUserConnector::GetAccountNickName(userId);
286 InitDeviceNameToSoftBus(nickName, deviceName);
287 InitDisplayDeviceNameToSettingsData(nickName, deviceName, userId);
288 }
289
InitDeviceNameToSoftBus(const std::string & prefixName,const std::string & subffixName)290 void DeviceNameManager::InitDeviceNameToSoftBus(const std::string &prefixName, const std::string &subffixName)
291 {
292 LOGI("In prefixName:%{public}s, subffixName:%{public}s",
293 GetAnonyString(prefixName).c_str(), GetAnonyString(subffixName).c_str());
294 std::string raw = GetLocalDisplayDeviceName(prefixName, subffixName, 0);
295 std::string name18 = GetLocalDisplayDeviceName(prefixName, subffixName, NUM18);
296 std::string name21 = GetLocalDisplayDeviceName(prefixName, subffixName, NUM21);
297 std::string name24 = GetLocalDisplayDeviceName(prefixName, subffixName, NUM24);
298 cJSON *root = cJSON_CreateObject();
299 if (root == NULL) {
300 LOGE("cJSON_CreateObject fail!");
301 return;
302 }
303 cJSON_AddStringToObject(root, SOFTBUS_NAME_RAW_JSON_KEY, raw.c_str());
304 cJSON_AddStringToObject(root, SOFTBUS_NAME_18_JSON_KEY, name18.c_str());
305 cJSON_AddStringToObject(root, SOFTBUS_NAME_21_JSON_KEY, name21.c_str());
306 cJSON_AddStringToObject(root, SOFTBUS_NAME_24_JSON_KEY, name24.c_str());
307 char *jsonChar = cJSON_PrintUnformatted(root);
308 cJSON_Delete(root);
309 if (jsonChar == NULL) {
310 LOGE("cJSON_PrintUnformatted fail!");
311 return;
312 }
313 std::string displayName = jsonChar;
314 cJSON_free(jsonChar);
315 DeviceManagerService::GetInstance().SetLocalDisplayNameToSoftbus(displayName);
316 }
317
GetLocalDisplayDeviceName(int32_t maxNamelength,std::string & displayName)318 int32_t DeviceNameManager::GetLocalDisplayDeviceName(int32_t maxNamelength, std::string &displayName)
319 {
320 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
321 if (maxNamelength < 0 || (maxNamelength > 0 && maxNamelength < NAME_LENGTH_MIN) ||
322 maxNamelength > NAME_LENGTH_MAX) {
323 LOGE("maxNamelength:%{public}d is invalid", maxNamelength);
324 return ERR_DM_INPUT_PARA_INVALID;
325 }
326 std::string userDefinedDeviceName = "";
327 GetUserDefinedDeviceName(userId, userDefinedDeviceName);
328 if (!userDefinedDeviceName.empty()) {
329 LOGI("userDefinedDeviceName:%{public}s", GetAnonyString(userDefinedDeviceName).c_str());
330 displayName = GetLocalDisplayDeviceName("", userDefinedDeviceName, maxNamelength);
331 return DM_OK;
332 }
333 std::string nickName = MultipleUserConnector::GetAccountNickName(userId);
334 std::string localMarketName = GetLocalMarketName();
335 displayName = GetLocalDisplayDeviceName(nickName, localMarketName, maxNamelength);
336 return DM_OK;
337 }
338
GetLocalDisplayDeviceName(const std::string & prefixName,const std::string & subffixName,int32_t maxNameLength)339 std::string DeviceNameManager::GetLocalDisplayDeviceName(const std::string &prefixName, const std::string &subffixName,
340 int32_t maxNameLength)
341 {
342 if (prefixName.empty()) {
343 if (maxNameLength == 0 || static_cast<int32_t>(subffixName.size()) <= maxNameLength) {
344 return subffixName;
345 }
346 return SubstrByBytes(subffixName, maxNameLength - NUM3) + DEFAULT_CONCATENATION_CHARACTER;
347 }
348 int32_t defaultNameMaxLength = DEFAULT_DEVICE_NAME_MAX_LENGTH;
349 if (maxNameLength >= NUM21) {
350 defaultNameMaxLength = DEFAULT_DEVICE_NAME_MAX_LENGTH + NUM3;
351 }
352 std::string nameSeparator = NAME_SEPARATOR_ZH;
353 if (GetSystemLanguage() != LANGUAGE_ZH_HANS || GetSystemRegion() != LOCAL_ZH_HANS_CN) {
354 nameSeparator = NAME_SEPARATOR_OTHER;
355 }
356 std::string displayName = prefixName + nameSeparator + subffixName;
357 if (maxNameLength == 0 || static_cast<int32_t>(displayName.size()) <= maxNameLength) {
358 return displayName;
359 }
360 std::string subffix = subffixName;
361 if (static_cast<int32_t>(subffixName.size()) > defaultNameMaxLength) {
362 subffix = SubstrByBytes(subffixName, defaultNameMaxLength - NUM3) + DEFAULT_CONCATENATION_CHARACTER;
363 }
364 int32_t remainingLen = maxNameLength - static_cast<int32_t>(subffix.size());
365 if (remainingLen <= 0) {
366 return subffix;
367 }
368 displayName = prefixName + nameSeparator + subffix;
369 if (static_cast<int32_t>(displayName.size()) <= maxNameLength) {
370 return displayName;
371 }
372 remainingLen = remainingLen - NUM3;
373 std::string prefix = prefixName;
374 if (static_cast<int32_t>(prefix.size()) > remainingLen) {
375 prefix = SubstrByBytes(prefix, remainingLen) + DEFAULT_CONCATENATION_CHARACTER;
376 }
377 displayName = prefix + subffix;
378 return displayName;
379 }
380
ModifyUserDefinedName(const std::string & deviceName)381 int32_t DeviceNameManager::ModifyUserDefinedName(const std::string &deviceName)
382 {
383 LOGI("In");
384 if (deviceName.empty()) {
385 LOGE("deviceName is empty");
386 return ERR_DM_NAME_EMPTY;
387 }
388 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
389 SetUserDefinedDeviceName(deviceName, userId);
390 SetDisplayDeviceNameState(USER_DEFINED_DEVICE_NAME, userId);
391 SetDisplayDeviceName(deviceName, userId);
392 InitDeviceNameToSoftBus("", deviceName);
393 return DM_OK;
394 }
395
RestoreLocalDeviceName()396 int32_t DeviceNameManager::RestoreLocalDeviceName()
397 {
398 LOGI("In");
399 int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
400 SetUserDefinedDeviceName("", userId);
401 SetDisplayDeviceNameState("", userId);
402 std::string nickName = MultipleUserConnector::GetAccountNickName(userId);
403 std::string localMarketName = GetLocalMarketName();
404 InitDeviceNameToSoftBus(nickName, localMarketName);
405 InitDisplayDeviceNameToSettingsData(nickName, localMarketName, userId);
406 return DM_OK;
407 }
408
InitDisplayDeviceNameToSettingsData(const std::string & nickName,const std::string & deviceName,int32_t userId)409 int32_t DeviceNameManager::InitDisplayDeviceNameToSettingsData(const std::string &nickName,
410 const std::string &deviceName, int32_t userId)
411 {
412 #if defined(SUPPORT_WISEDEVICE)
413 std::string newDisplayName = GetLocalDisplayDeviceName(nickName, deviceName, 0);
414 std::string oldDisplayName = "";
415 GetDisplayDeviceName(userId, oldDisplayName);
416 if (oldDisplayName != newDisplayName) {
417 SetDisplayDeviceName(newDisplayName, userId);
418 }
419 #else
420 (void) nickName;
421 (void) deviceName;
422 (void) userId;
423 #endif // SUPPORT_WISEDEVICE
424 return DM_OK;
425 }
426
GetUserDefinedDeviceName(int32_t userId,std::string & deviceName)427 int32_t DeviceNameManager::GetUserDefinedDeviceName(int32_t userId, std::string &deviceName)
428 {
429 return GetValue(SETTINGSDATA_SECURE, userId, SETTINGS_GENERAL_USER_DEFINED_DEVICE_NAME, deviceName);
430 }
431
SubstrByBytes(const std::string & str,int32_t maxNumBytes)432 std::string DeviceNameManager::SubstrByBytes(const std::string &str, int32_t maxNumBytes)
433 {
434 int32_t length = static_cast<int32_t>(str.size());
435 if (length <= maxNumBytes || maxNumBytes <= 0) {
436 return str;
437 }
438 std::vector<std::string> substrVec;
439 for (int32_t i = 0; i < length;) {
440 unsigned char c = static_cast<unsigned char>(str[i]);
441 int numBytes = NUM1;
442 if ((c & 0x80) == 0) {
443 numBytes = NUM1;
444 } else if ((c & 0xE0) == 0xC0) {
445 numBytes = NUM2;
446 } else if ((c & 0xF0) == 0xE0) {
447 numBytes = NUM3;
448 } else if ((c & 0xF8) == 0xF0) {
449 numBytes = NUM4;
450 } else {
451 LOGE("Invalid characters");
452 return "";
453 }
454 if (i + numBytes > length) {
455 break;
456 }
457 std::string substr(str.begin() + i, str.begin() + i + numBytes);
458 substrVec.emplace_back(substr);
459 i += numBytes;
460 }
461 std::string result = "";
462 int32_t totalNumBytes = 0;
463 for (const auto &item : substrVec) {
464 int32_t cnt = totalNumBytes + static_cast<int32_t>(item.size());
465 if (cnt > maxNumBytes) {
466 break;
467 }
468 totalNumBytes = cnt;
469 result = result + item;
470 }
471 return result;
472 }
473
GetSystemLanguage()474 std::string DeviceNameManager::GetSystemLanguage()
475 {
476 char param[SYSPARA_SIZE] = {0};
477 int status = GetParameter(PERSIST_GLOBAL_LANGUAGE, "", param, SYSPARA_SIZE);
478 if (status > 0) {
479 return param;
480 }
481 status = GetParameter(DEFAULT_LANGUAGE_KEY, "", param, SYSPARA_SIZE);
482 if (status > 0) {
483 return param;
484 }
485 LOGE("Failed to get system language");
486 return "";
487 }
488
GetSystemRegion()489 std::string DeviceNameManager::GetSystemRegion()
490 {
491 char param[SYSPARA_SIZE] = {0};
492 int status = GetParameter(PERSIST_GLOBAL_LOCALE, "", param, SYSPARA_SIZE);
493 if (status > 0) {
494 return param;
495 }
496 status = GetParameter(DEFAULT_LOCALE_KEY, "", param, SYSPARA_SIZE);
497 if (status > 0) {
498 return param;
499 }
500 LOGE("Failed to get system local");
501 return "";
502 }
503
GetLocalMarketName()504 std::string DeviceNameManager::GetLocalMarketName()
505 {
506 std::lock_guard<std::mutex> lock(localMarketNameMtx_);
507 if (localMarketName_.empty()) {
508 const char *marketName = GetMarketName();
509 if (marketName == nullptr) {
510 LOGE("get marketName fail!");
511 return "";
512 }
513 localMarketName_ = marketName;
514 free((char *)marketName);
515 }
516 std::vector<std::string> prefixs = DeviceManagerService::GetInstance().GetDeviceNamePrefixs();
517 for (const auto &item : prefixs) {
518 localMarketName_ = TrimStr(ReplaceStr(localMarketName_, item, ""));
519 }
520 LOGI("localMarketName : %{public}s", GetAnonyString(localMarketName_).c_str());
521 return localMarketName_;
522 }
523
SetUserDefinedDeviceName(const std::string & deviceName,int32_t userId)524 int32_t DeviceNameManager::SetUserDefinedDeviceName(const std::string &deviceName, int32_t userId)
525 {
526 LOGI("SetUserDefinedDeviceName:%{public}s, userId:%{public}d", GetAnonyString(deviceName).c_str(), userId);
527 return SetValue(SETTINGSDATA_SECURE, userId, SETTINGS_GENERAL_USER_DEFINED_DEVICE_NAME, deviceName);
528 }
529
GetDisplayDeviceName(int32_t userId,std::string & deviceName)530 int32_t DeviceNameManager::GetDisplayDeviceName(int32_t userId, std::string &deviceName)
531 {
532 return GetValue(SETTINGSDATA_SECURE, userId, SETTINGS_GENERAL_DISPLAY_DEVICE_NAME, deviceName);
533 }
534
SetDisplayDeviceNameState(const std::string & state,int32_t userId)535 int32_t DeviceNameManager::SetDisplayDeviceNameState(const std::string &state, int32_t userId)
536 {
537 LOGI("SetDisplayDeviceNameState:%{public}s, userId:%{public}d", state.c_str(), userId);
538 return SetValue(SETTINGSDATA_SECURE, userId, SETTINGS_GENERAL_DISPLAY_DEVICE_NAME_STATE, state);
539 }
540
SetDisplayDeviceName(const std::string & deviceName,int32_t userId)541 int32_t DeviceNameManager::SetDisplayDeviceName(const std::string &deviceName, int32_t userId)
542 {
543 if (deviceName.empty()) {
544 LOGE("SetDisplayDeviceName deviceName is empty, userId:%{public}d", userId);
545 return ERR_DM_NAME_EMPTY;
546 }
547 LOGI("SetDisplayDeviceName:%{public}s, userId:%{public}d", GetAnonyString(deviceName).c_str(), userId);
548 return SetValue(SETTINGSDATA_SECURE, userId, SETTINGS_GENERAL_DISPLAY_DEVICE_NAME, deviceName);
549 }
550
GetDeviceName(std::string & deviceName)551 int32_t DeviceNameManager::GetDeviceName(std::string &deviceName)
552 {
553 return GetValue(SETTINGSDATA_GLOBAL, 0, SETTINGS_GENERAL_DEVICE_NAME, deviceName);
554 }
555
SetDeviceName(const std::string & deviceName)556 int32_t DeviceNameManager::SetDeviceName(const std::string &deviceName)
557 {
558 if (deviceName.empty()) {
559 LOGE("deviceName is empty");
560 return ERR_DM_NAME_EMPTY;
561 }
562 return SetValue(SETTINGSDATA_GLOBAL, 0, SETTINGS_GENERAL_DEVICE_NAME, deviceName);
563 }
564
GetRemoteObj()565 sptr<IRemoteObject> DeviceNameManager::GetRemoteObj()
566 {
567 std::lock_guard<std::mutex> lock(remoteObjMtx_);
568 if (remoteObj_ != nullptr) {
569 return remoteObj_;
570 }
571 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
572 if (samgr == nullptr) {
573 LOGE("get sa manager return nullptr");
574 return nullptr;
575 }
576 auto remoteObj = samgr->GetSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
577 if (remoteObj == nullptr) {
578 LOGE("get system ability failed, id=%{public}d", DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
579 return nullptr;
580 }
581 remoteObj_ = remoteObj;
582 return remoteObj_;
583 }
584
GetValue(const std::string & tableName,int32_t userId,const std::string & key,std::string & value)585 int32_t DeviceNameManager::GetValue(const std::string &tableName, int32_t userId,
586 const std::string &key, std::string &value)
587 {
588 std::string proxyUri = GetProxyUriStr(tableName, userId);
589 auto helper = CreateDataShareHelper(proxyUri);
590 if (helper == nullptr) {
591 LOGE("helper is nullptr, proxyUri=%{public}s", proxyUri.c_str());
592 return ERR_DM_POINT_NULL;
593 }
594 std::vector<std::string> columns = { SETTING_COLUMN_VALUE };
595 DataShare::DataSharePredicates predicates;
596 predicates.EqualTo(SETTING_COLUMN_KEYWORD, key);
597 Uri uri = MakeUri(proxyUri, key);
598 auto resultSet = helper->Query(uri, predicates, columns);
599 ReleaseDataShareHelper(helper);
600 if (resultSet == nullptr) {
601 LOGE("Query failed key=%{public}s, proxyUri=%{public}s", key.c_str(), proxyUri.c_str());
602 return ERR_DM_POINT_NULL;
603 }
604 int32_t count = 0;
605 resultSet->GetRowCount(count);
606 if (count == 0) {
607 LOGW("no value, key=%{public}s, proxyUri=%{public}s", key.c_str(), proxyUri.c_str());
608 resultSet->Close();
609 return DM_OK;
610 }
611 int32_t index = 0;
612 resultSet->GoToRow(index);
613 int32_t ret = resultSet->GetString(index, value);
614 if (ret != DataShare::E_OK) {
615 LOGE("get value failed, ret=%{public}d, proxyUri=%{public}s", ret, proxyUri.c_str());
616 resultSet->Close();
617 return ret;
618 }
619 resultSet->Close();
620 LOGI("proxyUri=%{public}s, value=%{public}s", proxyUri.c_str(), GetAnonyString(value).c_str());
621 return DM_OK;
622 }
623
SetValue(const std::string & tableName,int32_t userId,const std::string & key,const std::string & value)624 int32_t DeviceNameManager::SetValue(const std::string &tableName, int32_t userId,
625 const std::string &key, const std::string &value)
626 {
627 std::string proxyUri = GetProxyUriStr(tableName, userId);
628 auto helper = CreateDataShareHelper(proxyUri);
629 if (helper == nullptr) {
630 LOGE("helper is nullptr, proxyUri=%{public}s, value=%{public}s",
631 proxyUri.c_str(), GetAnonyString(value).c_str());
632 return ERR_DM_POINT_NULL;
633 }
634 DataShare::DataShareValuesBucket val;
635 val.Put(SETTING_COLUMN_KEYWORD, key);
636 val.Put(SETTING_COLUMN_VALUE, value);
637 Uri uri = MakeUri(proxyUri, key);
638 DataShare::DataSharePredicates predicates;
639 predicates.EqualTo(SETTING_COLUMN_KEYWORD, key);
640 int32_t ret = helper->Update(uri, predicates, val);
641 if (ret <= 0) {
642 LOGW("Update failed, ret=%{public}d, proxyUri=%{public}s, value=%{public}s",
643 ret, proxyUri.c_str(), GetAnonyString(value).c_str());
644 ret = helper->Insert(uri, val);
645 }
646 ReleaseDataShareHelper(helper);
647 if (ret <= 0) {
648 LOGE("set value failed, ret=%{public}d, proxyUri=%{public}s, value=%{public}s",
649 ret, proxyUri.c_str(), GetAnonyString(value).c_str());
650 return ret;
651 }
652 return ret;
653 }
654
CreateDataShareHelper(const std::string & proxyUri)655 std::shared_ptr<DataShare::DataShareHelper> DeviceNameManager::CreateDataShareHelper(const std::string &proxyUri)
656 {
657 if (proxyUri.empty()) {
658 LOGE("proxyUri is empty");
659 return nullptr;
660 }
661 auto [ret, helper] = DataShare::DataShareHelper::Create(GetRemoteObj(), proxyUri, SETTINGS_DATA_EXT_URI);
662 if (ret != 0) {
663 LOGE("create helper failed ret %{public}d", ret);
664 return nullptr;
665 }
666 return helper;
667 }
668
GetProxyUriStr(const std::string & tableName,int32_t userId)669 std::string DeviceNameManager::GetProxyUriStr(const std::string &tableName, int32_t userId)
670 {
671 if (userId < USERID_HELPER_NUMBER) {
672 userId = USERID_HELPER_NUMBER;
673 }
674 if (tableName == SETTINGSDATA_GLOBAL) {
675 return SETTING_URI_PROXY + SETTINGSDATA_GLOBAL + URI_PROXY_SUFFIX;
676 } else {
677 return SETTING_URI_PROXY + tableName + std::to_string(userId) + URI_PROXY_SUFFIX;
678 }
679 }
680
MakeUri(const std::string & proxyUri,const std::string & key)681 Uri DeviceNameManager::MakeUri(const std::string &proxyUri, const std::string &key)
682 {
683 if (proxyUri.empty() || key.empty()) {
684 LOGE("Invalid parameter.");
685 }
686 Uri uri(proxyUri + "&key=" + key);
687 return uri;
688 }
689
ReleaseDataShareHelper(std::shared_ptr<DataShare::DataShareHelper> helper)690 bool DeviceNameManager::ReleaseDataShareHelper(std::shared_ptr<DataShare::DataShareHelper> helper)
691 {
692 if (helper == nullptr) {
693 LOGE("helper is nullptr");
694 return false;
695 }
696 if (!helper->Release()) {
697 LOGE("release helper fail");
698 return false;
699 }
700 return true;
701 }
702 } // namespace DistributedHardware
703 } // namespace OHOS