1 /*
2 * Copyright (c) 2022 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 #define LOG_TAG "DeviceManagerAdapter"
17 #include "device_manager_adapter.h"
18
19 #include <thread>
20
21 #include "kvstore_utils.h"
22 #include "log_print.h"
23 #include "net_conn_callback_stub.h"
24 #include "net_conn_client.h"
25 #include "net_handle.h"
26
27 namespace OHOS::DistributedData {
28 using namespace OHOS::DistributedHardware;
29 using namespace OHOS::AppDistributedKv;
30 using namespace OHOS::NetManagerStandard;
31 using KvStoreUtils = OHOS::DistributedKv::KvStoreUtils;
32 constexpr int32_t DM_OK = 0;
33 constexpr const char *PKG_NAME = "ohos.distributeddata.service";
34 class DataMgrDmStateCall final : public DistributedHardware::DeviceStateCallback {
35 public:
DataMgrDmStateCall(DeviceManagerAdapter & dmAdapter)36 explicit DataMgrDmStateCall(DeviceManagerAdapter &dmAdapter) : dmAdapter_(dmAdapter) {}
37 void OnDeviceOnline(const DmDeviceInfo &info) override;
38 void OnDeviceOffline(const DmDeviceInfo &info) override;
39 void OnDeviceChanged(const DmDeviceInfo &info) override;
40 void OnDeviceReady(const DmDeviceInfo &info) override;
41
42 private:
43 DeviceManagerAdapter &dmAdapter_;
44 };
45
OnDeviceOnline(const DmDeviceInfo & info)46 void DataMgrDmStateCall::OnDeviceOnline(const DmDeviceInfo &info)
47 {
48 dmAdapter_.Online(info);
49 }
50
OnDeviceOffline(const DmDeviceInfo & info)51 void DataMgrDmStateCall::OnDeviceOffline(const DmDeviceInfo &info)
52 {
53 dmAdapter_.Offline(info);
54 }
55
OnDeviceChanged(const DmDeviceInfo & info)56 void DataMgrDmStateCall::OnDeviceChanged(const DmDeviceInfo &info)
57 {
58 dmAdapter_.OnChanged(info);
59 }
60
OnDeviceReady(const DmDeviceInfo & info)61 void DataMgrDmStateCall::OnDeviceReady(const DmDeviceInfo &info)
62 {
63 dmAdapter_.OnReady(info);
64 }
65
66 class DataMgrDmInitCall final : public DistributedHardware::DmInitCallback {
67 public:
DataMgrDmInitCall(DeviceManagerAdapter & dmAdapter,std::shared_ptr<ExecutorPool> executors)68 explicit DataMgrDmInitCall(DeviceManagerAdapter &dmAdapter, std::shared_ptr<ExecutorPool> executors)
69 : dmAdapter_(dmAdapter), executors_(executors) {}
70 void OnRemoteDied() override;
71
72 private:
73 DeviceManagerAdapter &dmAdapter_;
74 std::shared_ptr<ExecutorPool> executors_;
75 };
76
OnRemoteDied()77 void DataMgrDmInitCall::OnRemoteDied()
78 {
79 ZLOGI("device manager died, init again");
80 dmAdapter_.Init(executors_);
81 }
82
83 class NetConnCallbackObserver : public NetConnCallbackStub {
84 public:
NetConnCallbackObserver(DeviceManagerAdapter & dmAdapter)85 explicit NetConnCallbackObserver(DeviceManagerAdapter &dmAdapter) : dmAdapter_(dmAdapter) {}
86 ~NetConnCallbackObserver() override = default;
87 int32_t NetAvailable(sptr<NetHandle> &netHandle) override;
88 int32_t NetCapabilitiesChange(sptr<NetHandle> &netHandle, const sptr<NetAllCapabilities> &netAllCap) override;
89 int32_t NetConnectionPropertiesChange(sptr<NetHandle> &netHandle, const sptr<NetLinkInfo> &info) override;
90 int32_t NetLost(sptr<NetHandle> &netHandle) override;
91 int32_t NetUnavailable() override;
92 int32_t NetBlockStatusChange(sptr<NetHandle> &netHandle, bool blocked) override;
93
94 private:
95 DeviceManagerAdapter &dmAdapter_;
96 };
97
NetAvailable(sptr<NetManagerStandard::NetHandle> & netHandle)98 int32_t NetConnCallbackObserver::NetAvailable(sptr<NetManagerStandard::NetHandle> &netHandle)
99 {
100 ZLOGI("OnNetworkAvailable");
101 dmAdapter_.SetNetAvailable(true);
102 dmAdapter_.Online(dmAdapter_.cloudDmInfo);
103 return DistributedKv::SUCCESS;
104 }
105
NetUnavailable()106 int32_t NetConnCallbackObserver::NetUnavailable()
107 {
108 ZLOGI("OnNetworkUnavailable");
109 dmAdapter_.SetNetAvailable(false);
110 return DistributedKv::SUCCESS;
111 }
112
NetCapabilitiesChange(sptr<NetHandle> & netHandle,const sptr<NetAllCapabilities> & netAllCap)113 int32_t NetConnCallbackObserver::NetCapabilitiesChange(sptr<NetHandle> &netHandle,
114 const sptr<NetAllCapabilities> &netAllCap)
115 {
116 ZLOGI("OnNetCapabilitiesChange");
117 return DistributedKv::SUCCESS;
118 }
119
NetConnectionPropertiesChange(sptr<NetHandle> & netHandle,const sptr<NetLinkInfo> & info)120 int32_t NetConnCallbackObserver::NetConnectionPropertiesChange(sptr<NetHandle> &netHandle,
121 const sptr<NetLinkInfo> &info)
122 {
123 ZLOGI("OnNetConnectionPropertiesChange");
124 return DistributedKv::SUCCESS;
125 }
126
NetLost(sptr<NetHandle> & netHandle)127 int32_t NetConnCallbackObserver::NetLost(sptr<NetHandle> &netHandle)
128 {
129 ZLOGI("OnNetLost");
130 dmAdapter_.SetNetAvailable(false);
131 dmAdapter_.Offline(dmAdapter_.cloudDmInfo);
132 return DistributedKv::SUCCESS;
133 }
134
NetBlockStatusChange(sptr<NetHandle> & netHandle,bool blocked)135 int32_t NetConnCallbackObserver::NetBlockStatusChange(sptr<NetHandle> &netHandle, bool blocked)
136 {
137 ZLOGI("OnNetBlockStatusChange");
138 return DistributedKv::SUCCESS;
139 }
140
DeviceManagerAdapter()141 DeviceManagerAdapter::DeviceManagerAdapter()
142 : cloudDmInfo({ "cloudDeviceId", "cloudDeviceName", 0, "cloudNetworkId", 0 })
143 {
144 ZLOGI("construct");
145 }
146
~DeviceManagerAdapter()147 DeviceManagerAdapter::~DeviceManagerAdapter()
148 {
149 ZLOGI("Destruct");
150 }
151
GetInstance()152 DeviceManagerAdapter &DeviceManagerAdapter::GetInstance()
153 {
154 static DeviceManagerAdapter dmAdapter;
155 return dmAdapter;
156 }
157
Init(std::shared_ptr<ExecutorPool> executors)158 void DeviceManagerAdapter::Init(std::shared_ptr<ExecutorPool> executors)
159 {
160 ZLOGI("begin");
161 if (executors_ == nullptr) {
162 executors_ = std::move(executors);
163 }
164 RegDevCallback()();
165 }
166
RegDevCallback()167 std::function<void()> DeviceManagerAdapter::RegDevCallback()
168 {
169 return [this]() {
170 auto &devManager = DeviceManager::GetInstance();
171 auto dmStateCall = std::make_shared<DataMgrDmStateCall>(*this);
172 auto dmInitCall = std::make_shared<DataMgrDmInitCall>(*this, executors_);
173 auto resultInit = devManager.InitDeviceManager(PKG_NAME, dmInitCall);
174 auto resultState = devManager.RegisterDevStateCallback(PKG_NAME, "", dmStateCall);
175 auto resultNet = RegOnNetworkChange();
176 if (resultInit == DM_OK && resultState == DM_OK && resultNet) {
177 InitDeviceInfo(false);
178 return;
179 }
180 constexpr int32_t INTERVAL = 500;
181 executors_->Schedule(std::chrono::milliseconds(INTERVAL), RegDevCallback());
182 };
183 }
184
StartWatchDeviceChange(const AppDeviceChangeListener * observer,const PipeInfo & pipeInfo)185 Status DeviceManagerAdapter::StartWatchDeviceChange(const AppDeviceChangeListener *observer,
186 __attribute__((unused)) const PipeInfo &pipeInfo)
187 {
188 if (observer == nullptr) {
189 ZLOGE("observer is nullptr");
190 return Status::INVALID_ARGUMENT;
191 }
192 if (!observers_.Insert(observer, observer)) {
193 ZLOGE("insert observer fail");
194 return Status::ERROR;
195 }
196 return Status::SUCCESS;
197 }
198
StopWatchDeviceChange(const AppDeviceChangeListener * observer,const PipeInfo & pipeInfo)199 Status DeviceManagerAdapter::StopWatchDeviceChange(const AppDeviceChangeListener *observer,
200 __attribute__((unused)) const PipeInfo &pipeInfo)
201 {
202 if (observer == nullptr) {
203 ZLOGE("observer is nullptr");
204 return Status::INVALID_ARGUMENT;
205 }
206 if (!observers_.Erase(observer)) {
207 ZLOGE("erase observer fail");
208 return Status::ERROR;
209 }
210 return Status::SUCCESS;
211 }
212
Online(const DmDeviceInfo & info)213 void DeviceManagerAdapter::Online(const DmDeviceInfo &info)
214 {
215 DeviceInfo dvInfo;
216 if (!GetDeviceInfo(info, dvInfo)) {
217 ZLOGE("get device info fail");
218 return;
219 }
220 ZLOGI("[online] uuid:%{public}s, name:%{public}s, type:%{public}d",
221 KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType);
222 SaveDeviceInfo(dvInfo, DeviceChangeType::DEVICE_ONLINE);
223 syncTask_.Insert(dvInfo.uuid, dvInfo.uuid);
224 auto observers = GetObservers();
225 for (const auto &item : observers) { // notify db
226 if (item == nullptr) {
227 continue;
228 }
229 if (item->GetChangeLevelType() == ChangeLevelType::HIGH) {
230 item->OnDeviceChanged(dvInfo, DeviceChangeType::DEVICE_OFFLINE);
231 item->OnDeviceChanged(dvInfo, DeviceChangeType::DEVICE_ONLINE);
232 }
233 }
234 for (const auto &item : observers) { // sync meta, get device security level
235 if (item == nullptr) {
236 continue;
237 }
238 if (item->GetChangeLevelType() == ChangeLevelType::LOW) {
239 item->OnDeviceChanged(dvInfo, DeviceChangeType::DEVICE_ONLINE);
240 }
241 }
242
243 executors_->Schedule(std::chrono::milliseconds(SYNC_TIMEOUT), [this, dvInfo]() {
244 TimeOut(dvInfo.uuid);
245 });
246
247 for (const auto &item : observers) { // set compatible identify, sync service meta
248 if (item == nullptr) {
249 continue;
250 }
251 if (item->GetChangeLevelType() == ChangeLevelType::MIN) {
252 item->OnDeviceChanged(dvInfo, DeviceChangeType::DEVICE_ONLINE);
253 }
254 }
255 }
256
TimeOut(const std::string uuid)257 void DeviceManagerAdapter::TimeOut(const std::string uuid)
258 {
259 if (uuid.empty()) {
260 ZLOGE("uuid empty!");
261 return;
262 }
263 if (syncTask_.Contains(uuid) && uuid != CLOUD_DEVICE_UUID) {
264 ZLOGI("[TimeOutReadyEvent] uuid:%{public}s", KvStoreUtils::ToBeAnonymous(uuid).c_str());
265 std::string event = R"({"extra": {"deviceId":")" + uuid + R"(" } })";
266 DeviceManager::GetInstance().NotifyEvent(PKG_NAME, DmNotifyEvent::DM_NOTIFY_EVENT_ONDEVICEREADY, event);
267 }
268 syncTask_.Erase(uuid);
269 }
270
NotifyReadyEvent(const std::string & uuid)271 void DeviceManagerAdapter::NotifyReadyEvent(const std::string &uuid)
272 {
273 if (uuid.empty() || !syncTask_.Contains(uuid)) {
274 return;
275 }
276
277 syncTask_.Erase(uuid);
278 ZLOGI("[NotifyReadyEvent] uuid:%{public}s", KvStoreUtils::ToBeAnonymous(uuid).c_str());
279 std::string event = R"({"extra": {"deviceId":")" + uuid + R"(" } })";
280 DeviceManager::GetInstance().NotifyEvent(PKG_NAME, DmNotifyEvent::DM_NOTIFY_EVENT_ONDEVICEREADY, event);
281 }
282
GetObservers()283 std::vector<const AppDeviceChangeListener *> DeviceManagerAdapter::GetObservers()
284 {
285 std::vector<const AppDeviceChangeListener *> observers;
286 observers.reserve(observers_.Size());
287 observers_.ForEach([&observers](const auto &key, auto &value) {
288 observers.emplace_back(value);
289 return false;
290 });
291 return observers;
292 }
293
Offline(const DmDeviceInfo & info)294 void DeviceManagerAdapter::Offline(const DmDeviceInfo &info)
295 {
296 DeviceInfo dvInfo;
297 if (!GetDeviceInfo(info, dvInfo)) {
298 ZLOGE("get device info fail");
299 return;
300 }
301 syncTask_.Erase(dvInfo.uuid);
302 ZLOGI("[offline] uuid:%{public}s, name:%{public}s, type:%{public}d",
303 KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType);
304 SaveDeviceInfo(dvInfo, DeviceChangeType::DEVICE_OFFLINE);
305 auto task = [this, dvInfo]() {
306 observers_.ForEachCopies([&dvInfo](const auto &key, auto &value) {
307 if (value != nullptr) {
308 value->OnDeviceChanged(dvInfo, DeviceChangeType::DEVICE_OFFLINE);
309 }
310 return false;
311 });
312 };
313 executors_->Execute(std::move(task));
314 }
315
OnChanged(const DmDeviceInfo & info)316 void DeviceManagerAdapter::OnChanged(const DmDeviceInfo &info)
317 {
318 DeviceInfo dvInfo;
319 if (!GetDeviceInfo(info, dvInfo)) {
320 ZLOGE("get device info fail");
321 return;
322 }
323 ZLOGI("[OnChanged] uuid:%{public}s, name:%{public}s, type:%{public}d",
324 KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType);
325 }
326
OnReady(const DmDeviceInfo & info)327 void DeviceManagerAdapter::OnReady(const DmDeviceInfo &info)
328 {
329 DeviceInfo dvInfo;
330 if (!GetDeviceInfo(info, dvInfo)) {
331 ZLOGE("get device info fail");
332 return;
333 }
334 readyDevices_.InsertOrAssign(dvInfo.uuid, std::make_pair(DeviceState::DEVICE_ONREADY, dvInfo));
335 ZLOGI("[OnReady] uuid:%{public}s, name:%{public}s, type:%{public}d",
336 KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType);
337 auto task = [this, dvInfo]() {
338 observers_.ForEachCopies([&dvInfo](const auto &key, auto &value) {
339 if (value != nullptr) {
340 value->OnDeviceChanged(dvInfo, DeviceChangeType::DEVICE_ONREADY);
341 }
342 return false;
343 });
344 };
345 executors_->Execute(std::move(task));
346 }
347
GetDeviceInfo(const DmDeviceInfo & dmInfo,DeviceInfo & dvInfo)348 bool DeviceManagerAdapter::GetDeviceInfo(const DmDeviceInfo &dmInfo, DeviceInfo &dvInfo)
349 {
350 std::string networkId = std::string(dmInfo.networkId);
351 if (networkId.empty()) {
352 return false;
353 }
354 auto uuid = GetUuidByNetworkId(networkId);
355 auto udid = GetUdidByNetworkId(networkId);
356 if (uuid.empty() || udid.empty()) {
357 ZLOGW("uuid or udid empty");
358 return false;
359 }
360 dvInfo = { uuid, udid, networkId, std::string(dmInfo.deviceName), dmInfo.deviceTypeId };
361 return true;
362 }
363
SaveDeviceInfo(const DeviceInfo & dvInfo,const DeviceChangeType & type)364 void DeviceManagerAdapter::SaveDeviceInfo(const DeviceInfo &dvInfo, const DeviceChangeType &type)
365 {
366 if (dvInfo.networkId == DeviceManagerAdapter::cloudDmInfo.networkId) {
367 return;
368 }
369 switch (type) {
370 case DeviceChangeType::DEVICE_ONLINE: {
371 deviceInfos_.Set(dvInfo.networkId, dvInfo);
372 deviceInfos_.Set(dvInfo.uuid, dvInfo);
373 deviceInfos_.Set(dvInfo.udid, dvInfo);
374 readyDevices_.InsertOrAssign(dvInfo.uuid, std::make_pair(DeviceState::DEVICE_ONLINE, dvInfo));
375 break;
376 }
377 case DeviceChangeType::DEVICE_OFFLINE: {
378 deviceInfos_.Delete(dvInfo.networkId);
379 deviceInfos_.Delete(dvInfo.uuid);
380 deviceInfos_.Delete(dvInfo.udid);
381 readyDevices_.Erase(dvInfo.uuid);
382 break;
383 }
384 default: {
385 ZLOGW("unknown type.");
386 break;
387 }
388 }
389 }
390
GetLocalDevice()391 DeviceInfo DeviceManagerAdapter::GetLocalDevice()
392 {
393 std::lock_guard<decltype(devInfoMutex_)> lock(devInfoMutex_);
394 if (!localInfo_.uuid.empty() && !localInfo_.udid.empty()) {
395 return localInfo_;
396 }
397 localInfo_ = GetLocalDeviceInfo();
398 return localInfo_;
399 }
400
GetRemoteDevices()401 std::vector<DeviceInfo> DeviceManagerAdapter::GetRemoteDevices()
402 {
403 std::vector<DmDeviceInfo> dmInfos;
404 auto ret = DeviceManager::GetInstance().GetTrustedDeviceList(PKG_NAME, "", dmInfos);
405 if (ret != DM_OK) {
406 ZLOGE("get trusted device:%{public}d", ret);
407 return {};
408 }
409
410 std::vector<DeviceInfo> dvInfos;
411 for (const auto &dmInfo : dmInfos) {
412 auto networkId = std::string(dmInfo.networkId);
413 auto uuid = GetUuidByNetworkId(networkId);
414 auto udid = GetUdidByNetworkId(networkId);
415 DeviceInfo dvInfo = { std::move(uuid), std::move(udid), std::move(networkId),
416 std::string(dmInfo.deviceName), dmInfo.deviceTypeId };
417 dvInfos.emplace_back(std::move(dvInfo));
418 }
419 return dvInfos;
420 }
421
GetOnlineDevices()422 std::vector<DeviceInfo> DeviceManagerAdapter::GetOnlineDevices()
423 {
424 std::vector<DeviceInfo> devices;
425 devices.reserve(readyDevices_.Size());
426 readyDevices_.ForEach([&devices](auto &, auto &info) {
427 devices.push_back(info.second);
428 return false;
429 });
430 return devices;
431 }
432
IsDeviceReady(const std::string & id)433 bool DeviceManagerAdapter::IsDeviceReady(const std::string& id)
434 {
435 auto it = readyDevices_.Find(id);
436 return (it.first && it.second.first == DeviceState::DEVICE_ONREADY);
437 }
438
GetOnlineSize()439 size_t DeviceManagerAdapter::GetOnlineSize()
440 {
441 return readyDevices_.Size();
442 }
443
GetDeviceInfo(const std::string & id)444 DeviceInfo DeviceManagerAdapter::GetDeviceInfo(const std::string &id)
445 {
446 return GetDeviceInfoFromCache(id);
447 }
448
GetDeviceInfoFromCache(const std::string & id)449 DeviceInfo DeviceManagerAdapter::GetDeviceInfoFromCache(const std::string &id)
450 {
451 DeviceInfo dvInfo;
452 if (!deviceInfos_.Get(id, dvInfo)) {
453 InitDeviceInfo();
454 deviceInfos_.Get(id, dvInfo);
455 }
456 if (dvInfo.uuid.empty()) {
457 ZLOGE("invalid id:%{public}s", KvStoreUtils::ToBeAnonymous(id).c_str());
458 }
459 return dvInfo;
460 }
461
InitDeviceInfo(bool onlyCache)462 void DeviceManagerAdapter::InitDeviceInfo(bool onlyCache)
463 {
464 std::vector<DeviceInfo> dvInfos = GetRemoteDevices();
465 if (dvInfos.empty()) {
466 ZLOGW("there is no trusted device!");
467 }
468 if (!onlyCache) {
469 readyDevices_.Clear();
470 }
471 for (const auto &info : dvInfos) {
472 if (info.networkId.empty() || info.uuid.empty() || info.udid.empty()) {
473 ZLOGE("networkId:%{public}s, uuid:%{public}d, udid:%{public}d",
474 KvStoreUtils::ToBeAnonymous(info.networkId).c_str(), info.uuid.empty(), info.udid.empty());
475 continue;
476 }
477 deviceInfos_.Set(info.networkId, info);
478 deviceInfos_.Set(info.uuid, info);
479 deviceInfos_.Set(info.udid, info);
480 if (!onlyCache) {
481 readyDevices_.InsertOrAssign(info.uuid, std::make_pair(DeviceState::DEVICE_ONREADY, info));
482 }
483 }
484 auto local = GetLocalDeviceInfo();
485 deviceInfos_.Set(local.networkId, local);
486 deviceInfos_.Set(local.uuid, local);
487 deviceInfos_.Set(local.udid, local);
488 }
489
GetLocalDeviceInfo()490 DeviceInfo DeviceManagerAdapter::GetLocalDeviceInfo()
491 {
492 DmDeviceInfo info;
493 auto ret = DeviceManager::GetInstance().GetLocalDeviceInfo(PKG_NAME, info);
494 if (ret != DM_OK) {
495 ZLOGE("get local device info fail");
496 return {};
497 }
498 auto networkId = std::string(info.networkId);
499 auto uuid = GetUuidByNetworkId(networkId);
500 auto udid = GetUdidByNetworkId(networkId);
501 if (uuid.empty()) {
502 return {};
503 }
504 ZLOGI("[LocalDevice] uuid:%{public}s, name:%{public}s, type:%{public}d", KvStoreUtils::ToBeAnonymous(uuid).c_str(),
505 info.deviceName, info.deviceTypeId);
506 return { std::move(uuid), std::move(udid), std::move(networkId), std::string(info.deviceName), info.deviceTypeId };
507 }
508
GetUuidByNetworkId(const std::string & networkId)509 std::string DeviceManagerAdapter::GetUuidByNetworkId(const std::string &networkId)
510 {
511 if (networkId.empty()) {
512 return "";
513 }
514 if (networkId == DeviceManagerAdapter::cloudDmInfo.networkId) {
515 return CLOUD_DEVICE_UUID;
516 }
517 DeviceInfo dvInfo;
518 if (deviceInfos_.Get(networkId, dvInfo)) {
519 return dvInfo.uuid;
520 }
521 std::string uuid;
522 auto ret = DeviceManager::GetInstance().GetUuidByNetworkId(PKG_NAME, networkId, uuid);
523 if (ret != DM_OK || uuid.empty()) {
524 ZLOGE("failed, result:%{public}d, networkId:%{public}s", ret, KvStoreUtils::ToBeAnonymous(networkId).c_str());
525 return "";
526 }
527 return uuid;
528 }
529
GetUdidByNetworkId(const std::string & networkId)530 std::string DeviceManagerAdapter::GetUdidByNetworkId(const std::string &networkId)
531 {
532 if (networkId.empty()) {
533 return "";
534 }
535 if (networkId == DeviceManagerAdapter::cloudDmInfo.networkId) {
536 return CLOUD_DEVICE_UDID;
537 }
538 DeviceInfo dvInfo;
539 if (deviceInfos_.Get(networkId, dvInfo)) {
540 return dvInfo.udid;
541 }
542 std::string udid;
543 auto ret = DeviceManager::GetInstance().GetUdidByNetworkId(PKG_NAME, networkId, udid);
544 if (ret != DM_OK || udid.empty()) {
545 ZLOGE("failed, result:%{public}d, networkId:%{public}s", ret, KvStoreUtils::ToBeAnonymous(networkId).c_str());
546 return "";
547 }
548 return udid;
549 }
550
ToUUID(const std::string & id)551 std::string DeviceManagerAdapter::ToUUID(const std::string &id)
552 {
553 return GetDeviceInfoFromCache(id).uuid;
554 }
555
ToUDID(const std::string & id)556 std::string DeviceManagerAdapter::ToUDID(const std::string &id)
557 {
558 return GetDeviceInfoFromCache(id).udid;
559 }
560
ToUUID(const std::vector<std::string> & devices)561 std::vector<std::string> DeviceManagerAdapter::ToUUID(const std::vector<std::string> &devices)
562 {
563 std::vector<std::string> uuids;
564 for (auto &device : devices) {
565 auto uuid = DeviceManagerAdapter::GetInstance().ToUUID(device);
566 if (uuid.empty()) {
567 continue;
568 }
569 uuids.push_back(std::move(uuid));
570 }
571 return uuids;
572 }
573
ToUUID(std::vector<DeviceInfo> devices)574 std::vector<std::string> DeviceManagerAdapter::ToUUID(std::vector<DeviceInfo> devices)
575 {
576 std::vector<std::string> uuids;
577 for (auto &device : devices) {
578 if (device.uuid.empty()) {
579 continue;
580 }
581 uuids.push_back(std::move(device.uuid));
582 }
583 return uuids;
584 }
585
ToNetworkID(const std::string & id)586 std::string DeviceManagerAdapter::ToNetworkID(const std::string &id)
587 {
588 return GetDeviceInfoFromCache(id).networkId;
589 }
590
CalcClientUuid(const std::string & appId,const std::string & uuid)591 std::string DeviceManagerAdapter::CalcClientUuid(const std::string &appId, const std::string &uuid)
592 {
593 if (uuid.empty()) {
594 return "";
595 }
596 std::string encryptedUuid;
597 auto ret = DeviceManager::GetInstance().GenerateEncryptedUuid(PKG_NAME, uuid, appId, encryptedUuid);
598 if (ret != DM_OK) {
599 ZLOGE("failed, result:%{public}d", ret);
600 return "";
601 }
602 return encryptedUuid;
603 }
604
RegOnNetworkChange()605 bool DeviceManagerAdapter::RegOnNetworkChange()
606 {
607 sptr<NetConnCallbackObserver> observer = new (std::nothrow) NetConnCallbackObserver(*this);
608 if (observer == nullptr) {
609 ZLOGE("new operator error.observer is nullptr");
610 return false;
611 }
612 int nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer);
613 if (nRet != NETMANAGER_SUCCESS) {
614 ZLOGE("RegisterNetConnCallback failed, ret = %{public}d", nRet);
615 return false;
616 }
617 return true;
618 }
619
IsNetworkAvailable()620 bool DeviceManagerAdapter::IsNetworkAvailable()
621 {
622 {
623 std::shared_lock<decltype(mutex_)> lock(mutex_);
624 if (isNetAvailable_ || expireTime_ > std::chrono::steady_clock::now()) {
625 return isNetAvailable_;
626 }
627 }
628 NetHandle handle;
629 auto status = NetConnClient::GetInstance().GetDefaultNet(handle);
630 return SetNetAvailable(status == 0 && handle.GetNetId() != 0);
631 }
632
SetNetAvailable(bool isNetAvailable)633 bool DeviceManagerAdapter::SetNetAvailable(bool isNetAvailable)
634 {
635 std::unique_lock<decltype(mutex_)> lock(mutex_);
636 isNetAvailable_ = isNetAvailable;
637 expireTime_ = std::chrono::steady_clock::now() + std::chrono::milliseconds(EFFECTIVE_DURATION);
638 return isNetAvailable_;
639 }
640 } // namespace OHOS::DistributedData
641