• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "native_devicemanager_js.h"
17 #include <securec.h>
18 #include "nlohmann/json.hpp"
19 #include "device_manager.h"
20 #include "dm_constants.h"
21 #include "jsi_types.h"
22 #include "js_async_work.h"
23 #include "dm_log.h"
24 #include "dm_device_info.h"
25 
26 using namespace OHOS::DistributedHardware;
27 using namespace std;
28 
29 namespace OHOS {
30 namespace ACELite {
31 const std::string DM_JSI_EVENT_DEVICE_STATE_CHANGE = "deviceStateChange";
32 const std::string DM_JSI_EVENT_DEVICE_FOUND = "deviceFound";
33 const std::string DM_JSI_EVENT_DEVICE_DISCOVER_FAIL = "discoverFail";
34 const std::string DM_JSI_EVENT_DMFA_CALLBACK = "dmFaCallback";
35 const std::string DM_JSI_EVENT_DEVICE_SERVICE_DIE = "serviceDie";
36 
37 const std::string DEVICE_MANAGER_JSI_CLASS_NAME = "DeviceManager";
38 const uint8_t DM_JSI_ARGS_ONE = 1;
39 const uint8_t DM_JSI_ARGS_TWO = 2;
40 const uint8_t DM_JSI_ARGS_THREE = 3;
41 const int32_t DM_JSI_SUB_ID_MAX = 65535;
42 
43 const int32_t DM_AUTH_TYPE_PINCODE = 1;
44 const int32_t DM_AUTH_DIRECTION_CLIENT = 1;
45 
46 const int32_t DM_JSI_SUBSCRIBE_CAPABILITY_DDMP = 0;
47 const int32_t DM_JSI_SUBSCRIBE_CAPABILITY_OSD = 1;
48 const char *DM_CAPABILITY_OSD = "osdCapability";
49 
50 std::map<std::string, DeviceManagerModule *> g_deviceManagerMap;
51 std::map<std::string, std::shared_ptr<DmJSIInitCallback>> g_initCallbackMap;
52 std::map<std::string, std::shared_ptr<DmJSIDeviceStateCallback>> g_deviceStateCallbackMap;
53 std::map<std::string, std::shared_ptr<DmJSIDiscoverCallback>> g_discoverCallbackMap;
54 std::map<std::string, std::shared_ptr<DmJSIAuthenticateCallback>> g_authCallbackMap;
55 std::map<std::string, std::shared_ptr<DmJSICheckAuthCallback>> g_checkAuthCallbackMap;
56 std::map<std::string, std::shared_ptr<DmJSIDeviceManagerFaCallback>> g_dmfaCallbackMap;
57 
58 AuthAsyncCallbackInfo DeviceManagerModule::authAsyncCallbackInfo_;
59 AuthAsyncCallbackInfo DeviceManagerModule::verifyAsyncCallbackInfo_;
60 
GetDeviceManagerJSI(std::string & bundleName)61 DeviceManagerModule *DeviceManagerModule::GetDeviceManagerJSI(std::string &bundleName)
62 {
63     auto iter = g_deviceManagerMap.find(bundleName);
64     if (iter == g_deviceManagerMap.end()) {
65         return nullptr;
66     }
67     return iter->second;
68 }
69 
DeviceManagerModule()70 DeviceManagerModule::DeviceManagerModule() : DmNativeEvent()
71 {
72     LOGI("new DeviceManagerModule is success");
73 }
74 
~DeviceManagerModule()75 DeviceManagerModule::~DeviceManagerModule()
76 {
77 }
78 
OnRemoteDied()79 void DmJSIInitCallback::OnRemoteDied()
80 {
81     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
82     if (deviceManagerJSI == nullptr) {
83         LOGE("OnRemoteDied, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
84         return;
85     }
86     deviceManagerJSI->OnRemoteDied();
87 }
88 
OnRemoteDied()89 void DeviceManagerModule::OnRemoteDied()
90 {
91     OnEvent("serviceDie", 0, nullptr);
92 }
93 
OnDeviceOnline(const DmDeviceInfo & deviceInfo)94 void DmJSIDeviceStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo)
95 {
96     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
97     if (deviceManagerJSI == nullptr) {
98         LOGE("OnDeviceOnline, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
99         return;
100     }
101     deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::ONLINE, deviceInfo);
102 }
103 
OnDeviceReady(const DmDeviceInfo & deviceInfo)104 void DmJSIDeviceStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo)
105 {
106     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
107     if (deviceManagerJSI == nullptr) {
108         LOGE("OnDeviceOnline, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
109         return;
110     }
111     deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::READY, deviceInfo);
112 }
113 
OnDeviceOffline(const DmDeviceInfo & deviceInfo)114 void DmJSIDeviceStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo)
115 {
116     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
117     if (deviceManagerJSI == nullptr) {
118         LOGE("OnDeviceOffline, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
119         return;
120     }
121     deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::OFFLINE, deviceInfo);
122 }
123 
OnDeviceChanged(const DmDeviceInfo & deviceInfo)124 void DmJSIDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo)
125 {
126     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
127     if (deviceManagerJSI == nullptr) {
128         LOGE("OnDeviceChanged, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
129         return;
130     }
131     deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::CHANGE, deviceInfo);
132 }
133 
OnDeviceFound(uint16_t subscribeId,const DmDeviceInfo & deviceInfo)134 void DmJSIDiscoverCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo)
135 {
136     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
137     if (deviceManagerJSI == nullptr) {
138         LOGE("OnDeviceFound, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
139         return;
140     }
141 
142     LOGI("OnDeviceFound for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId);
143     deviceManagerJSI->OnDeviceFound(subscribeId, deviceInfo);
144 }
145 
OnDiscoveryFailed(uint16_t subscribeId,int32_t failedReason)146 void DmJSIDiscoverCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason)
147 {
148     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
149     if (deviceManagerJSI == nullptr) {
150         LOGE("OnDiscoverFailed, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
151         return;
152     }
153 
154     deviceManagerJSI->OnDiscoverFailed(subscribeId, failedReason);
155 }
156 
OnDiscoverySuccess(uint16_t subscribeId)157 void DmJSIDiscoverCallback::OnDiscoverySuccess(uint16_t subscribeId)
158 {
159     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
160     if (deviceManagerJSI == nullptr) {
161         LOGE("OnDiscoverySuccess, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
162         return;
163     }
164     LOGI("DiscoverySuccess for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId);
165 }
166 
OnAuthResult(const std::string & deviceId,const std::string & token,int32_t status,int32_t reason)167 void DmJSIAuthenticateCallback::OnAuthResult(const std::string &deviceId, const std::string &token,
168                                              int32_t status, int32_t reason)
169 {
170     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
171     if (deviceManagerJSI == nullptr) {
172         LOGE("OnAuthResult, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
173         return;
174     }
175     deviceManagerJSI->OnAuthResult(deviceId, token, status, reason);
176 }
177 
OnVerifyAuthResult(const std::string & deviceId,int32_t resultCode,int32_t flag)178 void DmJSICheckAuthCallback::OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag)
179 {
180     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
181     if (deviceManagerJSI == nullptr) {
182         LOGE("OnCheckAuthResult, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
183         return;
184     }
185     deviceManagerJSI->OnVerifyResult(deviceId, resultCode, flag);
186 }
187 
OnCall(const std::string & paramJson)188 void DmJSIDeviceManagerFaCallback::OnCall(const std::string &paramJson)
189 {
190     DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_);
191     if (deviceManagerJSI == nullptr) {
192         LOGE("OnCall, deviceManagerJSI not find for bundleName %s", bundleName_.c_str());
193         return;
194     }
195     deviceManagerJSI->OnDmfaCall(paramJson);
196 }
197 
IncreaseRefCount()198 void DmJSIDiscoverCallback::IncreaseRefCount()
199 {
200     uint32_t ret = pthread_mutex_init(&lock_, NULL);
201     if (ret != 0) {
202         LOGE("init mutex lock failed: %d.", ret);
203     }
204     pthread_mutex_lock(&lock_);
205     refCount_++;
206     pthread_mutex_unlock(&lock_);
207     LOGI("IncreaseRefCount: refCount_:%d.", refCount_);
208     ret = pthread_mutex_destroy(&lock_);
209     if (ret != 0) {
210         LOGE("destroy mutex lock failed: %d.", ret);
211     }
212 }
213 
DecreaseRefCount()214 void DmJSIDiscoverCallback::DecreaseRefCount()
215 {
216     uint32_t ret = pthread_mutex_init(&lock_, NULL);
217     if (ret != 0) {
218         LOGE("init mutex lock failed: %d.", ret);
219     }
220     pthread_mutex_lock(&lock_);
221     refCount_--;
222     pthread_mutex_unlock(&lock_);
223 
224     LOGI("DecreaseRefCount: refCount_:%d.", refCount_);
225     ret = pthread_mutex_destroy(&lock_);
226     if (ret != 0) {
227         LOGE("destroy mutex lock failed: %d.", ret);
228     }
229 }
230 
GetRefCount()231 int32_t DmJSIDiscoverCallback::GetRefCount()
232 {
233     return refCount_;
234 }
235 
OnDeviceStateChange(DmJSIDevStateChangeAction action,const DmDeviceInfo & deviceInfo)236 void DeviceManagerModule::OnDeviceStateChange(DmJSIDevStateChangeAction action, const DmDeviceInfo &deviceInfo)
237 {
238     JSIValue result = JSI::CreateObject();
239     JSI::SetNumberProperty(result, "action", (double)action);
240 
241     JSIValue device = JSI::CreateObject();
242     JSI::SetStringProperty(device, "deviceId", deviceInfo.deviceId);
243     JSI::SetStringProperty(device, "deviceName", deviceInfo.deviceName);
244     JSI::SetNumberProperty(device, "deviceTypeId", (double)deviceInfo.deviceTypeId);
245 
246     JSIValue param[2] = {result, device};
247     OnEvent("deviceStateChange", DM_JSI_ARGS_TWO, param);
248     JSI::ReleaseValueList(result, device, ARGS_END);
249 }
250 
OnDeviceFound(uint16_t subscribeId,const DmDeviceInfo & deviceInfo)251 void DeviceManagerModule::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo)
252 {
253     LOGI("OnDeviceFound for subscribeId %d", (int32_t)subscribeId);
254     JSIValue result = JSI::CreateObject();
255     JSI::SetNumberProperty(result, "subscribeId", (double)subscribeId);
256 
257     JSIValue device = JSI::CreateObject();
258     JSI::SetStringProperty(device, "deviceId", deviceInfo.deviceId);
259     JSI::SetStringProperty(device, "deviceName", deviceInfo.deviceName);
260     JSI::SetNumberProperty(device, "deviceTypeId", (double)deviceInfo.deviceTypeId);
261     LOGI("OnDeviceFound subscribeId %ld ", subscribeId);
262     LOGI("OnDeviceFound deviceId %s ", GetAnonyString(deviceInfo.deviceId));
263     LOGI("OnDeviceFound deviceName %s ", deviceInfo.deviceName);
264     LOGI("OnDeviceFound deviceTypeId %x ", deviceInfo.deviceTypeId);
265 
266     JSIValue param[2] = {result, device};
267     OnEvent("deviceFound", DM_JSI_ARGS_TWO, param);
268     JSI::ReleaseValueList(result, device, ARGS_END);
269 }
270 
OnDiscoverFailed(uint16_t subscribeId,int32_t failedReason)271 void DeviceManagerModule::OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason)
272 {
273     LOGI("OnDiscoverFailed for subscribeId %d", (int32_t)subscribeId);
274     JSIValue result = JSI::CreateObject();
275     JSI::SetNumberProperty(result, "subscribeId", (double)subscribeId);
276     JSIValue reason = JSI::CreateObject();
277     JSI::SetNumberProperty(reason, "reason", (double)failedReason);
278 
279     JSIValue param[2] = {result, reason};
280     OnEvent("discoverFail", DM_JSI_ARGS_TWO, param);
281     JSI::ReleaseValueList(result, reason, ARGS_END);
282 }
283 
OnDmfaCall(const std::string & paramJson)284 void DeviceManagerModule::OnDmfaCall(const std::string &paramJson)
285 {
286     LOGI("OnCall for paramJson");
287     JSIValue result = JSI::CreateObject();
288     JSI::SetStringProperty(result, "param", paramJson.c_str());
289 
290     JSIValue param[1] = {result};
291     OnEvent("dmFaCallback", DM_JSI_ARGS_ONE, param);
292     JSI::ReleaseValueList(result, ARGS_END);
293 }
294 
OnAuthResult(const std::string & deviceId,const std::string & token,int32_t status,int32_t reason)295 void DeviceManagerModule::OnAuthResult(const std::string &deviceId, const std::string &token,
296                                        int32_t status, int32_t reason)
297 {
298     LOGI("OnAuthResult for status: %d, reason: %d", status, reason);
299     JSIValue thisVar = authAsyncCallbackInfo_.thisVal_;
300     JSIValue success = JSI::GetNamedProperty(authAsyncCallbackInfo_.callback, CB_SUCCESS);
301     JSIValue fail = JSI::GetNamedProperty(authAsyncCallbackInfo_.callback, CB_FAIL);
302 
303     JSIValue errOne = JSI::CreateObject();
304     JSIValue errTwo = JSI::CreateObject();
305     JSIValue successOne = JSI::CreateObject();
306     JSIValue successTwo = JSI::CreateObject();
307 
308     if (status == DM_JSI_AUTH_REQUEST_FINISH) {
309         LOGI("OnAuthResult success");
310         JSI::SetStringProperty(successOne, "deviceId", deviceId.c_str());
311         JSIValue param[1] = {successOne};
312         AuthFuncParams* params = new AuthFuncParams();
313         params->handlerRef = success;
314         params->thisVarRef_ = thisVar;
315         params->args = param;
316         params->argsSize = DM_JSI_ARGS_ONE;
317         LOGI("OnAuthResult SuccessCallBack in.");
318         JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast<void *>(params));
319     } else {
320         LOGI("OnAuthResult failed");
321         JSI::SetNumberProperty(errOne, "code", (double)status);
322         JSI::SetNumberProperty(errTwo, "reason", (double)reason);
323         JSIValue param[2] = {errOne, errTwo};
324         AuthFuncParams* params = new AuthFuncParams();
325         params->handlerRef = fail;
326         params->thisVarRef_ = thisVar;
327         params->args = param;
328         params->argsSize = DM_JSI_ARGS_TWO;
329         LOGI("OnAuthResult FailCallBack in.");
330         JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast<void *>(params));
331     }
332     g_authCallbackMap.erase(bundleName_);
333     JSI::ReleaseValueList(thisVar, success, fail, errOne, errTwo, successOne, successTwo,
334                           authAsyncCallbackInfo_.thisVal_, authAsyncCallbackInfo_.callback, ARGS_END);
335 }
336 
OnVerifyResult(const std::string & deviceId,int32_t resultCode,int32_t flag)337 void DeviceManagerModule::OnVerifyResult(const std::string &deviceId, int32_t resultCode, int32_t flag)
338 {
339     LOGI("OnVerifyResult for resultCode: %d, flag: %d", resultCode, flag);
340     JSIValue thisVar = verifyAsyncCallbackInfo_.thisVal_;
341     JSIValue success = JSI::GetNamedProperty(verifyAsyncCallbackInfo_.callback, CB_SUCCESS);
342     JSIValue fail = JSI::GetNamedProperty(verifyAsyncCallbackInfo_.callback, CB_FAIL);
343 
344     JSIValue successOne = JSI::CreateObject();
345     JSIValue successTwo = JSI::CreateObject();
346     JSIValue errOne = JSI::CreateObject();
347 
348     if (resultCode == 0) {
349         LOGI("OnVerifyResult success");
350         JSI::SetStringProperty(successOne, "deviceId", deviceId.c_str());
351         JSI::SetNumberProperty(successTwo, "level", (double)flag);
352         JSIValue param[2] = {successOne, successTwo};
353         AuthFuncParams* params = new AuthFuncParams();
354         params->handlerRef = success;
355         params->thisVarRef_ = thisVar;
356         params->args = param;
357         params->argsSize = DM_JSI_ARGS_TWO;
358         LOGI("OnVerifyResult SuccessCallBack in.");
359         JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast<void *>(params));
360     } else {
361         LOGI("OnVerifyResult failed");
362         JSI::SetNumberProperty(errOne, "code", (double)resultCode);
363         JSIValue param[1] = {errOne};
364         AuthFuncParams* params = new AuthFuncParams();
365         params->handlerRef = fail;
366         params->thisVarRef_ = thisVar;
367         params->args = param;
368         params->argsSize = DM_JSI_ARGS_ONE;
369         LOGI("OnVerifyResult FailCallBack in.");
370         JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast<void *>(params));
371     }
372 
373     g_checkAuthCallbackMap.erase(bundleName_);
374     JSI::ReleaseValueList(thisVar, success, fail, successOne, successTwo, errOne,
375                           verifyAsyncCallbackInfo_.thisVal_, verifyAsyncCallbackInfo_.callback, ARGS_END);
376 }
377 
DeviceInfoToJsArray(const std::vector<DmDeviceInfo> & vecDevInfo,const int32_t idx,JSIValue & arrayResult)378 void DeviceManagerModule::DeviceInfoToJsArray(const std::vector<DmDeviceInfo> &vecDevInfo,
379                                               const int32_t idx, JSIValue &arrayResult)
380 {
381     bool status = false;
382     JSIValue result = JSI::CreateObject();
383     char *deviceId = const_cast<char *>(vecDevInfo[idx].deviceId);
384     char *deviceName = const_cast<char *>(vecDevInfo[idx].deviceName);
385 
386     JSI::SetStringProperty(result, "deviceId", deviceId);
387     JSI::SetStringProperty(result, "deviceName", deviceName);
388     JSI::SetNumberProperty(result, "deviceTypeId", (double)vecDevInfo[idx].deviceTypeId);
389 
390     status = JSI::SetPropertyByIndex(arrayResult, idx, result);
391     if (status == false) {
392         LOGE("DmDeviceInfo To JsArray set element error");
393     }
394     JSI::ReleaseValue(result);
395 }
396 
DmAuthParamToJsAuthParamy(const DmAuthParam & authParam,JSIValue & paramResult)397 void DeviceManagerModule::DmAuthParamToJsAuthParamy(const DmAuthParam &authParam, JSIValue &paramResult)
398 {
399     LOGI("DmAuthParamToJsAuthParamy in");
400     JSI::SetNumberProperty(paramResult, "authType", (double)authParam.authType);
401 
402     JSIValue extraInfo = JSI::CreateObject();
403     JSI::SetNumberProperty(extraInfo, "direction", (double)authParam.direction);
404     JSI::SetNumberProperty(extraInfo, "pinToken", (double)authParam.pinToken);
405     if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) {
406         JSI::SetNamedProperty(paramResult, "extraInfo", extraInfo);
407         return;
408     }
409     JSI::SetStringProperty(extraInfo, "packageName", authParam.packageName.c_str());
410     JSI::SetStringProperty(extraInfo, "appName", authParam.appName.c_str());
411     JSI::SetStringProperty(extraInfo, "appDescription", authParam.appDescription.c_str());
412     JSI::SetNumberProperty(extraInfo, "business", (double)authParam.business);
413     JSI::SetNumberProperty(extraInfo, "pincode", (double)authParam.pincode);
414     JSI::SetNamedProperty(paramResult, "extraInfo", extraInfo);
415     LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, packageName: %s", authParam.packageName.c_str());
416     LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, appName: %s", authParam.appName.c_str());
417     LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, appDescription: %s", authParam.appDescription.c_str());
418     LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, business: %d", authParam.business);
419     LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, pincode: %d", authParam.pincode);
420     LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, pinToken: %d", authParam.pinToken);
421 
422     size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen();
423     if (appIconLen > 0) {
424         uint8_t *appIcon = nullptr;
425         JSIValue appIconBuffer = JSI::CreateArrayBuffer(appIconLen, appIcon);
426         if (appIcon != nullptr &&
427             memcpy_s(appIcon, appIconLen, reinterpret_cast<const void*>(authParam.imageinfo.GetAppIcon()),
428                      appIconLen) == 0) {
429             JSIValue appIconArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY,
430                                                           appIconLen, appIconBuffer, 0);
431             JSI::SetNamedProperty(paramResult, "appIcon", appIconArray);
432         }
433     }
434 
435     size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen();
436     if (appThumbnailLen > 0) {
437         uint8_t *appThumbnail = nullptr;
438         JSIValue appThumbnailBuffer = JSI::CreateArrayBuffer(appThumbnailLen, appThumbnail);
439         if (appThumbnail != nullptr && memcpy_s(appThumbnail, appThumbnailLen,
440             reinterpret_cast<const void*>(authParam.imageinfo.GetAppThumbnail()), appThumbnailLen) == 0) {
441             JSIValue appThumbnailArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY,
442                                                                appThumbnailLen,
443                                                                appThumbnailBuffer, 0);
444             JSI::SetNamedProperty(paramResult, "appThumbnail", appThumbnailArray);
445         }
446     }
447 }
448 
JsObjectToInt(const JSIValue & object,const std::string & fieldStr)449 int32_t DeviceManagerModule::JsObjectToInt(const JSIValue &object,
450     const std::string &fieldStr)
451 {
452     double result = JSI::GetNumberProperty(object, fieldStr.c_str());
453     return (int32_t)result;
454 }
455 
JsObjectToBool(const JSIValue & object,const std::string & fieldStr)456 bool DeviceManagerModule::JsObjectToBool(const JSIValue &object,
457     const std::string &fieldStr)
458 {
459     bool result = JSI::GetBooleanProperty(object, fieldStr.c_str());
460     return result;
461 }
462 
JsObjectToString(const JSIValue & object,const std::string & fieldStr)463 char *DeviceManagerModule::JsObjectToString(const JSIValue &object,
464     const std::string &fieldStr)
465 {
466     char* str = JSI::GetStringProperty(object, fieldStr.c_str());
467     return str;
468 }
469 
JsToDmSubscribeInfo(const JSIValue & object,DmSubscribeInfo & info)470 int32_t DeviceManagerModule::JsToDmSubscribeInfo(const JSIValue &object, DmSubscribeInfo &info)
471 {
472     int32_t subscribeId = -1;
473     subscribeId = JsObjectToInt(object, "subscribeId");
474     if (subscribeId < 0 || subscribeId > DM_JSI_SUB_ID_MAX) {
475         LOGE("DeviceManagerModule::JsToDmSubscribeInfo, subscribeId error, subscribeId: %d ", subscribeId);
476         return -1;
477     }
478     info.subscribeId = (uint16_t)subscribeId;
479 
480     int32_t mode = -1;
481     mode = JsObjectToInt(object, "mode");
482     info.mode = (DmDiscoverMode)mode;
483 
484     int32_t medium = -1;
485     medium = JsObjectToInt(object, "medium");
486     info.medium = (DmExchangeMedium)medium;
487 
488     int32_t freq = -1;
489     freq = JsObjectToInt(object, "freq");
490     info.freq = (DmExchangeFreq)freq;
491 
492     info.isSameAccount = JsObjectToBool(object, "isSameAccount");
493     info.isWakeRemote = JsObjectToBool(object, "isWakeRemote");
494 
495     int32_t capability = -1;
496     capability = JsObjectToInt(object, "capability");
497     if (capability == DM_JSI_SUBSCRIBE_CAPABILITY_DDMP || capability == DM_JSI_SUBSCRIBE_CAPABILITY_OSD) {
498         (void)strncpy_s(info.capability, sizeof(info.capability), DM_CAPABILITY_OSD, strlen(DM_CAPABILITY_OSD));
499     }
500     return 0;
501 }
502 
JsToDmDeviceInfo(const JSIValue & object,DmDeviceInfo & info)503 void DeviceManagerModule::JsToDmDeviceInfo(const JSIValue &object,
504                                            DmDeviceInfo &info)
505 {
506     int ret = strcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, JsObjectToString(object, "deviceId"));
507     if (ret != DM_OK) {
508         LOGE("JsToDmDeviceInfo error: copy deviceId failed %d", ret);
509         return;
510     }
511     ret = strcpy_s(info.deviceName, DM_MAX_DEVICE_NAME_LEN, JsObjectToString(object, "deviceName"));
512     if (ret != DM_OK) {
513         LOGE("JsToDmDeviceInfo error: copy deviceName failed %d", ret);
514         return;
515     }
516     uint16_t deviceTypeId = -1;
517     deviceTypeId = (uint16_t)JsObjectToInt(object, "deviceTypeId");
518     info.deviceTypeId = deviceTypeId;
519 }
520 
JsToDmAppImageInfoAndDmExtra(const JSIValue & object,DmAppImageInfo & appImageInfo,std::string & extra,int32_t & authType)521 void DeviceManagerModule::JsToDmAppImageInfoAndDmExtra(const JSIValue &object,
522     DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType)
523 {
524     LOGI("JsToDmAppImageInfoAndDmExtra in.");
525     int32_t authTypeTemp = -1;
526     authTypeTemp = (int32_t)JsObjectToInt(object, "authType");
527     authType = authTypeTemp;
528 
529     uint8_t *appIconBufferPtr = nullptr;
530     int32_t appIconBufferLen = 0;
531     JsToDmBuffer(object, "appIcon", &appIconBufferPtr, appIconBufferLen);
532 
533     uint8_t *appThumbnailBufferPtr = nullptr;
534     int32_t appThumbnailBufferLen = 0;
535     JsToDmBuffer(object, "appThumbnail", &appThumbnailBufferPtr, appThumbnailBufferLen);
536 
537     appImageInfo.Reset(appIconBufferPtr, appIconBufferLen, appThumbnailBufferPtr, appThumbnailBufferLen);
538     if (appIconBufferPtr != nullptr) {
539         free(appIconBufferPtr);
540         appIconBufferPtr = nullptr;
541     }
542     if (appThumbnailBufferPtr != nullptr) {
543         free(appThumbnailBufferPtr);
544         appThumbnailBufferPtr = nullptr;
545     }
546 
547     nlohmann::json jsonObj;
548     jsonObj[AUTH_TYPE] = authType;
549     std::string extraInfo = "extraInfo";
550 
551     JsToJsonObject(object, extraInfo, jsonObj);
552     extra = jsonObj.dump();
553     LOGI("appIconLen %d, appThumbnailLen %d", appIconBufferLen, appThumbnailBufferLen);
554 }
555 
JsToDmBuffer(const JSIValue & object,const std::string & fieldStr,uint8_t ** bufferPtr,int32_t & bufferLen)556 void DeviceManagerModule::JsToDmBuffer(const JSIValue &object,
557     const std::string &fieldStr, uint8_t **bufferPtr, int32_t &bufferLen)
558 {
559     LOGI("JsToDmBuffer in.");
560     JSIValue field = JSI::GetNamedProperty(object, fieldStr.c_str());
561     if (field == JSI::CreateUndefined() || field == JSI::CreateNull()) {
562         LOGE("devicemanager JSI js to str no property: %s", fieldStr.c_str());
563         return;
564     }
565     OHOS::ACELite::TypedArrayType type = TypedArrayType::JSI_UINT8_ARRAY;
566     size_t length = 0;
567     JSIValue buffer = nullptr;
568     size_t offset = 0;
569     uint8_t *data = nullptr;
570     data = JSI::GetTypedArrayInfo(field, type, length, buffer, offset);
571     if (type != TypedArrayType::JSI_UINT8_ARRAY || length == 0 || data == nullptr) {
572         LOGE("Invalid AppIconInfo");
573         return;
574     }
575     *bufferPtr = static_cast<uint8_t*>(calloc(sizeof(uint8_t), length));
576     if (*bufferPtr == nullptr) {
577         LOGE("low memory, calloc return nullptr, length is %d, filed %s", length, fieldStr.c_str());
578         return;
579     }
580     if (memcpy_s(*bufferPtr, length, data, length) != 0) {
581         LOGE("memcpy_s failed, filed %s", fieldStr.c_str());
582         free(*bufferPtr);
583         *bufferPtr = nullptr;
584         return;
585     }
586     bufferLen = length;
587 }
588 
JsToJsonObject(const JSIValue & object,const std::string & fieldStr,nlohmann::json & jsonObj)589 void DeviceManagerModule::JsToJsonObject(const JSIValue &object,
590     const std::string &fieldStr, nlohmann::json &jsonObj)
591 {
592     LOGI("JsToJsonObject in.");
593     JSIValue jsonField = JSI::GetNamedProperty(object, fieldStr.c_str());
594     if (jsonField == JSI::CreateUndefined() || jsonField == JSI::CreateNull()) {
595         LOGE("devicemanager JSI js to str no property: %s", fieldStr.c_str());
596         return;
597     }
598 
599     JSIValue jsProNameList = nullptr;
600     uint32_t jsProCount = 0;
601     jsProNameList = JSI::GetObjectKeys(jsonField);
602     jsProCount = JSI::GetArrayLength(jsProNameList);
603     LOGI("Property size = %d.", jsProCount);
604 
605     JSIValue jsProName = nullptr;
606     JSIValue jsProValue = nullptr;
607     for (uint32_t index = 0; index < jsProCount; index++) {
608         jsProName = JSI::GetPropertyByIndex(jsProNameList, index);
609         std::string strProName = JSI::ValueToString(jsProName);
610         jsProValue = JSI::GetNamedProperty(jsonField, strProName.c_str());
611         if (JSI::ValueIsString(jsProValue)) {
612             std::string natValue = JSI::ValueToString(jsProValue);
613             LOGI("Property name = %s, string, value = %s", strProName.c_str(), natValue.c_str());
614             jsonObj[strProName] = natValue;
615         }
616         if (JSI::ValueIsBoolean(jsProValue)) {
617             bool elementValue = JSI::ValueToBoolean(jsProValue);
618             LOGI("Property name = %s, boolean, value = %d.", strProName.c_str(), elementValue);
619             jsonObj[strProName] = elementValue;
620         }
621         if (JSI::ValueIsNumber(jsProValue)) {
622             int32_t elementValue = 0;
623             elementValue = (int32_t)JSI::ValueToNumber(jsProValue);
624             jsonObj[strProName] = elementValue;
625             LOGI("Property name = %s, number, value = %d.", strProName.c_str(), elementValue);
626         }
627     }
628 }
629 
JsToDmAuthInfo(const JSIValue & object,std::string & extra)630 void DeviceManagerModule::JsToDmAuthInfo(const JSIValue &object, std::string &extra)
631 {
632     LOGI("%s called.", __func__);
633     int32_t authType = -1;
634     int32_t token = -1;
635 
636     authType = JsObjectToInt(object, "authType");
637     token = JsObjectToInt(object, "token");
638 
639     nlohmann::json jsonObj;
640     jsonObj[AUTH_TYPE] = authType;
641     if (authType == DM_AUTH_TYPE_PINCODE) {
642         jsonObj[PIN_TOKEN] = token;
643     } else {
644         jsonObj[TOKEN] = token;
645     }
646     JsToJsonObject(object, "extraInfo", jsonObj);
647     extra = jsonObj.dump();
648 }
649 
CreateDmCallback(std::string & bundleName,std::string & eventType)650 void DeviceManagerModule::CreateDmCallback(std::string &bundleName, std::string &eventType)
651 {
652     LOGI("CreateDmCallback for bundleName %s eventType %s", bundleName.c_str(), eventType.c_str());
653     if (eventType == DM_JSI_EVENT_DEVICE_STATE_CHANGE) {
654         auto iter = g_deviceStateCallbackMap.find(bundleName);
655         if (iter == g_deviceStateCallbackMap.end()) {
656             auto callback = std::make_shared<DmJSIDeviceStateCallback>(bundleName);
657             std::string extra = "";
658             int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback(
659                 bundleName, extra, callback);
660             if (ret != 0) {
661                 LOGE("RegisterDevStateCallback failed for bundleName %s", bundleName.c_str());
662                 return;
663             }
664             g_deviceStateCallbackMap[bundleName] = callback;
665         }
666         return;
667     }
668 
669     if (eventType == DM_JSI_EVENT_DEVICE_FOUND || eventType == DM_JSI_EVENT_DEVICE_DISCOVER_FAIL) {
670         std::shared_ptr<DmJSIDiscoverCallback> discoverCallback = nullptr;
671         auto iter = g_discoverCallbackMap.find(bundleName);
672         if (iter == g_discoverCallbackMap.end()) {
673             auto callback = std::make_shared<DmJSIDiscoverCallback>(bundleName);
674             g_discoverCallbackMap[bundleName] = callback;
675             discoverCallback = callback;
676         } else {
677             discoverCallback = iter->second;
678         }
679 
680         discoverCallback->IncreaseRefCount();
681         return;
682     }
683 
684     if (eventType == DM_JSI_EVENT_DMFA_CALLBACK) {
685         auto iter = g_dmfaCallbackMap.find(bundleName);
686         if (iter == g_dmfaCallbackMap.end()) {
687             auto callback = std::make_shared<DmJSIDeviceManagerFaCallback>(bundleName);
688             int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(
689                 bundleName, callback);
690             if (ret != 0) {
691                 LOGE("RegisterDeviceManagerFaCallback failed for bundleName %s", bundleName.c_str());
692                 return;
693             }
694             g_dmfaCallbackMap[bundleName] = callback;
695         }
696         return;
697     }
698 }
699 
ReleaseDmCallback(std::string & bundleName,std::string & eventType)700 void DeviceManagerModule::ReleaseDmCallback(std::string &bundleName, std::string &eventType)
701 {
702     if (eventType == DM_JSI_EVENT_DEVICE_STATE_CHANGE) {
703         auto iter = g_deviceStateCallbackMap.find(bundleName);
704         if (iter == g_deviceStateCallbackMap.end()) {
705             LOGE("ReleaseDmCallback: cannot find stateCallback for bundleName %s", bundleName.c_str());
706             return;
707         }
708         int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnRegisterDevStateCallback(bundleName);
709         if (ret != 0) {
710             LOGE("RegisterDevStateCallback failed for bundleName %s", bundleName.c_str());
711             return;
712         }
713         g_deviceStateCallbackMap.erase(bundleName);
714         return;
715     }
716 
717     if (eventType == DM_JSI_EVENT_DEVICE_FOUND || eventType == DM_JSI_EVENT_DEVICE_DISCOVER_FAIL) {
718         std::shared_ptr<DmJSIDiscoverCallback> discoverCallback = nullptr;
719         auto iter = g_discoverCallbackMap.find(bundleName);
720         if (iter == g_discoverCallbackMap.end()) {
721             return;
722         }
723 
724         discoverCallback = iter->second;
725         discoverCallback->DecreaseRefCount();
726         if (discoverCallback->GetRefCount() == 0) {
727             g_discoverCallbackMap.erase(bundleName);
728         }
729         return;
730     }
731 
732     if (eventType == DM_JSI_EVENT_DMFA_CALLBACK) {
733         auto iter = g_dmfaCallbackMap.find(bundleName);
734         if (iter == g_dmfaCallbackMap.end()) {
735             LOGE("cannot find dmFaCallback for bundleName %s", bundleName.c_str());
736             return;
737         }
738         int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(
739             bundleName);
740         if (ret != 0) {
741             LOGE("RegisterDevStateCallback failed for bundleName %s", bundleName.c_str());
742             return;
743         }
744         g_dmfaCallbackMap.erase(bundleName);
745         return;
746     }
747 }
748 
AuthRsultVerifyInfoAsyncWorkFunc(void * data)749 void DeviceManagerModule::AuthRsultVerifyInfoAsyncWorkFunc(void *data)
750 {
751     LOGI("AuthRsultVerifyInfoAsyncWorkFunc in ............");
752     AuthFuncParams* params = reinterpret_cast<AuthFuncParams *>(data);
753     JSI::CallFunction(params->handlerRef, params->thisVarRef_, params->args, params->argsSize);
754 }
755 
UnAuthenticateDevice(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)756 JSIValue DeviceManagerModule::UnAuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
757 {
758     LOGI("UnAuthenticateDevice in");
759     if (argsSize < 1) {
760         LOGE("1 argument is required.");
761         return JSI::CreateNull();
762     }
763     if (!JSI::ValueIsObject(args[0])) {
764         LOGE("a object is required.");
765         return JSI::CreateNull();
766     }
767     std::string bundleName = GetJSIAppBundleName();
768     std::string deviceId = JSI::GetStringProperty(args[0], "deviceId");
769     LOGI("UnAuthenticateDevice deviceId = %s", GetAnonyString(deviceId.c_str()));
770     int32_t ret = 0;
771     ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnAuthenticateDevice(bundleName, deviceId);
772     if (ret != 0) {
773         LOGI("UnAuthenticateDevice for bundleName %s failed, ret %d", bundleName.c_str(), ret);
774     }
775 
776     JSIValue result = JSI::CreateObject();
777     JSI::SetNumberProperty(result, "ret", (double)ret);
778     return result;
779 }
780 
GetLocalDeviceInfoSync(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)781 JSIValue DeviceManagerModule::GetLocalDeviceInfoSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
782 {
783     LOGI("GetLocalDeviceInfoSync in");
784 
785     std::string bundleName = GetJSIAppBundleName();
786     DmDeviceInfo deviceInfo;
787     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceInfo(bundleName, deviceInfo);
788     if (ret != 0) {
789         LOGE("GetLocalDeviceInfoSync for failed, ret %d", ret);
790         return JSI::CreateNull();
791     }
792     LOGI("DeviceManager::GetLocalDeviceInfoSync deviceId:%s deviceName:%s deviceTypeId:%d ",
793          GetAnonyString(deviceInfo.deviceId), deviceInfo.deviceName, deviceInfo.deviceTypeId);
794     JSIValue result = JSI::CreateObject();
795     char *deviceId = const_cast<char *>(deviceInfo.deviceId);
796     char *deviceName = const_cast<char *>(deviceInfo.deviceName);
797 
798     JSI::SetStringProperty(result, "deviceId", deviceId);
799     JSI::SetStringProperty(result, "deviceName", deviceName);
800     JSI::SetNumberProperty(result, "deviceTypeId", (double)deviceInfo.deviceTypeId);
801     return result;
802 }
803 
SetUserOperationSync(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)804 JSIValue DeviceManagerModule::SetUserOperationSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
805 {
806     LOGI("SetUserOperationSync in");
807     if (argsSize < 1) {
808         LOGE("1 argument is required.");
809         return JSI::CreateNull();
810     }
811 
812     if (!JSI::ValueIsNumber(args[0])) {
813         LOGE("a Number is required.");
814         return JSI::CreateNull();
815     }
816 
817     std::string bundleName = GetJSIAppBundleName();
818     int32_t action = 0;
819     action = static_cast<int32_t>(JSI::ValueToNumber(args[0]));
820 
821     LOGI("SetUserOperation action %d", action);
822 
823     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().SetUserOperation(bundleName, action);
824     if (ret != 0) {
825         LOGE("SetUserOperation for bundleName %s failed, ret %d",
826             bundleName.c_str(), ret);
827         return JSI::CreateNull();
828     }
829     return JSI::CreateNull();
830 }
831 
GetAuthenticationParamSync(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)832 JSIValue DeviceManagerModule::GetAuthenticationParamSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
833 {
834     LOGI("GetAuthenticationParamSync in");
835     std::string bundleName = GetJSIAppBundleName();
836     JSIValue resultParam = JSI::CreateObject();
837     DmAuthParam authParam;
838     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetFaParam(bundleName, authParam);
839     if (ret != 0) {
840         LOGE("GetAuthenticationParam for %s failed, ret %d",
841             bundleName.c_str(), ret);
842         return JSI::CreateNull();
843     }
844 
845     DmAuthParamToJsAuthParamy(authParam, resultParam);
846     return resultParam;
847 }
848 
GetTrustedDeviceListSync(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)849 JSIValue DeviceManagerModule::GetTrustedDeviceListSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
850 {
851     LOGI("GetTrustedDeviceList in");
852     JSIValue array = JSI::CreateNull();
853     std::string extra = "";
854     std::vector<DmDeviceInfo> devList;
855     std::string bundleName = GetJSIAppBundleName();
856 
857     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(
858         bundleName, extra, devList);
859     if (ret != 0) {
860         LOGE("GetTrustedDeviceList for bundleName %s failed, ret %d",
861              bundleName.c_str(), ret);
862         return array;
863     }
864     if (devList.size() > 0) {
865         bool isArray = false;
866         array = JSI::CreateArray(devList.size());
867         isArray = JSI::ValueIsArray(array);
868         if (isArray == false) {
869             LOGE("JSI_create_array fail");
870         }
871 
872         for (size_t i = 0; i != devList.size(); ++i) {
873             DeviceInfoToJsArray(devList, i, array);
874         }
875     } else {
876         LOGE("devList is null");
877     }
878 
879     return array;
880 }
881 
StartDeviceDiscoverSync(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)882 JSIValue DeviceManagerModule::StartDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
883 {
884     LOGI("StartDeviceDiscoverSync in");
885     std::string bundleName = GetJSIAppBundleName();
886 
887     if (argsSize < 1) {
888         LOGE("1 argument is required.");
889         return JSI::CreateNull();
890     }
891 
892     if (!JSI::ValueIsObject(args[0])) {
893         LOGE("a object is required.");
894         return JSI::CreateNull();
895     }
896 
897     std::shared_ptr<DmJSIDiscoverCallback> discoverCallback = nullptr;
898     auto iter = g_discoverCallbackMap.find(bundleName);
899     if (iter == g_discoverCallbackMap.end()) {
900         discoverCallback = std::make_shared<DmJSIDiscoverCallback>(bundleName);
901         g_discoverCallbackMap[bundleName] = discoverCallback;
902     } else {
903         discoverCallback = iter->second;
904     }
905     DmSubscribeInfo subInfo;
906     int32_t res = JsToDmSubscribeInfo(args[0], subInfo);
907     if (res != 0) {
908         LOGE("Wrong subscribeId.");
909         return JSI::CreateNull();
910     }
911 
912     LOGI("subInfo %d, %d, %d, %d, %d, %d, %s",
913          subInfo.subscribeId,
914          subInfo.mode,
915          subInfo.medium, subInfo.freq, subInfo.isSameAccount,
916          subInfo.isWakeRemote, subInfo.capability);
917     std::string extra = "";
918     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().StartDeviceDiscovery(bundleName,
919         subInfo, extra, discoverCallback);
920     if (ret != 0) {
921         LOGE("StartDeviceDiscovery for bundleName %s failed, ret %d",
922             bundleName.c_str(), ret);
923         return JSI::CreateNull();
924     }
925     return JSI::CreateNull();
926 }
927 
StopDeviceDiscoverSync(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)928 JSIValue DeviceManagerModule::StopDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
929 {
930     LOGI("StopDeviceDiscoverSync in");
931     std::string bundleName = GetJSIAppBundleName();
932 
933     if (argsSize < 1) {
934         LOGE("1 argument is required.");
935         return JSI::CreateNull();
936     }
937 
938     if (!JSI::ValueIsNumber(args[0])) {
939         LOGE("a Number is required.");
940         return JSI::CreateNull();
941     }
942 
943     int16_t subscribeId = 0;
944     subscribeId = static_cast<int16_t>(JSI::ValueToNumber(args[0]));
945     LOGI("subscribeId %d", subscribeId);
946     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().StopDeviceDiscovery(bundleName, subscribeId);
947     if (ret != 0) {
948         LOGE("StopDeviceDiscovery for bundleName %s failed, ret %d",
949             bundleName.c_str(), ret);
950         return JSI::CreateNull();
951     }
952     return JSI::CreateNull();
953 }
954 
AuthenticateDevice(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)955 JSIValue DeviceManagerModule::AuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
956 {
957     LOGI("AuthenticateDevice in");
958     std::string bundleName = GetJSIAppBundleName();
959     if (argsSize < DM_JSI_ARGS_THREE) {
960         LOGE("3 argument is required.");
961         return JSI::CreateNull();
962     }
963 
964     if (!JSI::ValueIsObject(args[0])) {
965         LOGE("a object is required.");
966         return JSI::CreateNull();
967     }
968 
969     if (!JSI::ValueIsObject(args[1])) {
970         LOGE("a object is required.");
971         return JSI::CreateNull();
972     }
973 
974     authAsyncCallbackInfo_.thisVal_ = JSI::AcquireValue(thisVal);
975     authAsyncCallbackInfo_.callback = JSI::AcquireValue(args[DM_JSI_ARGS_TWO]);
976 
977     std::shared_ptr<DmJSIAuthenticateCallback> authCallback = nullptr;
978     auto iter = g_authCallbackMap.find(bundleName);
979     if (iter == g_authCallbackMap.end()) {
980         authCallback = std::make_shared<DmJSIAuthenticateCallback>(bundleName);
981         g_authCallbackMap[bundleName] = authCallback;
982     } else {
983         authCallback = iter->second;
984     }
985     DmDeviceInfo deviceInfo;
986     JsToDmDeviceInfo(args[0], deviceInfo);
987 
988     LOGI("deviceInfo %s, %s, %d", GetAnonyString(deviceInfo.deviceId),
989         deviceInfo.deviceName, deviceInfo.deviceTypeId);
990     DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0);
991     std::string extra;
992     JsToDmAppImageInfoAndDmExtra(args[1], appImageInfo, extra, authAsyncCallbackInfo_.authType);
993 
994     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().AuthenticateDevice(
995         bundleName, 1, deviceInfo, extra, authCallback);
996     if (ret != 0) {
997         LOGE("AuthenticateDevice for bundleName %s failed, ret %d",
998             bundleName.c_str(), ret);
999     }
1000 
1001     return JSI::CreateUndefined();
1002 }
1003 
VerifyAuthInfo(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)1004 JSIValue DeviceManagerModule::VerifyAuthInfo(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
1005 {
1006     LOGI("VerifyAuthInfo in");
1007     std::string bundleName = GetJSIAppBundleName();
1008     if (argsSize < DM_JSI_ARGS_TWO) {
1009         LOGE("2 argument is required.");
1010         return JSI::CreateNull();
1011     }
1012 
1013     if (!JSI::ValueIsObject(args[0])) {
1014         LOGE("a object is required.");
1015         return JSI::CreateNull();
1016     }
1017 
1018     verifyAsyncCallbackInfo_.thisVal_ = JSI::AcquireValue(thisVal);
1019     verifyAsyncCallbackInfo_.callback = JSI::AcquireValue(args[1]);
1020 
1021     std::shared_ptr<DmJSICheckAuthCallback> verifyCallback = nullptr;
1022     auto iter = g_checkAuthCallbackMap.find(bundleName);
1023     if (iter == g_checkAuthCallbackMap.end()) {
1024         verifyCallback = std::make_shared<DmJSICheckAuthCallback>(bundleName);
1025         g_checkAuthCallbackMap[bundleName] = verifyCallback;
1026     } else {
1027         verifyCallback = iter->second;
1028     }
1029     std::string authParam;
1030     JsToDmAuthInfo(args[0], authParam);
1031     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().VerifyAuthentication(bundleName,
1032         authParam, verifyCallback);
1033     if (ret != 0) {
1034         LOGE("VerifyAuthInfo for bundleName %s failed, ret %d",
1035             bundleName.c_str(), ret);
1036     }
1037     return JSI::CreateUndefined();
1038 }
1039 
JsOn(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)1040 JSIValue DeviceManagerModule::JsOn(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
1041 {
1042     LOGI("JsOn in");
1043     std::string bundleName = GetJSIAppBundleName();
1044     if (argsSize < DM_JSI_ARGS_TWO) {
1045         LOGE("2 argument is required.");
1046         return JSI::CreateNull();
1047     }
1048     if (!JSI::ValueIsString(args[0])) {
1049         LOGE("a string is required.");
1050         return JSI::CreateNull();
1051     }
1052     if (!JSI::ValueIsFunction(args[1])) {
1053         LOGE("a FUNC is required.");
1054         return JSI::CreateNull();
1055     }
1056     std::string eventType = JSI::ValueToString(args[0]);
1057 
1058     LOGI("JsOn for bundleName %s, eventType %s ", bundleName.c_str(),
1059         eventType.c_str());
1060     std::shared_ptr<DmNativeEvent> DmNativeEventobj = std::make_shared<DmNativeEvent>(thisVal);
1061     DmNativeEventobj->On(eventType, args[1], thisVal);
1062     CreateDmCallback(bundleName, eventType);
1063 
1064     return JSI::CreateUndefined();
1065 }
1066 
JsOff(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)1067 JSIValue DeviceManagerModule::JsOff(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
1068 {
1069     LOGI("JsOff in");
1070     std::string bundleName = GetJSIAppBundleName();
1071 
1072     if (!JSI::ValueIsString(args[0])) {
1073         LOGE("a string is required.");
1074         return JSI::CreateNull();
1075     }
1076 
1077     std::string eventType = JSI::ValueToString(args[0]);
1078 
1079     LOGI("JsOff for bundleName %s, eventType %s ", bundleName.c_str(),
1080         eventType.c_str());
1081 
1082     DmNativeEvent* DmNativeEventobj = new DmNativeEvent();
1083     DmNativeEventobj->Off(eventType);
1084     delete(DmNativeEventobj);
1085     ReleaseDmCallback(bundleName, eventType);
1086 
1087     return JSI::CreateUndefined();
1088 }
1089 
ReleaseDeviceManager(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)1090 JSIValue DeviceManagerModule::ReleaseDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
1091 {
1092     LOGI("ReleaseDeviceManager in");
1093     std::string bundleName = GetJSIAppBundleName();
1094     LOGI("ReleaseDeviceManager for bundleName %s", bundleName.c_str());
1095 
1096     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnInitDeviceManager(bundleName);
1097     if (ret != 0) {
1098         LOGE("ReleaseDeviceManager for bundleName %s failed, ret %d",
1099             bundleName.c_str(), ret);
1100         JSIValue result = JSI::CreateNumber((double)ret);
1101         return result;
1102     }
1103 
1104     g_deviceManagerMap.erase(bundleName);
1105     g_initCallbackMap.erase(bundleName);
1106     g_deviceStateCallbackMap.erase(bundleName);
1107     g_discoverCallbackMap.erase(bundleName);
1108     g_authCallbackMap.erase(bundleName);
1109     g_checkAuthCallbackMap.erase(bundleName);
1110 
1111     return JSI::CreateUndefined();
1112 }
1113 
CreateDeviceManager(const JSIValue thisVal,const JSIValue * args,uint8_t argsSize)1114 JSIValue DeviceManagerModule::CreateDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize)
1115 {
1116     if (argsSize < 1) {
1117         LOGE("1 argument is required.");
1118         return JSI::CreateNull();
1119     }
1120 
1121     if (!JSI::ValueIsString(args[0])) {
1122         LOGE("a string is required.");
1123         return JSI::CreateNull();
1124     }
1125     std::string bundleName = GetJSIAppBundleName();
1126     LOGI("CreateDeviceManager for bundleName is %s", bundleName.c_str());
1127 
1128     if (DeviceManagerModule::GetDeviceManagerJSI(bundleName) != nullptr) {
1129         LOGI("CreateDeviceManager repeat for bundleName %s", bundleName.c_str());
1130         return JSI::CreateNull();
1131     }
1132 
1133     DeviceManagerModule *obj = new DeviceManagerModule();
1134     obj->bundleName_ = bundleName;
1135     g_deviceManagerMap[bundleName] = obj;
1136 
1137     int32_t ret = 0;
1138     std::shared_ptr<DmJSIInitCallback> initCallback = std::make_shared<DmJSIInitCallback>(bundleName);
1139     ret = OHOS::DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(bundleName, initCallback);
1140     if (ret == 0) {
1141         LOGI("InitDeviceManager for bundleName %s success", bundleName.c_str());
1142         JSIValue success = JSI::GetNamedProperty(args[1], CB_SUCCESS);
1143         JSIValue data = JSI::CreateObject();
1144         std::string str = "InitDeviceManager success";
1145         JSI::SetStringProperty(data, "data", str.c_str());
1146         JSI::CallFunction(success, thisVal, &data, 1);
1147     }
1148     if (ret != 0) {
1149         LOGI("InitDeviceManager for bundleName %s fail", bundleName.c_str());
1150         JSIValue fail = JSI::GetNamedProperty(args[1], CB_FAIL);
1151         JSIValue err = JSI::CreateObject();
1152         std::string str = "InitDeviceManager fail";
1153         JSI::SetStringProperty(err, "err", str.c_str());
1154         JSI::CallFunction(fail, thisVal, &err, 1);
1155     }
1156     return JSI::CreateNull();
1157 }
1158 
GetJSIAppBundleName()1159 char *DeviceManagerModule::GetJSIAppBundleName()
1160 {
1161     JSAbility *g_targetJSAbility = new JSAbility();
1162     const char *pname = g_targetJSAbility->GetPackageName();
1163     char *packageName = new char[strlen(pname)+1];
1164     int ret = strcpy_s(packageName, strlen(pname)+1, pname);
1165     if (ret != DM_OK) {
1166         LOGE("GetJSIAppBundleName error: copy BundleName failed %d", ret);
1167         delete(g_targetJSAbility);
1168         delete[] packageName;
1169         return nullptr;
1170     }
1171     delete(g_targetJSAbility);
1172     return packageName;
1173 }
1174 
InitDeviceManagerModule(JSIValue exports)1175 void InitDeviceManagerModule(JSIValue exports)
1176 {
1177     JSI::SetModuleAPI(exports, "createDeviceManager", DeviceManagerModule::CreateDeviceManager);
1178     JSI::SetModuleAPI(exports, "getTrustedDeviceListSync", DeviceManagerModule::GetTrustedDeviceListSync);
1179     JSI::SetModuleAPI(exports, "release", DeviceManagerModule::ReleaseDeviceManager);
1180     JSI::SetModuleAPI(exports, "startDeviceDiscovery", DeviceManagerModule::StartDeviceDiscoverSync);
1181     JSI::SetModuleAPI(exports, "stopDeviceDiscovery", DeviceManagerModule::StopDeviceDiscoverSync);
1182     JSI::SetModuleAPI(exports, "authenticateDevice", DeviceManagerModule::AuthenticateDevice);
1183     JSI::SetModuleAPI(exports, "verifyAuthInfo", DeviceManagerModule::VerifyAuthInfo);
1184     JSI::SetModuleAPI(exports, "setUserOperation", DeviceManagerModule::SetUserOperationSync);
1185     JSI::SetModuleAPI(exports, "getAuthenticationParam", DeviceManagerModule::GetAuthenticationParamSync);
1186     JSI::SetModuleAPI(exports, "on", DeviceManagerModule::JsOn);
1187     JSI::SetModuleAPI(exports, "off", DeviceManagerModule::JsOff);
1188     JSI::SetModuleAPI(exports, "getLocalDeviceInfoSync", DeviceManagerModule::GetLocalDeviceInfoSync);
1189     JSI::SetModuleAPI(exports, "unAuthenticateDevice", DeviceManagerModule::UnAuthenticateDevice);
1190 }
1191 }
1192 }