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