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