• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2023 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 
18 #include <securec.h>
19 #include <uv.h>
20 #include <mutex>
21 
22 #include "device_manager.h"
23 #include "dm_constants.h"
24 #include "dm_device_info.h"
25 #include "dm_log.h"
26 #include "ipc_skeleton.h"
27 #include "js_native_api.h"
28 #include "tokenid_kit.h"
29 #include "nlohmann/json.hpp"
30 
31 using namespace OHOS::DistributedHardware;
32 
33 namespace {
34 #define GET_PARAMS(env, info, num)    \
35     size_t argc = num;                \
36     napi_value argv[num] = {nullptr}; \
37     napi_value thisVar = nullptr;     \
38     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr))
39 
40 const std::string DM_NAPI_EVENT_DEVICE_STATE_CHANGE = "deviceStateChange";
41 const std::string DM_NAPI_EVENT_DEVICE_FOUND = "deviceFound";
42 const std::string DM_NAPI_EVENT_DEVICE_DISCOVERY_FAIL = "discoveryFail";
43 const std::string DM_NAPI_EVENT_DEVICE_PUBLISH_SUCCESS = "publishSuccess";
44 const std::string DM_NAPI_EVENT_DEVICE_PUBLISH_FAIL = "publishFail";
45 const std::string DM_NAPI_EVENT_DEVICE_SERVICE_DIE = "serviceDie";
46 const std::string DEVICE_MANAGER_NAPI_CLASS_NAME = "DeviceManager";
47 const std::string DM_NAPI_EVENT_UI_STATE_CHANGE = "uiStateChange";
48 
49 const int32_t DM_NAPI_ARGS_ZERO = 0;
50 const int32_t DM_NAPI_ARGS_ONE = 1;
51 const int32_t DM_NAPI_ARGS_TWO = 2;
52 const int32_t DM_NAPI_ARGS_THREE = 3;
53 const int32_t DM_NAPI_SUB_ID_MAX = 65535;
54 const int32_t DM_AUTH_DIRECTION_CLIENT = 1;
55 const int32_t DM_AUTH_REQUEST_SUCCESS_STATUS = 7;
56 
57 const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP = 0;
58 const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_OSD = 1;
59 
60 napi_ref deviceTypeEnumConstructor_ = nullptr;
61 napi_ref deviceStateChangeActionEnumConstructor_ = nullptr;
62 napi_ref discoverModeEnumConstructor_ = nullptr;
63 napi_ref exchangeMediumEnumConstructor_ = nullptr;
64 napi_ref exchangeFreqEnumConstructor_ = nullptr;
65 napi_ref subscribeCapEnumConstructor_ = nullptr;
66 
67 std::map<std::string, DeviceManagerNapi *> g_deviceManagerMap;
68 std::map<std::string, std::shared_ptr<DmNapiInitCallback>> g_initCallbackMap;
69 std::map<std::string, std::shared_ptr<DmNapiDeviceStateCallback>> g_deviceStateCallbackMap;
70 std::map<std::string, std::shared_ptr<DmNapiDiscoveryCallback>> g_DiscoveryCallbackMap;
71 std::map<std::string, std::shared_ptr<DmNapiPublishCallback>> g_publishCallbackMap;
72 std::map<std::string, std::shared_ptr<DmNapiAuthenticateCallback>> g_authCallbackMap;
73 std::map<std::string, std::shared_ptr<DmNapiVerifyAuthCallback>> g_verifyAuthCallbackMap;
74 std::map<std::string, std::shared_ptr<DmNapiDeviceManagerUiCallback>> g_dmUiCallbackMap;
75 std::map<std::string, std::shared_ptr<DmNapiCredentialCallback>> g_creCallbackMap;
76 
77 std::mutex g_initCallbackMapMutex;
78 std::mutex g_deviceManagerMapMutex;
79 
80 enum DMBussinessErrorCode {
81     // Permission verify failed.
82     ERR_NO_PERMISSION = 201,
83     //The caller is not a system application.
84     ERR_NOT_SYSTEM_APP = 202,
85     // Input parameter error.
86     ERR_INVALID_PARAMS = 401,
87     // Failed to execute the function.
88     DM_ERR_FAILED = 11600101,
89     // Failed to obtain the service.
90     DM_ERR_OBTAIN_SERVICE = 11600102,
91     // Authentication invalid.
92     DM_ERR_AUTHENTICALTION_INVALID = 11600103,
93     // Discovery invalid.
94     DM_ERR_DISCOVERY_INVALID = 11600104,
95     // Publish invalid.
96     DM_ERR_PUBLISH_INVALID = 11600105,
97 };
98 
99 const std::string ERR_MESSAGE_NO_PERMISSION = "Permission verify failed.";
100 const std::string ERR_MESSAGE_NOT_SYSTEM_APP = "The caller is not a system application.";
101 const std::string ERR_MESSAGE_INVALID_PARAMS = "Input parameter error.";
102 const std::string ERR_MESSAGE_FAILED = "Failed to execute the function.";
103 const std::string ERR_MESSAGE_OBTAIN_SERVICE = "Failed to obtain the service.";
104 const std::string ERR_MESSAGE_AUTHENTICALTION_INVALID = "Authentication invalid.";
105 const std::string ERR_MESSAGE_DISCOVERY_INVALID = "Discovery invalid.";
106 const std::string ERR_MESSAGE_PUBLISH_INVALID = "Publish invalid.";
107 
GenerateBusinessError(napi_env env,int32_t err,const std::string & msg)108 napi_value GenerateBusinessError(napi_env env, int32_t err, const std::string &msg)
109 {
110     napi_value businessError = nullptr;
111     NAPI_CALL(env, napi_create_object(env, &businessError));
112     napi_value errorCode = nullptr;
113     NAPI_CALL(env, napi_create_int32(env, err, &errorCode));
114     napi_value errorMessage = nullptr;
115     NAPI_CALL(env, napi_create_string_utf8(env, msg.c_str(), NAPI_AUTO_LENGTH, &errorMessage));
116     NAPI_CALL(env, napi_set_named_property(env, businessError, "code", errorCode));
117     NAPI_CALL(env, napi_set_named_property(env, businessError, "message", errorMessage));
118 
119     return businessError;
120 }
121 
CheckArgsVal(napi_env env,bool assertion,const std::string & param,const std::string & msg)122 bool CheckArgsVal(napi_env env, bool assertion, const std::string &param, const std::string &msg)
123 {
124     if (!(assertion)) {
125         std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + "The value of " + param + ": " + msg;
126         napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str());
127         return false;
128     }
129     return true;
130 }
131 
CheckArgsCount(napi_env env,bool assertion,const std::string & message)132 bool CheckArgsCount(napi_env env, bool assertion, const std::string &message)
133 {
134     if (!(assertion)) {
135         std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + message;
136         napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str());
137         return false;
138     }
139     return true;
140 }
141 
CheckArgsType(napi_env env,bool assertion,const std::string & paramName,const std::string & type)142 bool CheckArgsType(napi_env env, bool assertion, const std::string &paramName, const std::string &type)
143 {
144     if (!(assertion)) {
145         std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + "The type of " + paramName +
146                 " must be " + type;
147         napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str());
148         return false;
149     }
150     return true;
151 }
152 
CreateErrorForCall(napi_env env,int32_t code,const std::string & errMsg,bool isAsync=true)153 napi_value CreateErrorForCall(napi_env env, int32_t code, const std::string &errMsg, bool isAsync = true)
154 {
155     LOGI("CreateErrorForCall code:%d, message:%s", code, errMsg.c_str());
156     napi_value error = nullptr;
157     if (isAsync) {
158         napi_throw_error(env, std::to_string(code).c_str(), errMsg.c_str());
159     } else {
160         error = GenerateBusinessError(env, code, errMsg);
161     }
162     return error;
163 }
164 
CreateBusinessError(napi_env env,int32_t errCode,bool isAsync=true)165 napi_value CreateBusinessError(napi_env env, int32_t errCode, bool isAsync = true)
166 {
167     napi_value error = nullptr;
168     switch (errCode) {
169         case ERR_DM_NO_PERMISSION:
170             error = CreateErrorForCall(env, ERR_NO_PERMISSION, ERR_MESSAGE_NO_PERMISSION, isAsync);
171             break;
172         case ERR_DM_DISCOVERY_REPEATED:
173             error = CreateErrorForCall(env, DM_ERR_DISCOVERY_INVALID, ERR_MESSAGE_DISCOVERY_INVALID, isAsync);
174             break;
175         case ERR_DM_PUBLISH_REPEATED:
176             error = CreateErrorForCall(env, DM_ERR_PUBLISH_INVALID, ERR_MESSAGE_PUBLISH_INVALID, isAsync);
177             break;
178         case ERR_DM_AUTH_BUSINESS_BUSY:
179             error = CreateErrorForCall(env, DM_ERR_AUTHENTICALTION_INVALID,
180                 ERR_MESSAGE_AUTHENTICALTION_INVALID, isAsync);
181             break;
182         case ERR_DM_INPUT_PARA_INVALID:
183         case ERR_DM_UNSUPPORTED_AUTH_TYPE:
184             error = CreateErrorForCall(env, ERR_INVALID_PARAMS, ERR_MESSAGE_INVALID_PARAMS, isAsync);
185             break;
186         case ERR_DM_INIT_FAILED:
187             error = CreateErrorForCall(env, DM_ERR_OBTAIN_SERVICE, ERR_MESSAGE_OBTAIN_SERVICE, isAsync);
188             break;
189         case ERR_NOT_SYSTEM_APP:
190             error = CreateErrorForCall(env, ERR_NOT_SYSTEM_APP, ERR_MESSAGE_NOT_SYSTEM_APP, isAsync);
191             break;
192         default:
193             error = CreateErrorForCall(env, DM_ERR_FAILED, ERR_MESSAGE_FAILED, isAsync);
194             break;
195     }
196     return error;
197 }
198 
DeleteUvWork(uv_work_t * work)199 void DeleteUvWork(uv_work_t *work)
200 {
201     if (work == nullptr) {
202         return;
203     }
204     delete work;
205     work = nullptr;
206     LOGI("delete work!");
207 }
208 
DeleteDmNapiStateJsCallbackPtr(DmNapiStateJsCallback * pJsCallbackPtr)209 void DeleteDmNapiStateJsCallbackPtr(DmNapiStateJsCallback *pJsCallbackPtr)
210 {
211     if (pJsCallbackPtr == nullptr) {
212         return;
213     }
214     delete pJsCallbackPtr;
215     pJsCallbackPtr = nullptr;
216     LOGI("delete DmNapiStateJsCallback callbackPtr!");
217 }
218 
DeleteAsyncCallbackInfo(DeviceInfoListAsyncCallbackInfo * pAsynCallbackInfo)219 void DeleteAsyncCallbackInfo(DeviceInfoListAsyncCallbackInfo *pAsynCallbackInfo)
220 {
221     if (pAsynCallbackInfo == nullptr) {
222         return;
223     }
224     delete pAsynCallbackInfo;
225     pAsynCallbackInfo = nullptr;
226 }
227 
IsJSObjectType(napi_env env,napi_value value,const std::string & param)228 bool IsJSObjectType(napi_env env, napi_value value, const std::string &param)
229 {
230     napi_valuetype authparamType = napi_undefined;
231     napi_typeof(env, value, &authparamType);
232     return CheckArgsType(env, authparamType == napi_object, param, "object");
233 }
234 
IsFunctionType(napi_env env,napi_value value)235 bool IsFunctionType(napi_env env, napi_value value)
236 {
237     napi_valuetype eventHandleType = napi_undefined;
238     napi_typeof(env, value, &eventHandleType);
239     return CheckArgsType(env, eventHandleType == napi_function, "callback", "function");
240 }
241 
IsDeviceManagerNapiNull(napi_env env,napi_value thisVar,DeviceManagerNapi ** pDeviceManagerWrapper)242 bool IsDeviceManagerNapiNull(napi_env env, napi_value thisVar, DeviceManagerNapi **pDeviceManagerWrapper)
243 {
244     napi_unwrap(env, thisVar, reinterpret_cast<void **>(pDeviceManagerWrapper));
245     if (pDeviceManagerWrapper != nullptr && *pDeviceManagerWrapper != nullptr) {
246         return false;
247     }
248     CreateBusinessError(env, ERR_DM_POINT_NULL);
249     LOGE(" DeviceManagerNapi object is nullptr!");
250     return true;
251 }
252 } // namespace
253 
254 thread_local napi_ref DeviceManagerNapi::sConstructor_ = nullptr;
255 AuthAsyncCallbackInfo DeviceManagerNapi::authAsyncCallbackInfo_;
256 AuthAsyncCallbackInfo DeviceManagerNapi::verifyAsyncCallbackInfo_;
257 CredentialAsyncCallbackInfo DeviceManagerNapi::creAsyncCallbackInfo_;
258 std::mutex DeviceManagerNapi::creMapLocks_;
259 
OnRemoteDied()260 void DmNapiInitCallback::OnRemoteDied()
261 {
262     uv_loop_s *loop = nullptr;
263     napi_get_uv_event_loop(env_, &loop);
264     if (loop == nullptr) {
265         return;
266     }
267     uv_work_t *work = new (std::nothrow) uv_work_t;
268     if (work == nullptr) {
269         LOGE("DmNapiInitCallback: OnRemoteDied, No memory");
270         return;
271     }
272 
273     DmDeviceInfo info;
274     DmNapiStateJsCallback *jsCallback = new DmNapiStateJsCallback(bundleName_, 0, 0, info);
275     if (jsCallback == nullptr) {
276         DeleteUvWork(work);
277         return;
278     }
279     work->data = reinterpret_cast<void *>(jsCallback);
280 
281     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
282         DmNapiStateJsCallback *callback = reinterpret_cast<DmNapiStateJsCallback *>(work->data);
283         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
284         if (deviceManagerNapi == nullptr) {
285             LOGE("OnRemoteDied, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
286         } else {
287             deviceManagerNapi->OnEvent("serviceDie", 0, nullptr);
288         }
289         LOGI("OnRemoteDied, deviceManagerNapi bundleName %s", callback->bundleName_.c_str());
290         DeleteDmNapiStateJsCallbackPtr(callback);
291         DeleteUvWork(work);
292     }, uv_qos_user_initiated);
293     if (ret != 0) {
294         LOGE("Failed to execute OnRemoteDied work queue");
295         DeleteDmNapiStateJsCallbackPtr(jsCallback);
296         DeleteUvWork(work);
297     }
298 }
299 
OnDeviceOnline(const DmDeviceInfo & deviceInfo)300 void DmNapiDeviceStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo)
301 {
302     uv_loop_s *loop = nullptr;
303     napi_get_uv_event_loop(env_, &loop);
304     if (loop == nullptr) {
305         return;
306     }
307     uv_work_t *work = new (std::nothrow) uv_work_t;
308     if (work == nullptr) {
309         LOGE("DmNapiDeviceStateCallback: OnDeviceOnline, No memory");
310         return;
311     }
312 
313     DmNapiStateJsCallback *jsCallback = new DmNapiStateJsCallback(bundleName_, 0, 0, deviceInfo);
314     if (jsCallback == nullptr) {
315         DeleteUvWork(work);
316         return;
317     }
318     work->data = reinterpret_cast<void *>(jsCallback);
319 
320     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
321         DmNapiStateJsCallback *callback = reinterpret_cast<DmNapiStateJsCallback *>(work->data);
322         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
323         if (deviceManagerNapi == nullptr) {
324             LOGE("OnDeviceOnline, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
325         } else {
326             deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::ONLINE, callback->deviceInfo_);
327         }
328         DeleteDmNapiStateJsCallbackPtr(callback);
329         DeleteUvWork(work);
330     }, uv_qos_user_initiated);
331     if (ret != 0) {
332         LOGE("Failed to execute OnDeviceOnline work queue");
333         DeleteDmNapiStateJsCallbackPtr(jsCallback);
334         DeleteUvWork(work);
335     }
336 }
337 
OnDeviceReady(const DmDeviceInfo & deviceInfo)338 void DmNapiDeviceStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo)
339 {
340     uv_loop_s *loop = nullptr;
341     napi_get_uv_event_loop(env_, &loop);
342     if (loop == nullptr) {
343         return;
344     }
345     uv_work_t *work = new (std::nothrow) uv_work_t;
346     if (work == nullptr) {
347         LOGE("DmNapiDeviceStateCallback: OnDeviceReady, No memory");
348         return;
349     }
350 
351     DmNapiStateJsCallback *jsCallback = new DmNapiStateJsCallback(bundleName_, 0, 0, deviceInfo);
352     if (jsCallback == nullptr) {
353         DeleteUvWork(work);
354         return;
355     }
356     work->data = reinterpret_cast<void *>(jsCallback);
357 
358     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
359         DmNapiStateJsCallback *callback = reinterpret_cast<DmNapiStateJsCallback *>(work->data);
360         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
361         if (deviceManagerNapi == nullptr) {
362             LOGE("OnDeviceReady, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
363         } else {
364             deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::READY, callback->deviceInfo_);
365         }
366         DeleteDmNapiStateJsCallbackPtr(callback);
367         DeleteUvWork(work);
368     }, uv_qos_user_initiated);
369     if (ret != 0) {
370         LOGE("Failed to execute OnDeviceReady work queue");
371         DeleteDmNapiStateJsCallbackPtr(jsCallback);
372         DeleteUvWork(work);
373     }
374 }
375 
OnDeviceOffline(const DmDeviceInfo & deviceInfo)376 void DmNapiDeviceStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo)
377 {
378     uv_loop_s *loop = nullptr;
379     napi_get_uv_event_loop(env_, &loop);
380     if (loop == nullptr) {
381         return;
382     }
383     uv_work_t *work = new (std::nothrow) uv_work_t;
384     if (work == nullptr) {
385         LOGE("DmNapiDeviceStateCallback: OnDeviceOffline, No memory");
386         return;
387     }
388 
389     DmNapiStateJsCallback *jsCallback = new DmNapiStateJsCallback(bundleName_, 0, 0, deviceInfo);
390     if (jsCallback == nullptr) {
391         DeleteUvWork(work);
392         return;
393     }
394     work->data = reinterpret_cast<void *>(jsCallback);
395 
396     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
397         DmNapiStateJsCallback *callback = reinterpret_cast<DmNapiStateJsCallback *>(work->data);
398         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
399         if (deviceManagerNapi == nullptr) {
400             LOGE("OnDeviceOffline, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
401         } else {
402             deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::OFFLINE, callback->deviceInfo_);
403         }
404         DeleteDmNapiStateJsCallbackPtr(callback);
405         DeleteUvWork(work);
406     }, uv_qos_user_initiated);
407     if (ret != 0) {
408         LOGE("Failed to execute OnDeviceOffline work queue");
409         DeleteDmNapiStateJsCallbackPtr(jsCallback);
410         DeleteUvWork(work);
411     }
412 }
413 
OnDeviceChanged(const DmDeviceInfo & deviceInfo)414 void DmNapiDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo)
415 {
416     uv_loop_s *loop = nullptr;
417     napi_get_uv_event_loop(env_, &loop);
418     if (loop == nullptr) {
419         return;
420     }
421     uv_work_t *work = new (std::nothrow) uv_work_t;
422     if (work == nullptr) {
423         LOGE("DmNapiDeviceStateCallback: OnDeviceChanged, No memory");
424         return;
425     }
426 
427     DmNapiStateJsCallback *jsCallback = new DmNapiStateJsCallback(bundleName_, 0, 0, deviceInfo);
428     if (jsCallback == nullptr) {
429         DeleteUvWork(work);
430         return;
431     }
432     work->data = reinterpret_cast<void *>(jsCallback);
433 
434     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
435         DmNapiStateJsCallback *callback = reinterpret_cast<DmNapiStateJsCallback *>(work->data);
436         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
437         if (deviceManagerNapi == nullptr) {
438             LOGE("OnDeviceChanged, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
439         } else {
440             deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::CHANGE, callback->deviceInfo_);
441         }
442         DeleteDmNapiStateJsCallbackPtr(callback);
443         DeleteUvWork(work);
444     }, uv_qos_user_initiated);
445     if (ret != 0) {
446         LOGE("Failed to execute OnDeviceChanged work queue");
447         DeleteDmNapiStateJsCallbackPtr(jsCallback);
448         DeleteUvWork(work);
449     }
450 }
451 
OnDeviceFound(uint16_t subscribeId,const DmDeviceInfo & deviceInfo)452 void DmNapiDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo)
453 {
454     LOGI("OnDeviceFound for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId);
455 
456     uv_loop_s *loop = nullptr;
457     napi_get_uv_event_loop(env_, &loop);
458     if (loop == nullptr) {
459         return;
460     }
461     uv_work_t *work = new (std::nothrow) uv_work_t;
462     if (work == nullptr) {
463         LOGE("DmNapiDiscoveryCallback: OnDeviceFound, No memory");
464         return;
465     }
466 
467     DmNapiStateJsCallback *jsCallback = new DmNapiStateJsCallback(bundleName_, subscribeId, 0, deviceInfo);
468     if (jsCallback == nullptr) {
469         DeleteUvWork(work);
470         return;
471     }
472     work->data = reinterpret_cast<void *>(jsCallback);
473 
474     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
475         DmNapiStateJsCallback *callback = reinterpret_cast<DmNapiStateJsCallback *>(work->data);
476         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
477         if (deviceManagerNapi == nullptr) {
478             LOGE("OnDeviceFound, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
479         } else {
480             deviceManagerNapi->OnDeviceFound(callback->subscribeId_, callback->deviceInfo_);
481         }
482         DeleteDmNapiStateJsCallbackPtr(callback);
483         DeleteUvWork(work);
484     }, uv_qos_user_initiated);
485     if (ret != 0) {
486         LOGE("Failed to execute OnDeviceFound work queue");
487         DeleteDmNapiStateJsCallbackPtr(jsCallback);
488         DeleteUvWork(work);
489     }
490 }
491 
OnDiscoveryFailed(uint16_t subscribeId,int32_t failedReason)492 void DmNapiDiscoveryCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason)
493 {
494     LOGI("OnDiscoveryFailed for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId);
495 
496     uv_loop_s *loop = nullptr;
497     napi_get_uv_event_loop(env_, &loop);
498     if (loop == nullptr) {
499         return;
500     }
501     uv_work_t *work = new (std::nothrow) uv_work_t;
502     if (work == nullptr) {
503         LOGE("DmNapiDiscoveryCallback: OnDiscoveryFailed, No memory");
504         return;
505     }
506 
507     DmDeviceInfo info;
508     DmNapiStateJsCallback *jsCallback = new DmNapiStateJsCallback(bundleName_, subscribeId,
509         failedReason, info);
510     if (jsCallback == nullptr) {
511         DeleteUvWork(work);
512         return;
513     }
514     work->data = reinterpret_cast<void *>(jsCallback);
515 
516     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
517         DmNapiStateJsCallback *callback = reinterpret_cast<DmNapiStateJsCallback *>(work->data);
518         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
519         if (deviceManagerNapi == nullptr) {
520             LOGE("OnDiscoveryFailed, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
521         } else {
522             deviceManagerNapi->OnDiscoveryFailed(callback->subscribeId_, callback->reason_);
523         }
524         DeleteDmNapiStateJsCallbackPtr(callback);
525         DeleteUvWork(work);
526     }, uv_qos_user_initiated);
527     if (ret != 0) {
528         LOGE("Failed to execute OnDiscoveryFailed work queue");
529         DeleteDmNapiStateJsCallbackPtr(jsCallback);
530         DeleteUvWork(work);
531     }
532 }
533 
OnDiscoverySuccess(uint16_t subscribeId)534 void DmNapiDiscoveryCallback::OnDiscoverySuccess(uint16_t subscribeId)
535 {
536     DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_);
537     if (deviceManagerNapi == nullptr) {
538         LOGE("OnDiscoverySuccess, deviceManagerNapi not find for bundleName %s", bundleName_.c_str());
539         return;
540     }
541     LOGI("DiscoverySuccess for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId);
542 }
543 
IncreaseRefCount()544 void DmNapiDiscoveryCallback::IncreaseRefCount()
545 {
546     refCount_++;
547 }
548 
DecreaseRefCount()549 void DmNapiDiscoveryCallback::DecreaseRefCount()
550 {
551     refCount_--;
552 }
553 
GetRefCount()554 int32_t DmNapiDiscoveryCallback::GetRefCount()
555 {
556     return refCount_;
557 }
558 
OnPublishResult(int32_t publishId,int32_t publishResult)559 void DmNapiPublishCallback::OnPublishResult(int32_t publishId, int32_t publishResult)
560 {
561     LOGI("OnPublishResult for %s, publishId %d, publishResult %d", bundleName_.c_str(), publishId, publishResult);
562     uv_loop_s *loop = nullptr;
563     napi_get_uv_event_loop(env_, &loop);
564     if (loop == nullptr) {
565         return;
566     }
567     uv_work_t *work = new (std::nothrow) uv_work_t;
568     if (work == nullptr) {
569         LOGE("DmNapiPublishCallback: OnPublishResult, No memory");
570         return;
571     }
572 
573     DmNapiPublishJsCallback *jsCallback = new DmNapiPublishJsCallback(bundleName_, publishId, publishResult);
574     if (jsCallback == nullptr) {
575         DeleteUvWork(work);
576         return;
577     }
578     work->data = reinterpret_cast<void *>(jsCallback);
579 
580     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
581         DmNapiPublishJsCallback *callback = reinterpret_cast<DmNapiPublishJsCallback *>(work->data);
582         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
583         if (deviceManagerNapi == nullptr) {
584             LOGE("OnPublishResult, deviceManagerNapi failed for bundleName %s", callback->bundleName_.c_str());
585         } else {
586             deviceManagerNapi->OnPublishResult(callback->publishId_, callback->reason_);
587         }
588         delete callback;
589         callback = nullptr;
590         DeleteUvWork(work);
591     }, uv_qos_user_initiated);
592     if (ret != 0) {
593         LOGE("Failed to execute OnPublishResult work queue");
594         delete jsCallback;
595         jsCallback = nullptr;
596         DeleteUvWork(work);
597     }
598 }
599 
IncreaseRefCount()600 void DmNapiPublishCallback::IncreaseRefCount()
601 {
602     refCount_++;
603 }
604 
DecreaseRefCount()605 void DmNapiPublishCallback::DecreaseRefCount()
606 {
607     refCount_--;
608 }
609 
GetRefCount()610 int32_t DmNapiPublishCallback::GetRefCount()
611 {
612     return refCount_;
613 }
614 
OnAuthResult(const std::string & deviceId,const std::string & token,int32_t status,int32_t reason)615 void DmNapiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status,
616                                               int32_t reason)
617 {
618     uv_loop_s *loop = nullptr;
619     napi_get_uv_event_loop(env_, &loop);
620     if (loop == nullptr) {
621         return;
622     }
623     uv_work_t *work = new (std::nothrow) uv_work_t;
624     if (work == nullptr) {
625         LOGE("DmNapiAuthenticateCallback: OnAuthResult, No memory");
626         return;
627     }
628 
629     DmNapiAuthJsCallback *jsCallback = new DmNapiAuthJsCallback(bundleName_, deviceId, token, status, reason);
630     if (jsCallback == nullptr) {
631         DeleteUvWork(work);
632         return;
633     }
634     work->data = reinterpret_cast<void *>(jsCallback);
635 
636     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
637         DmNapiAuthJsCallback *callback = reinterpret_cast<DmNapiAuthJsCallback *>(work->data);
638         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
639         if (deviceManagerNapi == nullptr) {
640             LOGE("OnAuthResult, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
641         } else {
642             deviceManagerNapi->OnAuthResult(callback->deviceId_, callback->token_,
643                 callback->status_, callback->reason_);
644         }
645         delete callback;
646         callback = nullptr;
647         DeleteUvWork(work);
648     }, uv_qos_user_initiated);
649     if (ret != 0) {
650         LOGE("Failed to execute OnAuthResult work queue");
651         delete jsCallback;
652         jsCallback = nullptr;
653         DeleteUvWork(work);
654     }
655 }
656 
OnCredentialResult(int32_t & action,const std::string & credentialResult)657 void DmNapiCredentialCallback::OnCredentialResult(int32_t &action, const std::string &credentialResult)
658 {
659     uv_loop_s *loop = nullptr;
660     napi_get_uv_event_loop(env_, &loop);
661     if (loop == nullptr) {
662         return;
663     }
664     uv_work_t *work = new (std::nothrow) uv_work_t;
665     if (work == nullptr) {
666         LOGE("DmNapiAuthenticateCallback: OnAuthResult, No memory");
667         return;
668     }
669 
670     DmNapiCredentialJsCallback *jsCallback = new DmNapiCredentialJsCallback(bundleName_, action, credentialResult);
671     if (jsCallback == nullptr) {
672         delete work;
673         work = nullptr;
674         return;
675     }
676     work->data = reinterpret_cast<void *>(jsCallback);
677 
678     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
679         DmNapiCredentialJsCallback *callback = reinterpret_cast<DmNapiCredentialJsCallback *>(work->data);
680         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
681         if (deviceManagerNapi == nullptr) {
682             LOGE("OnCredentialResult, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
683         } else {
684             deviceManagerNapi->OnCredentialResult(callback->action_, callback->credentialResult_);
685         }
686         delete callback;
687         callback = nullptr;
688         delete work;
689         work = nullptr;
690     }, uv_qos_user_initiated);
691     if (ret != 0) {
692         LOGE("Failed to execute OnCredentialResult work queue");
693         delete jsCallback;
694         jsCallback = nullptr;
695         delete work;
696         work = nullptr;
697     }
698 }
699 
OnVerifyAuthResult(const std::string & deviceId,int32_t resultCode,int32_t flag)700 void DmNapiVerifyAuthCallback::OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag)
701 {
702     uv_loop_s *loop = nullptr;
703     napi_get_uv_event_loop(env_, &loop);
704     if (loop == nullptr) {
705         return;
706     }
707     uv_work_t *work = new (std::nothrow) uv_work_t;
708     if (work == nullptr) {
709         LOGE("DmNapiVerifyAuthCallback: OnVerifyAuthResult, No memory");
710         return;
711     }
712 
713     DmNapiVerifyJsCallback *jsCallback = new DmNapiVerifyJsCallback(bundleName_, deviceId, resultCode, flag);
714     if (jsCallback == nullptr) {
715         DeleteUvWork(work);
716         return;
717     }
718     work->data = reinterpret_cast<void *>(jsCallback);
719 
720     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
721         DmNapiVerifyJsCallback *callback = reinterpret_cast<DmNapiVerifyJsCallback *>(work->data);
722         DeviceManagerNapi *deviceManagerNapi =  DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
723         if (deviceManagerNapi == nullptr) {
724             LOGE("OnVerifyAuthResult, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
725         } else {
726             deviceManagerNapi->OnVerifyResult(callback->deviceId_, callback->resultCode_, callback->flag_);
727         }
728         delete callback;
729         callback = nullptr;
730         DeleteUvWork(work);
731     }, uv_qos_user_initiated);
732     if (ret != 0) {
733         LOGE("Failed to execute OnVerifyAuthResult work queue");
734         delete jsCallback;
735         jsCallback = nullptr;
736         DeleteUvWork(work);
737     }
738 }
739 
DeviceManagerNapi(napi_env env,napi_value thisVar)740 DeviceManagerNapi::DeviceManagerNapi(napi_env env, napi_value thisVar) : DmNativeEvent(env, thisVar)
741 {
742     env_ = env;
743 }
744 
~DeviceManagerNapi()745 DeviceManagerNapi::~DeviceManagerNapi()
746 {
747 }
748 
GetDeviceManagerNapi(std::string & bundleName)749 DeviceManagerNapi *DeviceManagerNapi::GetDeviceManagerNapi(std::string &bundleName)
750 {
751     std::lock_guard<std::mutex> autoLock(g_deviceManagerMapMutex);
752     auto iter = g_deviceManagerMap.find(bundleName);
753     if (iter == g_deviceManagerMap.end()) {
754         return nullptr;
755     }
756     return iter->second;
757 }
758 
OnDeviceStateChange(DmNapiDevStateChangeAction action,const OHOS::DistributedHardware::DmDeviceInfo & deviceInfo)759 void DeviceManagerNapi::OnDeviceStateChange(DmNapiDevStateChangeAction action,
760                                             const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo)
761 {
762     napi_handle_scope scope;
763     napi_open_handle_scope(env_, &scope);
764     napi_value result = nullptr;
765     napi_create_object(env_, &result);
766     SetValueInt32(env_, "action", (int)action, result);
767 
768     napi_value device = nullptr;
769     napi_create_object(env_, &device);
770     SetValueUtf8String(env_, "deviceId", deviceInfo.deviceId, device);
771     SetValueUtf8String(env_, "networkId", deviceInfo.networkId, device);
772     SetValueUtf8String(env_, "deviceName", deviceInfo.deviceName, device);
773     SetValueInt32(env_, "deviceType", (int)deviceInfo.deviceTypeId, device);
774     SetValueInt32(env_, "authForm", (int)deviceInfo.authForm, device);
775 
776     napi_set_named_property(env_, result, "device", device);
777     OnEvent("deviceStateChange", DM_NAPI_ARGS_ONE, &result);
778     napi_close_handle_scope(env_, scope);
779 }
780 
OnDeviceFound(uint16_t subscribeId,const DmDeviceInfo & deviceInfo)781 void DeviceManagerNapi::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo)
782 {
783     LOGI("OnDeviceFound for subscribeId %d, range : %d", (int32_t)subscribeId, deviceInfo.range);
784     napi_handle_scope scope;
785     napi_open_handle_scope(env_, &scope);
786     napi_value result = nullptr;
787     napi_create_object(env_, &result);
788     SetValueInt32(env_, "subscribeId", (int)subscribeId, result);
789 
790     napi_value device = nullptr;
791     napi_create_object(env_, &device);
792     SetValueUtf8String(env_, "deviceId", deviceInfo.deviceId, device);
793     SetValueUtf8String(env_, "networkId", deviceInfo.networkId, device);
794     SetValueUtf8String(env_, "deviceName", deviceInfo.deviceName, device);
795     SetValueInt32(env_, "deviceType", (int)deviceInfo.deviceTypeId, device);
796     SetValueInt32(env_, "authForm", (int)deviceInfo.authForm, device);
797     SetValueInt32(env_, "range", deviceInfo.range, device);
798 
799     napi_set_named_property(env_, result, "device", device);
800     OnEvent("deviceFound", DM_NAPI_ARGS_ONE, &result);
801     napi_close_handle_scope(env_, scope);
802 }
803 
OnDiscoveryFailed(uint16_t subscribeId,int32_t failedReason)804 void DeviceManagerNapi::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason)
805 {
806     LOGI("OnDiscoveryFailed for subscribeId %d", (int32_t)subscribeId);
807     napi_handle_scope scope;
808     napi_open_handle_scope(env_, &scope);
809     napi_value result = nullptr;
810     napi_create_object(env_, &result);
811     SetValueInt32(env_, "subscribeId", (int)subscribeId, result);
812     SetValueInt32(env_, "reason", (int)failedReason, result);
813     std::string errCodeInfo = OHOS::DistributedHardware::GetErrorString((int)failedReason);
814     SetValueUtf8String(env_, "errInfo", errCodeInfo, result);
815     OnEvent("discoverFail", DM_NAPI_ARGS_ONE, &result);
816     napi_close_handle_scope(env_, scope);
817 }
818 
OnPublishResult(int32_t publishId,int32_t publishResult)819 void DeviceManagerNapi::OnPublishResult(int32_t publishId, int32_t publishResult)
820 {
821     LOGI("OnPublishResult for publishId %d, publishResult %d", publishId, publishResult);
822     napi_handle_scope scope;
823     napi_open_handle_scope(env_, &scope);
824     napi_value result = nullptr;
825     napi_create_object(env_, &result);
826     SetValueInt32(env_, "publishId", publishId, result);
827     if (publishResult == 0) {
828         OnEvent("publishSuccess", DM_NAPI_ARGS_ONE, &result);
829     } else {
830         SetValueInt32(env_, "reason", publishResult, result);
831         std::string errCodeInfo = OHOS::DistributedHardware::GetErrorString(publishResult);
832         SetValueUtf8String(env_, "errInfo", errCodeInfo, result);
833         OnEvent("publishFail", DM_NAPI_ARGS_ONE, &result);
834     }
835     NAPI_CALL_RETURN_VOID(env_, napi_close_handle_scope(env_, scope));
836 }
837 
OnCredentialResult(int32_t & action,const std::string & credentialResult)838 void DeviceManagerNapi::OnCredentialResult(int32_t &action, const std::string &credentialResult)
839 {
840     LOGI("OnCredentialResult for action: %d, credentialResult: %s", action, credentialResult.c_str());
841     napi_handle_scope scope = nullptr;
842     napi_open_handle_scope(env_, &scope);
843     if (scope == nullptr) {
844         LOGE("scope is nullptr");
845         return;
846     }
847     napi_value result = nullptr;
848     napi_create_object(env_, &result);
849     SetValueUtf8String(env_, "resultInfo", credentialResult, result);
850 
851     napi_value callResult = nullptr;
852     napi_value handler = nullptr;
853     napi_get_reference_value(env_, creAsyncCallbackInfo_.callback, &handler);
854     if (handler != nullptr) {
855         napi_call_function(env_, nullptr, handler, DM_NAPI_ARGS_ONE, &result, &callResult);
856         napi_delete_reference(env_, creAsyncCallbackInfo_.callback);
857     } else {
858         LOGE("handler is nullptr");
859     }
860     napi_close_handle_scope(env_, scope);
861     DeviceManager::GetInstance().UnRegisterCredentialCallback(bundleName_);
862     {
863         std::lock_guard<std::mutex> autoLock(creMapLocks_);
864         g_creCallbackMap.erase(bundleName_);
865     }
866 }
867 
OnAuthResult(const std::string & deviceId,const std::string & token,int32_t status,int32_t reason)868 void DeviceManagerNapi::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status,
869                                      int32_t reason)
870 {
871     LOGI("OnAuthResult for status: %d, reason: %d", status, reason);
872     napi_handle_scope scope;
873     napi_open_handle_scope(env_, &scope);
874     napi_value thisVar = nullptr;
875     napi_get_reference_value(env_, thisVarRef_, &thisVar);
876     napi_value result[DM_NAPI_ARGS_TWO] = {0};
877 
878     if (status == DM_AUTH_REQUEST_SUCCESS_STATUS && reason == 0) {
879         LOGI("OnAuthResult success");
880         napi_get_undefined(env_, &result[0]);
881         napi_create_object(env_, &result[1]);
882         SetValueUtf8String(env_, "deviceId", deviceId, result[1]);
883     } else {
884         LOGI("OnAuthResult failed");
885         napi_create_object(env_, &result[0]);
886         SetValueInt32(env_, "code", status, result[0]);
887         SetValueInt32(env_, "reason", reason, result[0]);
888         std::string errCodeInfo = OHOS::DistributedHardware::GetErrorString((int)reason);
889         SetValueUtf8String(env_, "errInfo", errCodeInfo, result[0]);
890         napi_get_undefined(env_, &result[1]);
891     }
892 
893     napi_value callResult = nullptr;
894     napi_value handler = nullptr;
895     napi_get_reference_value(env_, authAsyncCallbackInfo_.callback, &handler);
896     if (handler != nullptr) {
897         napi_call_function(env_, nullptr, handler, DM_NAPI_ARGS_TWO, &result[0], &callResult);
898         napi_delete_reference(env_, authAsyncCallbackInfo_.callback);
899     } else {
900         LOGE("handler is nullptr");
901     }
902     napi_close_handle_scope(env_, scope);
903     g_authCallbackMap.erase(bundleName_);
904 }
905 
OnVerifyResult(const std::string & deviceId,int32_t resultCode,int32_t flag)906 void DeviceManagerNapi::OnVerifyResult(const std::string &deviceId, int32_t resultCode, int32_t flag)
907 {
908     LOGI("OnVerifyResult for resultCode: %d, flag: %d", resultCode, flag);
909     napi_handle_scope scope;
910     napi_open_handle_scope(env_, &scope);
911     napi_value thisVar = nullptr;
912     napi_get_reference_value(env_, thisVarRef_, &thisVar);
913     napi_value result[DM_NAPI_ARGS_TWO] = {0};
914     if (resultCode == 0) {
915         napi_get_undefined(env_, &result[0]);
916         napi_create_object(env_, &result[1]);
917         SetValueUtf8String(env_, "deviceId", deviceId, result[1]);
918         SetValueInt32(env_, "level", flag, result[1]);
919     } else {
920         napi_create_object(env_, &result[0]);
921         SetValueInt32(env_, "code", resultCode, result[0]);
922         napi_get_undefined(env_, &result[1]);
923     }
924 
925     napi_value callResult = nullptr;
926     napi_value handler = nullptr;
927     napi_get_reference_value(env_, verifyAsyncCallbackInfo_.callback, &handler);
928     if (handler != nullptr) {
929         napi_call_function(env_, nullptr, handler, DM_NAPI_ARGS_TWO, &result[0], &callResult);
930         napi_delete_reference(env_, verifyAsyncCallbackInfo_.callback);
931     } else {
932         LOGE("handler is nullptr");
933     }
934     napi_close_handle_scope(env_, scope);
935     g_verifyAuthCallbackMap.erase(bundleName_);
936 }
937 
SetValueUtf8String(const napi_env & env,const std::string & fieldStr,const std::string & str,napi_value & result)938 void DeviceManagerNapi::SetValueUtf8String(const napi_env &env, const std::string &fieldStr, const std::string &str,
939                                            napi_value &result)
940 {
941     napi_value value = nullptr;
942     napi_create_string_utf8(env, str.c_str(), NAPI_AUTO_LENGTH, &value);
943     napi_set_named_property(env, result, fieldStr.c_str(), value);
944 }
945 
SetValueInt32(const napi_env & env,const std::string & fieldStr,const int32_t intValue,napi_value & result)946 void DeviceManagerNapi::SetValueInt32(const napi_env &env, const std::string &fieldStr, const int32_t intValue,
947                                       napi_value &result)
948 {
949     napi_value value = nullptr;
950     napi_create_int32(env, intValue, &value);
951     napi_set_named_property(env, result, fieldStr.c_str(), value);
952 }
953 
DeviceInfoToJsArray(const napi_env & env,const std::vector<DmDeviceInfo> & vecDevInfo,const int32_t idx,napi_value & arrayResult)954 void DeviceManagerNapi::DeviceInfoToJsArray(const napi_env &env, const std::vector<DmDeviceInfo> &vecDevInfo,
955                                             const int32_t idx, napi_value &arrayResult)
956 {
957     napi_value result = nullptr;
958     napi_create_object(env, &result);
959 
960     SetValueUtf8String(env, "deviceId", vecDevInfo[idx].deviceId, result);
961     SetValueUtf8String(env, "networkId", vecDevInfo[idx].networkId, result);
962     SetValueUtf8String(env, "deviceName", vecDevInfo[idx].deviceName, result);
963     SetValueInt32(env, "deviceType", (int)vecDevInfo[idx].deviceTypeId, result);
964     SetValueInt32(env, "authForm", (int)vecDevInfo[idx].authForm, result);
965 
966     napi_status status = napi_set_element(env, arrayResult, idx, result);
967     if (status != napi_ok) {
968         LOGE("DmDeviceInfo To JsArray set element error: %d", status);
969     }
970 }
971 
DmAuthParamDetection(const DmAuthParam & authParam)972 bool DeviceManagerNapi::DmAuthParamDetection(const DmAuthParam &authParam)
973 {
974     LOGI("DeviceManagerNapi::DmAuthParamDetection");
975     const uint32_t maxIntValueLen = 10;
976     const std::string maxAuthToken = "2147483647";
977     if (authParam.authToken.length() > maxIntValueLen) {
978         LOGE("The authToken is illegal");
979         return false;
980     } else {
981         if (!IsNumberString(authParam.authToken)) {
982             LOGE("The authToken is Error");
983             return false;
984         } else {
985             if (authParam.authToken > maxAuthToken) {
986                 LOGE("The authToken is Cross the border");
987                 return false;
988             }
989         }
990     }
991     return true;
992 }
993 
DmAuthParamToJsAuthParam(const napi_env & env,const DmAuthParam & authParam,napi_value & paramResult)994 void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, const DmAuthParam &authParam,
995                                                  napi_value &paramResult)
996 {
997     LOGI("DeviceManagerNapi::DmAuthParamToJsAuthParam");
998     if (!DmAuthParamDetection(authParam)) {
999         LOGE("The authToken is Error");
1000         return;
1001     }
1002     napi_value extraInfo = nullptr;
1003     napi_create_object(env, &extraInfo);
1004     SetValueInt32(env, "direction", authParam.direction, extraInfo);
1005     SetValueInt32(env, "authType", authParam.authType, paramResult);
1006     SetValueInt32(env, "pinToken", stoi(authParam.authToken), extraInfo);
1007 
1008     if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) {
1009         napi_set_named_property(env, paramResult, "extraInfo", extraInfo);
1010         return;
1011     }
1012 
1013     SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo);
1014     SetValueUtf8String(env, "appName", authParam.appName, extraInfo);
1015     SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo);
1016     SetValueInt32(env, "business", authParam.business, extraInfo);
1017     SetValueInt32(env, "pinCode", authParam.pincode, extraInfo);
1018     napi_set_named_property(env, paramResult, "extraInfo", extraInfo);
1019 
1020     size_t appIconLen = static_cast<size_t>(authParam.imageinfo.GetAppIconLen());
1021     if (appIconLen > 0) {
1022         void *appIcon = nullptr;
1023         napi_value appIconBuffer = nullptr;
1024         napi_create_arraybuffer(env, appIconLen, &appIcon, &appIconBuffer);
1025         if (appIcon != nullptr &&
1026             memcpy_s(appIcon, appIconLen, reinterpret_cast<const void *>(authParam.imageinfo.GetAppIcon()),
1027                      appIconLen) == 0) {
1028             napi_value appIconArray = nullptr;
1029             napi_create_typedarray(env, napi_uint8_array, appIconLen, appIconBuffer, 0, &appIconArray);
1030             napi_set_named_property(env, paramResult, "appIcon", appIconArray);
1031         }
1032     }
1033 
1034     size_t appThumbnailLen = static_cast<size_t>(authParam.imageinfo.GetAppThumbnailLen());
1035     if (appThumbnailLen > 0) {
1036         void *appThumbnail = nullptr;
1037         napi_value appThumbnailBuffer = nullptr;
1038         napi_create_arraybuffer(env, appThumbnailLen, &appThumbnail, &appThumbnailBuffer);
1039         if (appThumbnail != nullptr &&
1040             memcpy_s(appThumbnail, appThumbnailLen,
1041                      reinterpret_cast<const void *>(authParam.imageinfo.GetAppThumbnail()), appThumbnailLen) == 0) {
1042             napi_value appThumbnailArray = nullptr;
1043             napi_create_typedarray(env, napi_uint8_array, appThumbnailLen, appThumbnailBuffer, 0, &appThumbnailArray);
1044             napi_set_named_property(env, paramResult, "appThumbnail", appThumbnailArray);
1045         }
1046     }
1047     return;
1048 }
1049 
JsObjectToString(const napi_env & env,const napi_value & object,const std::string & fieldStr,char * dest,const int32_t destLen)1050 void DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value &object, const std::string &fieldStr,
1051                                          char *dest, const int32_t destLen)
1052 {
1053     bool hasProperty = false;
1054     NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty));
1055     if (hasProperty) {
1056         napi_value field = nullptr;
1057         napi_valuetype valueType = napi_undefined;
1058 
1059         napi_get_named_property(env, object, fieldStr.c_str(), &field);
1060         NAPI_CALL_RETURN_VOID(env, napi_typeof(env, field, &valueType));
1061         if (!CheckArgsType(env, valueType == napi_string, fieldStr.c_str(), "string")) {
1062             return;
1063         }
1064         size_t result = 0;
1065         NAPI_CALL_RETURN_VOID(env, napi_get_value_string_utf8(env, field, dest, destLen, &result));
1066     } else {
1067         LOGE("devicemanager napi js to str no property: %s", fieldStr.c_str());
1068     }
1069 }
1070 
JsObjectToString(const napi_env & env,const napi_value & param)1071 std::string DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value &param)
1072 {
1073     LOGI("JsObjectToString in.");
1074     size_t size = 0;
1075     if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != napi_ok) {
1076         return "";
1077     }
1078     if (size == 0) {
1079         return "";
1080     }
1081     char *buf = new (std::nothrow) char[size + 1];
1082     if (buf == nullptr) {
1083         return "";
1084     }
1085     int32_t ret = memset_s(buf, (size + 1), 0, (size + 1));
1086     if (ret != 0) {
1087         LOGE("devicemanager memset_s error.");
1088         delete[] buf;
1089         buf = nullptr;
1090         return "";
1091     }
1092     bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == napi_ok;
1093 
1094     std::string value;
1095     if (rev) {
1096         value = buf;
1097     } else {
1098         value = "";
1099     }
1100     delete[] buf;
1101     buf = nullptr;
1102     return value;
1103 }
1104 
JsObjectToInt(const napi_env & env,const napi_value & object,const std::string & fieldStr,int32_t & fieldRef)1105 void DeviceManagerNapi::JsObjectToInt(const napi_env &env, const napi_value &object, const std::string &fieldStr,
1106                                       int32_t &fieldRef)
1107 {
1108     bool hasProperty = false;
1109     NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty));
1110     if (hasProperty) {
1111         napi_value field = nullptr;
1112         napi_valuetype valueType = napi_undefined;
1113 
1114         napi_get_named_property(env, object, fieldStr.c_str(), &field);
1115         NAPI_CALL_RETURN_VOID(env, napi_typeof(env, field, &valueType));
1116         if (!CheckArgsType(env, valueType == napi_number, fieldStr.c_str(), "number")) {
1117             return;
1118         }
1119         napi_get_value_int32(env, field, &fieldRef);
1120     } else {
1121         LOGE("devicemanager napi js to int no property: %s", fieldStr.c_str());
1122     }
1123 }
1124 
JsObjectToBool(const napi_env & env,const napi_value & object,const std::string & fieldStr,bool & fieldRef)1125 void DeviceManagerNapi::JsObjectToBool(const napi_env &env, const napi_value &object, const std::string &fieldStr,
1126                                        bool &fieldRef)
1127 {
1128     bool hasProperty = false;
1129     NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty));
1130     if (hasProperty) {
1131         napi_value field = nullptr;
1132         napi_valuetype valueType = napi_undefined;
1133 
1134         napi_get_named_property(env, object, fieldStr.c_str(), &field);
1135         NAPI_CALL_RETURN_VOID(env, napi_typeof(env, field, &valueType));
1136         if (!CheckArgsType(env, valueType == napi_boolean, fieldStr.c_str(), "bool")) {
1137             return;
1138         }
1139         napi_get_value_bool(env, field, &fieldRef);
1140     } else {
1141         LOGE("devicemanager napi js to bool no property: %s", fieldStr.c_str());
1142     }
1143 }
1144 
JsToDmPublishInfo(const napi_env & env,const napi_value & object,DmPublishInfo & info)1145 void DeviceManagerNapi::JsToDmPublishInfo(const napi_env &env, const napi_value &object, DmPublishInfo &info)
1146 {
1147     int32_t publishId = -1;
1148     JsObjectToInt(env, object, "publishId", publishId);
1149     info.publishId = publishId;
1150 
1151     int32_t mode = -1;
1152     JsObjectToInt(env, object, "mode", mode);
1153     info.mode = static_cast<DmDiscoverMode>(mode);
1154 
1155     int32_t freq = -1;
1156     JsObjectToInt(env, object, "freq", freq);
1157     info.freq = static_cast<DmExchangeFreq>(freq);
1158 
1159     JsObjectToBool(env, object, "ranging", info.ranging);
1160     return;
1161 }
1162 
JsToDmSubscribeInfo(const napi_env & env,const napi_value & object,DmSubscribeInfo & info)1163 int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env &env, const napi_value &object, DmSubscribeInfo &info)
1164 {
1165     int32_t subscribeId = -1;
1166     JsObjectToInt(env, object, "subscribeId", subscribeId);
1167     if (subscribeId < 0 || subscribeId > DM_NAPI_SUB_ID_MAX) {
1168         LOGE("DeviceManagerNapi::JsToDmSubscribeInfo, subscribeId error, subscribeId: %d ", subscribeId);
1169         return -1;
1170     }
1171 
1172     info.subscribeId = static_cast<uint16_t>(subscribeId);
1173 
1174     int32_t mode = -1;
1175     JsObjectToInt(env, object, "mode", mode);
1176     info.mode = static_cast<DmDiscoverMode>(mode);
1177 
1178     int32_t medium = -1;
1179     JsObjectToInt(env, object, "medium", medium);
1180     info.medium = static_cast<DmExchangeMedium>(medium);
1181 
1182     int32_t freq = -1;
1183     JsObjectToInt(env, object, "freq", freq);
1184     info.freq = static_cast<DmExchangeFreq>(freq);
1185 
1186     JsObjectToBool(env, object, "isSameAccount", info.isSameAccount);
1187     JsObjectToBool(env, object, "isWakeRemote", info.isWakeRemote);
1188 
1189     int32_t capability = -1;
1190     JsObjectToInt(env, object, "capability", capability);
1191     if (capability == DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP || capability == DM_NAPI_SUBSCRIBE_CAPABILITY_OSD) {
1192         (void)strncpy_s(info.capability, sizeof(info.capability), DM_CAPABILITY_OSD, strlen(DM_CAPABILITY_OSD));
1193     }
1194     return 0;
1195 }
1196 
JsToDmDeviceInfo(const napi_env & env,const napi_value & object,DmDeviceInfo & info)1197 void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value &object, DmDeviceInfo &info)
1198 {
1199     JsObjectToString(env, object, "deviceId", info.deviceId, sizeof(info.deviceId));
1200     JsObjectToString(env, object, "deviceName", info.deviceName, sizeof(info.deviceName));
1201     JsObjectToString(env, object, "networkId", info.networkId, sizeof(info.networkId));
1202     int32_t deviceType = -1;
1203     JsObjectToInt(env, object, "deviceType", deviceType);
1204     info.deviceTypeId = static_cast<DmDeviceType>(deviceType);
1205     JsObjectToInt(env, object, "range", info.range);
1206 }
1207 
JsToDmExtra(const napi_env & env,const napi_value & object,std::string & extra,int32_t & authType)1208 void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &object, std::string &extra,
1209                                     int32_t &authType)
1210 {
1211     LOGI("JsToDmExtra in.");
1212     int32_t authTypeTemp = -1;
1213     JsObjectToInt(env, object, "authType", authTypeTemp);
1214     authType = authTypeTemp;
1215 
1216     char appOperation[DM_NAPI_DESCRIPTION_BUF_LENGTH] = "";
1217     JsObjectToString(env, object, "appOperation", appOperation, sizeof(appOperation));
1218     std::string appOperationStr = appOperation;
1219 
1220     char customDescription[DM_NAPI_DESCRIPTION_BUF_LENGTH] = "";
1221     JsObjectToString(env, object, "customDescription", customDescription, sizeof(customDescription));
1222     std::string customDescriptionStr = customDescription;
1223 
1224     nlohmann::json jsonObj;
1225     jsonObj[AUTH_TYPE] = authType;
1226     jsonObj[APP_OPERATION] = appOperationStr;
1227     jsonObj[CUSTOM_DESCRIPTION] = customDescriptionStr;
1228     JsToJsonObject(env, object, "extraInfo", jsonObj);
1229     extra = jsonObj.dump();
1230     LOGI("appOperationLen %d, customDescriptionLen %d.", appOperationStr.size(), customDescriptionStr.size());
1231 }
1232 
JsToDmBuffer(const napi_env & env,const napi_value & object,const std::string & fieldStr,uint8_t ** bufferPtr,int32_t & bufferLen)1233 void DeviceManagerNapi::JsToDmBuffer(const napi_env &env, const napi_value &object, const std::string &fieldStr,
1234                                      uint8_t **bufferPtr, int32_t &bufferLen)
1235 {
1236     LOGI("JsToDmBuffer in.");
1237     bool hasProperty = false;
1238     NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty));
1239     if (!hasProperty) {
1240         LOGE("devicemanager napi js to str no property: %s", fieldStr.c_str());
1241         return;
1242     }
1243 
1244     napi_value field = nullptr;
1245     napi_get_named_property(env, object, fieldStr.c_str(), &field);
1246     napi_typedarray_type type = napi_uint8_array;
1247     size_t length = 0;
1248     napi_value buffer = nullptr;
1249     size_t offset = 0;
1250     uint8_t *data = nullptr;
1251     napi_get_typedarray_info(env, field, &type, &length, reinterpret_cast<void **>(&data), &buffer, &offset);
1252     if (type != napi_uint8_array || length == 0 || data == nullptr) {
1253         LOGE("Invalid AppIconInfo");
1254         return;
1255     }
1256     *bufferPtr = static_cast<uint8_t *>(calloc(sizeof(uint8_t), length));
1257     if (*bufferPtr == nullptr) {
1258         LOGE("low memory, calloc return nullptr, length is %d, filed %s", length, fieldStr.c_str());
1259         return;
1260     }
1261     if (memcpy_s(*bufferPtr, length, data, length) != 0) {
1262         LOGE("memcpy_s failed, filed %s", fieldStr.c_str());
1263         free(*bufferPtr);
1264         *bufferPtr = nullptr;
1265         return;
1266     }
1267     bufferLen = static_cast<int32_t>(length);
1268 }
1269 
JsToJsonObject(const napi_env & env,const napi_value & object,const std::string & fieldStr,nlohmann::json & jsonObj)1270 void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &object, const std::string &fieldStr,
1271                                        nlohmann::json &jsonObj)
1272 {
1273     bool hasProperty = false;
1274     NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty));
1275     if (!hasProperty) {
1276         LOGE("devicemanager napi js to str no property: %s", fieldStr.c_str());
1277         return;
1278     }
1279 
1280     napi_value jsonField = nullptr;
1281     napi_get_named_property(env, object, fieldStr.c_str(), &jsonField);
1282     napi_valuetype jsValueType = napi_undefined;
1283     napi_value jsProNameList = nullptr;
1284     uint32_t jsProCount = 0;
1285     napi_get_property_names(env, jsonField, &jsProNameList);
1286     napi_get_array_length(env, jsProNameList, &jsProCount);
1287 
1288     napi_value jsProName = nullptr;
1289     napi_value jsProValue = nullptr;
1290     for (uint32_t index = 0; index < jsProCount; index++) {
1291         napi_get_element(env, jsProNameList, index, &jsProName);
1292         std::string strProName = JsObjectToString(env, jsProName);
1293         napi_get_named_property(env, jsonField, strProName.c_str(), &jsProValue);
1294         napi_typeof(env, jsProValue, &jsValueType);
1295         int32_t numberValue = 0;
1296         bool boolValue = false;
1297         std::string stringValue = "";
1298         switch (jsValueType) {
1299             case napi_string:
1300                 stringValue = JsObjectToString(env, jsProValue);
1301                 LOGI("Property name = %s, string, value = %s", strProName.c_str(), stringValue.c_str());
1302                 jsonObj[strProName] = stringValue;
1303                 break;
1304             case napi_boolean:
1305                 napi_get_value_bool(env, jsProValue, &boolValue);
1306                 LOGI("Property name = %s, boolean, value = %d.", strProName.c_str(), boolValue);
1307                 jsonObj[strProName] = boolValue;
1308                 break;
1309             case napi_number:
1310                 if (napi_get_value_int32(env, jsProValue, &numberValue) != napi_ok) {
1311                     LOGE("Property name = %s, Property int32_t parse error", strProName.c_str());
1312                 } else {
1313                     jsonObj[strProName] = numberValue;
1314                     LOGI("Property name = %s, number, value = %d.", strProName.c_str(), numberValue);
1315                 }
1316                 break;
1317             default:
1318                 LOGE("Property name = %s, value type not support.", strProName.c_str());
1319                 break;
1320         }
1321     }
1322 }
1323 
JsToDmAuthInfo(const napi_env & env,const napi_value & object,std::string & extra)1324 void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &object, std::string &extra)
1325 {
1326     LOGI("%s called.", __func__);
1327     int32_t authType = -1;
1328     int32_t token = -1;
1329 
1330     JsObjectToInt(env, object, "authType", authType);
1331     JsObjectToInt(env, object, "token", token);
1332     nlohmann::json jsonObj;
1333     jsonObj[AUTH_TYPE] = authType;
1334     jsonObj[PIN_TOKEN] = token;
1335     JsToJsonObject(env, object, "extraInfo", jsonObj);
1336     extra = jsonObj.dump();
1337 }
1338 
JsToDmDiscoveryExtra(const napi_env & env,const napi_value & object,std::string & extra)1339 void DeviceManagerNapi::JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::string &extra)
1340 {
1341     napi_valuetype valueType1 = napi_undefined;
1342     napi_typeof(env, object, &valueType1);
1343     if (valueType1 == napi_undefined) {
1344         extra = "";
1345         return;
1346     }
1347     char filterOption[DM_NAPI_BUF_LENGTH] = {0};
1348     size_t typeLen = 0;
1349     NAPI_CALL_RETURN_VOID(env, napi_get_value_string_utf8(env, object, nullptr, 0, &typeLen));
1350     if (!CheckArgsVal(env, typeLen > 0, "extra", "typeLen == 0")) {
1351         return;
1352     }
1353 
1354     if (!CheckArgsVal(env, typeLen < DM_NAPI_BUF_LENGTH, "extra", "typeLen >= BUF_MAX_LENGTH")) {
1355         return;
1356     }
1357     NAPI_CALL_RETURN_VOID(env, napi_get_value_string_utf8(env, object, filterOption, typeLen + 1, &typeLen));
1358     extra = filterOption;
1359     LOGI("JsToDmDiscoveryExtra, extra :%s, typeLen : %d", extra.c_str(), typeLen);
1360 }
1361 
IsSystemApp()1362 bool DeviceManagerNapi::IsSystemApp()
1363 {
1364     uint64_t tokenId = OHOS::IPCSkeleton::GetSelfTokenID();
1365     return OHOS::Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(tokenId);
1366 }
1367 
DmDeviceInfotoJsDeviceInfo(const napi_env & env,const DmDeviceInfo & vecDevInfo,napi_value & result)1368 void DeviceManagerNapi::DmDeviceInfotoJsDeviceInfo(const napi_env &env, const DmDeviceInfo &vecDevInfo,
1369                                                    napi_value &result)
1370 {
1371     napi_create_object(env, &result);
1372 
1373     SetValueUtf8String(env, "deviceId", vecDevInfo.deviceId, result);
1374     SetValueUtf8String(env, "networkId", vecDevInfo.networkId, result);
1375     SetValueUtf8String(env, "deviceName", vecDevInfo.deviceName, result);
1376     SetValueInt32(env, "deviceType", (int)vecDevInfo.deviceTypeId, result);
1377 }
1378 
CreateDmCallback(napi_env env,std::string & bundleName,std::string & eventType)1379 void DeviceManagerNapi::CreateDmCallback(napi_env env, std::string &bundleName, std::string &eventType)
1380 {
1381     LOGI("CreateDmCallback for bundleName %s eventType %s", bundleName.c_str(), eventType.c_str());
1382     if (eventType == DM_NAPI_EVENT_DEVICE_STATE_CHANGE) {
1383         auto callback = std::make_shared<DmNapiDeviceStateCallback>(env, bundleName);
1384         std::string extra = "";
1385         int32_t ret = DeviceManager::GetInstance().RegisterDevStateCallback(bundleName, extra, callback);
1386         if (ret != 0) {
1387             LOGE("RegisterDevStateCallback failed for bundleName %s", bundleName.c_str());
1388             return;
1389         }
1390         g_deviceStateCallbackMap.erase(bundleName);
1391         g_deviceStateCallbackMap[bundleName] = callback;
1392         return;
1393     }
1394 
1395     if (eventType == DM_NAPI_EVENT_DEVICE_FOUND || eventType == DM_NAPI_EVENT_DEVICE_DISCOVERY_FAIL) {
1396         auto callback = std::make_shared<DmNapiDiscoveryCallback>(env, bundleName);
1397         g_DiscoveryCallbackMap.erase(bundleName);
1398         g_DiscoveryCallbackMap[bundleName] = callback;
1399         std::shared_ptr<DmNapiDiscoveryCallback> discoveryCallback = callback;
1400         discoveryCallback->IncreaseRefCount();
1401         return;
1402     }
1403 
1404     if (eventType == DM_NAPI_EVENT_DEVICE_PUBLISH_SUCCESS || eventType == DM_NAPI_EVENT_DEVICE_PUBLISH_FAIL) {
1405         auto callback = std::make_shared<DmNapiPublishCallback>(env, bundleName);
1406         g_publishCallbackMap.erase(bundleName);
1407         g_publishCallbackMap[bundleName] = callback;
1408         std::shared_ptr<DmNapiPublishCallback> publishCallback = callback;
1409         publishCallback->IncreaseRefCount();
1410         return;
1411     }
1412 
1413     if (eventType == DM_NAPI_EVENT_UI_STATE_CHANGE) {
1414         auto callback = std::make_shared<DmNapiDeviceManagerUiCallback>(env, bundleName);
1415         int32_t ret = DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(bundleName, callback);
1416         if (ret != 0) {
1417             LOGE("RegisterDeviceManagerFaCallback failed for bundleName %s", bundleName.c_str());
1418             return;
1419         }
1420         g_dmUiCallbackMap.erase(bundleName);
1421         g_dmUiCallbackMap[bundleName] = callback;
1422     }
1423 }
1424 
CreateDmCallback(napi_env env,std::string & bundleName,std::string & eventType,std::string & extra)1425 void DeviceManagerNapi::CreateDmCallback(napi_env env, std::string &bundleName,
1426                                          std::string &eventType, std::string &extra)
1427 {
1428     LOGI("CreateDmCallback for bundleName %s eventType %s extra = %s",
1429          bundleName.c_str(), eventType.c_str(), extra.c_str());
1430     if (eventType == DM_NAPI_EVENT_DEVICE_STATE_CHANGE) {
1431         auto callback = std::make_shared<DmNapiDeviceStateCallback>(env, bundleName);
1432         int32_t ret = DeviceManager::GetInstance().RegisterDevStateCallback(bundleName, extra, callback);
1433         if (ret != 0) {
1434             LOGE("RegisterDevStateCallback failed for bundleName %s", bundleName.c_str());
1435             return;
1436         }
1437         g_deviceStateCallbackMap.erase(bundleName);
1438         g_deviceStateCallbackMap[bundleName] = callback;
1439     }
1440 }
1441 
ReleasePublishCallback(std::string & bundleName)1442 void DeviceManagerNapi::ReleasePublishCallback(std::string &bundleName)
1443 {
1444     std::shared_ptr<DmNapiPublishCallback> publishCallback = nullptr;
1445     auto iter = g_publishCallbackMap.find(bundleName);
1446     if (iter == g_publishCallbackMap.end()) {
1447         return;
1448     }
1449 
1450     publishCallback = iter->second;
1451     publishCallback->DecreaseRefCount();
1452     if (publishCallback->GetRefCount() == 0) {
1453         g_publishCallbackMap.erase(bundleName);
1454     }
1455     return;
1456 }
1457 
ReleaseDmCallback(std::string & bundleName,std::string & eventType)1458 void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string &eventType)
1459 {
1460     if (eventType == DM_NAPI_EVENT_DEVICE_STATE_CHANGE) {
1461         auto iter = g_deviceStateCallbackMap.find(bundleName);
1462         if (iter == g_deviceStateCallbackMap.end()) {
1463             LOGE("ReleaseDmCallback: cannot find stateCallback for bundleName %s", bundleName.c_str());
1464             return;
1465         }
1466         int32_t ret = DeviceManager::GetInstance().UnRegisterDevStateCallback(bundleName);
1467         if (ret != 0) {
1468             LOGE("RegisterDevStateCallback failed for bundleName %s", bundleName.c_str());
1469             return;
1470         }
1471         g_deviceStateCallbackMap.erase(bundleName);
1472         return;
1473     }
1474 
1475     if (eventType == DM_NAPI_EVENT_DEVICE_FOUND || eventType == DM_NAPI_EVENT_DEVICE_DISCOVERY_FAIL) {
1476         std::shared_ptr<DmNapiDiscoveryCallback> DiscoveryCallback = nullptr;
1477         auto iter = g_DiscoveryCallbackMap.find(bundleName);
1478         if (iter == g_DiscoveryCallbackMap.end()) {
1479             return;
1480         }
1481 
1482         DiscoveryCallback = iter->second;
1483         DiscoveryCallback->DecreaseRefCount();
1484         if (DiscoveryCallback->GetRefCount() == 0) {
1485             g_DiscoveryCallbackMap.erase(bundleName);
1486         }
1487         return;
1488     }
1489 
1490     if (eventType == DM_NAPI_EVENT_DEVICE_PUBLISH_SUCCESS || eventType == DM_NAPI_EVENT_DEVICE_PUBLISH_FAIL) {
1491         ReleasePublishCallback(bundleName);
1492         return;
1493     }
1494 
1495     if (eventType == DM_NAPI_EVENT_UI_STATE_CHANGE) {
1496         auto iter = g_dmUiCallbackMap.find(bundleName);
1497         if (iter == g_dmUiCallbackMap.end()) {
1498             LOGE("cannot find dmFaCallback for bundleName %s", bundleName.c_str());
1499             return;
1500         }
1501         int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(bundleName);
1502         if (ret != 0) {
1503             LOGE("RegisterDevStateCallback failed for bundleName %s", bundleName.c_str());
1504             return;
1505         }
1506         g_dmUiCallbackMap.erase(bundleName);
1507         return;
1508     }
1509 }
1510 
GetAuthenticationParamSync(napi_env env,napi_callback_info info)1511 napi_value DeviceManagerNapi::GetAuthenticationParamSync(napi_env env, napi_callback_info info)
1512 {
1513     LOGI("GetAuthenticationParamSync in");
1514     if (!IsSystemApp()) {
1515         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
1516         return nullptr;
1517     }
1518     size_t argc = 0;
1519     napi_value thisVar = nullptr;
1520     napi_value resultParam = nullptr;
1521     napi_value result = nullptr;
1522 
1523     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr));
1524     DeviceManagerNapi *deviceManagerWrapper = nullptr;
1525     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
1526         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
1527         return result;
1528     }
1529     DmAuthParam authParam;
1530     int32_t ret = DeviceManager::GetInstance().GetFaParam(deviceManagerWrapper->bundleName_, authParam);
1531     if (ret != 0) {
1532         LOGE("GetAuthenticationParam for %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
1533         napi_get_undefined(env, &resultParam);
1534         return resultParam;
1535     }
1536     napi_create_object(env, &resultParam);
1537     DmAuthParamToJsAuthParam(env, authParam, resultParam);
1538     return resultParam;
1539 }
1540 
SetUserOperationSync(napi_env env,napi_callback_info info)1541 napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_info info)
1542 {
1543     LOGI("SetUserOperationSync in");
1544     if (!IsSystemApp()) {
1545         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
1546         return nullptr;
1547     }
1548     GET_PARAMS(env, info, DM_NAPI_ARGS_TWO);
1549     napi_valuetype valueType;
1550     napi_typeof(env, argv[0], &valueType);
1551     if (!CheckArgsType(env, valueType == napi_number, "action", "number")) {
1552         return nullptr;
1553     }
1554 
1555     napi_valuetype strType;
1556     napi_typeof(env, argv[1], &strType);
1557     NAPI_ASSERT(env, strType == napi_string, "Wrong argument type, string expected.");
1558 
1559     int32_t action = 0;
1560     napi_get_value_int32(env, argv[0], &action);
1561 
1562     size_t typeLen = 0;
1563     napi_get_value_string_utf8(env, argv[1], nullptr, 0, &typeLen);
1564     NAPI_ASSERT(env, typeLen > 0, "typeLen == 0");
1565     NAPI_ASSERT(env, typeLen < DM_NAPI_BUF_LENGTH, "typeLen >= MAXLEN");
1566     char type[DM_NAPI_BUF_LENGTH] = {0};
1567     napi_get_value_string_utf8(env, argv[1], type, typeLen + 1, &typeLen);
1568 
1569     std::string params = type;
1570     napi_value result = nullptr;
1571     DeviceManagerNapi *deviceManagerWrapper = nullptr;
1572     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
1573         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
1574         return result;
1575     }
1576     int32_t ret = DeviceManager::GetInstance().SetUserOperation(deviceManagerWrapper->bundleName_, action, params);
1577     if (ret != 0) {
1578         LOGE("SetUserOperation for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
1579         CreateBusinessError(env, ret);
1580     }
1581     napi_get_undefined(env, &result);
1582     return result;
1583 }
1584 
CallGetTrustedDeviceListStatusSync(napi_env env,napi_status & status,DeviceInfoListAsyncCallbackInfo * deviceInfoListAsyncCallbackInfo)1585 void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_status &status,
1586     DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo)
1587 {
1588     for (unsigned int i = 0; i < deviceInfoListAsyncCallbackInfo->devList.size(); i++) {
1589         LOGI("DeviceManager::GetTrustedDeviceList deviceId:%s deviceName:%s deviceTypeId:%d ",
1590              GetAnonyString(deviceInfoListAsyncCallbackInfo->devList[i].deviceId).c_str(),
1591              deviceInfoListAsyncCallbackInfo->devList[i].deviceName,
1592              deviceInfoListAsyncCallbackInfo->devList[i].deviceTypeId);
1593     }
1594 
1595     napi_value array[DM_NAPI_ARGS_TWO] = {0};
1596     if (deviceInfoListAsyncCallbackInfo->status == 0) {
1597         bool isArray = false;
1598         napi_create_array(env, &array[1]);
1599         napi_is_array(env, array[1], &isArray);
1600         if (!isArray) {
1601             LOGE("napi_create_array fail");
1602         }
1603         if (deviceInfoListAsyncCallbackInfo->devList.size() > 0) {
1604             for (unsigned int i = 0; i != deviceInfoListAsyncCallbackInfo->devList.size(); ++i) {
1605                 DeviceInfoToJsArray(env, deviceInfoListAsyncCallbackInfo->devList, (int32_t)i, array[1]);
1606             }
1607             LOGI("devList is OK");
1608         } else {
1609             LOGE("devList is null");
1610         }
1611         napi_resolve_deferred(env, deviceInfoListAsyncCallbackInfo->deferred, array[1]);
1612     } else {
1613         array[0] = CreateBusinessError(env, deviceInfoListAsyncCallbackInfo->ret, false);
1614         napi_reject_deferred(env, deviceInfoListAsyncCallbackInfo->deferred, array[0]);
1615     }
1616 }
1617 
OnCall(const std::string & paramJson)1618 void DmNapiDeviceManagerUiCallback::OnCall(const std::string &paramJson)
1619 {
1620     uv_loop_s *loop = nullptr;
1621     napi_get_uv_event_loop(env_, &loop);
1622     if (loop == nullptr) {
1623         return;
1624     }
1625     uv_work_t *work = new (std::nothrow) uv_work_t;
1626     if (work == nullptr) {
1627         LOGE("DmNapiDeviceManagerUiCallback: OnCall, No memory");
1628         return;
1629     }
1630 
1631     DmNapiAuthJsCallback *jsCallback = new DmNapiAuthJsCallback(bundleName_, "", paramJson, 0, 0);
1632     if (jsCallback == nullptr) {
1633         DeleteUvWork(work);
1634         return;
1635     }
1636     work->data = reinterpret_cast<void *>(jsCallback);
1637 
1638     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
1639         DmNapiAuthJsCallback *callback = reinterpret_cast<DmNapiAuthJsCallback *>(work->data);
1640         DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_);
1641         if (deviceManagerNapi == nullptr) {
1642             LOGE("OnCall, deviceManagerNapi not find for bundleName %s", callback->bundleName_.c_str());
1643         } else {
1644             deviceManagerNapi->OnDmUiCall(callback->token_);
1645         }
1646         delete callback;
1647         callback = nullptr;
1648         DeleteUvWork(work);
1649     }, uv_qos_user_initiated);
1650     if (ret != 0) {
1651         LOGE("Failed to execute OnCall work queue");
1652         delete jsCallback;
1653         jsCallback = nullptr;
1654         DeleteUvWork(work);
1655     }
1656 }
1657 
OnDmUiCall(const std::string & paramJson)1658 void DeviceManagerNapi::OnDmUiCall(const std::string &paramJson)
1659 {
1660     LOGI("OnCall for paramJson");
1661     napi_handle_scope scope;
1662     napi_open_handle_scope(env_, &scope);
1663     napi_value result;
1664     napi_create_object(env_, &result);
1665     SetValueUtf8String(env_, "param", paramJson, result);
1666     OnEvent(DM_NAPI_EVENT_UI_STATE_CHANGE, DM_NAPI_ARGS_ONE, &result);
1667     napi_close_handle_scope(env_, scope);
1668 }
1669 
CallGetTrustedDeviceListStatus(napi_env env,napi_status & status,DeviceInfoListAsyncCallbackInfo * deviceInfoListAsyncCallbackInfo)1670 void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status &status,
1671                                                        DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo)
1672 {
1673     for (unsigned int i = 0; i < deviceInfoListAsyncCallbackInfo->devList.size(); i++) {
1674         LOGI("DeviceManager::GetTrustedDeviceList deviceId:%s deviceName:%s deviceTypeId:%d ",
1675              GetAnonyString(deviceInfoListAsyncCallbackInfo->devList[i].deviceId).c_str(),
1676              deviceInfoListAsyncCallbackInfo->devList[i].deviceName,
1677              deviceInfoListAsyncCallbackInfo->devList[i].deviceTypeId);
1678     }
1679     napi_value callResult = nullptr;
1680     napi_value handler = nullptr;
1681     napi_value array[DM_NAPI_ARGS_TWO] = {0};
1682 
1683     if (deviceInfoListAsyncCallbackInfo->status == 0) {
1684         if (deviceInfoListAsyncCallbackInfo->devList.size() > 0) {
1685             bool isArray = false;
1686             NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &array[1]));
1687             NAPI_CALL_RETURN_VOID(env, napi_is_array(env, array[1], &isArray));
1688             if (!isArray) {
1689                 LOGE("napi_create_array fail");
1690             }
1691             for (size_t i = 0; i != deviceInfoListAsyncCallbackInfo->devList.size(); ++i) {
1692                 DeviceInfoToJsArray(env, deviceInfoListAsyncCallbackInfo->devList, i, array[1]);
1693             }
1694             LOGI("devList is OK");
1695         } else {
1696             LOGE("devList is null");
1697         }
1698     } else {
1699         array[0] = CreateBusinessError(env, deviceInfoListAsyncCallbackInfo->ret, false);
1700     }
1701 
1702     NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, deviceInfoListAsyncCallbackInfo->callback, &handler));
1703     if (handler != nullptr) {
1704         NAPI_CALL_RETURN_VOID(env, napi_call_function(env, nullptr, handler, DM_NAPI_ARGS_TWO, &array[0], &callResult));
1705         NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, deviceInfoListAsyncCallbackInfo->callback));
1706     } else {
1707         LOGE("handler is nullptr");
1708     }
1709 }
1710 
CallRequestCreInfoStatus(napi_env env,napi_status & status,CredentialAsyncCallbackInfo * creAsyncCallbackInfo)1711 void DeviceManagerNapi::CallRequestCreInfoStatus(napi_env env, napi_status &status,
1712                                                  CredentialAsyncCallbackInfo *creAsyncCallbackInfo)
1713 {
1714     LOGI("DeviceManager::RequestCredential Info:%s", creAsyncCallbackInfo->returnJsonStr.c_str());
1715     napi_value callResult = nullptr;
1716     napi_value handler = nullptr;
1717     napi_value result = nullptr;
1718     napi_create_object(env, &result);
1719 
1720     if (creAsyncCallbackInfo->status == 0) {
1721         if (creAsyncCallbackInfo->returnJsonStr == "") {
1722             LOGE("creAsyncCallbackInfo returnJsonStr is null");
1723         }
1724         SetValueUtf8String(env, "registerInfo", creAsyncCallbackInfo->returnJsonStr, result);
1725     } else {
1726         result = CreateBusinessError(env, creAsyncCallbackInfo->ret, false);
1727     }
1728 
1729     napi_get_reference_value(env, creAsyncCallbackInfo->callback, &handler);
1730     if (handler != nullptr) {
1731         napi_call_function(env, nullptr, handler, DM_NAPI_ARGS_ONE, &result, &callResult);
1732         napi_delete_reference(env, creAsyncCallbackInfo->callback);
1733     } else {
1734         LOGE("handler is nullptr");
1735     }
1736 }
1737 
CallGetLocalDeviceInfoSync(napi_env env,napi_status & status,DeviceInfoAsyncCallbackInfo * deviceInfoAsyncCallbackInfo)1738 void DeviceManagerNapi::CallGetLocalDeviceInfoSync(napi_env env, napi_status &status,
1739                                                    DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo)
1740 {
1741     napi_value result[DM_NAPI_ARGS_TWO] = {0};
1742 
1743     LOGI("DeviceManager::CallGetLocalDeviceInfoSync deviceId:%s deviceName:%s deviceTypeId:%d ",
1744          GetAnonyString(deviceInfoAsyncCallbackInfo->deviceInfo.deviceId).c_str(),
1745          deviceInfoAsyncCallbackInfo->deviceInfo.deviceName,
1746          deviceInfoAsyncCallbackInfo->deviceInfo.deviceTypeId);
1747 
1748     if (deviceInfoAsyncCallbackInfo->status == 0) {
1749         DmDeviceInfotoJsDeviceInfo(env, deviceInfoAsyncCallbackInfo->deviceInfo, result[1]);
1750         napi_resolve_deferred(env, deviceInfoAsyncCallbackInfo->deferred, result[1]);
1751     } else {
1752         result[0] = CreateBusinessError(env, deviceInfoAsyncCallbackInfo->ret, false);
1753         napi_reject_deferred(env, deviceInfoAsyncCallbackInfo->deferred, result[0]);
1754     }
1755 }
1756 
CallGetLocalDeviceInfo(napi_env env,napi_status & status,DeviceInfoAsyncCallbackInfo * deviceInfoAsyncCallbackInfo)1757 void DeviceManagerNapi::CallGetLocalDeviceInfo(napi_env env, napi_status &status,
1758                                                DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo)
1759 {
1760     napi_value result[DM_NAPI_ARGS_TWO] = {0};
1761     LOGI("DeviceManager::CallGetLocalDeviceInfo deviceId:%s deviceName:%s deviceTypeId:%d ",
1762          GetAnonyString(deviceInfoAsyncCallbackInfo->deviceInfo.deviceId).c_str(),
1763          deviceInfoAsyncCallbackInfo->deviceInfo.deviceName,
1764          deviceInfoAsyncCallbackInfo->deviceInfo.deviceTypeId);
1765     napi_value callResult = nullptr;
1766     napi_value handler = nullptr;
1767 
1768     if (deviceInfoAsyncCallbackInfo->status == 0) {
1769         DmDeviceInfotoJsDeviceInfo(env, deviceInfoAsyncCallbackInfo->deviceInfo, result[1]);
1770     } else {
1771         result[0] = CreateBusinessError(env, deviceInfoAsyncCallbackInfo->ret, false);
1772     }
1773 
1774     NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, deviceInfoAsyncCallbackInfo->callback, &handler));
1775     if (handler != nullptr) {
1776         NAPI_CALL_RETURN_VOID(env, napi_call_function(env, nullptr, handler, DM_NAPI_ARGS_TWO,
1777             &result[0], &callResult));
1778         NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, deviceInfoAsyncCallbackInfo->callback));
1779     } else {
1780         LOGE("handler is nullptr");
1781     }
1782 }
1783 
CallAsyncWorkSync(napi_env env,DeviceInfoAsyncCallbackInfo * deviceInfoAsyncCallbackInfo)1784 void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo)
1785 {
1786     napi_value resourceName;
1787     napi_create_string_latin1(env, "GetLocalDeviceInfo", NAPI_AUTO_LENGTH, &resourceName);
1788     napi_create_async_work(
1789         env, nullptr, resourceName,
1790         [](napi_env env, void *data) {
1791             (void)env;
1792             DeviceInfoAsyncCallbackInfo *devInfoAsyncCallbackInfo =
1793                 reinterpret_cast<DeviceInfoAsyncCallbackInfo *>(data);
1794             int32_t ret = 0;
1795             ret = DeviceManager::GetInstance().GetLocalDeviceInfo(devInfoAsyncCallbackInfo->bundleName,
1796                                                                   devInfoAsyncCallbackInfo->deviceInfo);
1797             if (ret != 0) {
1798                 LOGE("CallAsyncWorkSync for bundleName %s failed, ret %d",
1799                      devInfoAsyncCallbackInfo->bundleName.c_str(), ret);
1800                 devInfoAsyncCallbackInfo->status = -1;
1801                 devInfoAsyncCallbackInfo->ret = ret;
1802             } else {
1803                 devInfoAsyncCallbackInfo->status = 0;
1804                 LOGI("CallAsyncWorkSync status %d", devInfoAsyncCallbackInfo->status);
1805             }
1806         },
1807         [](napi_env env, napi_status status, void *data) {
1808             (void)status;
1809             DeviceInfoAsyncCallbackInfo *dInfoAsyncCallbackInfo =
1810                 reinterpret_cast<DeviceInfoAsyncCallbackInfo *>(data);
1811             CallGetLocalDeviceInfoSync(env, status, dInfoAsyncCallbackInfo);
1812             napi_delete_async_work(env, dInfoAsyncCallbackInfo->asyncWork);
1813             delete dInfoAsyncCallbackInfo;
1814         },
1815         (void *)deviceInfoAsyncCallbackInfo, &deviceInfoAsyncCallbackInfo->asyncWork);
1816     napi_queue_async_work_with_qos(env, deviceInfoAsyncCallbackInfo->asyncWork, napi_qos_user_initiated);
1817 }
1818 
CallAsyncWork(napi_env env,DeviceInfoAsyncCallbackInfo * deviceInfoAsyncCallbackInfo)1819 void DeviceManagerNapi::CallAsyncWork(napi_env env, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo)
1820 {
1821     napi_value resourceName;
1822     napi_create_string_latin1(env, "GetLocalDeviceInfo", NAPI_AUTO_LENGTH, &resourceName);
1823     napi_create_async_work(
1824         env, nullptr, resourceName,
1825         [](napi_env env, void *data) {
1826             DeviceInfoAsyncCallbackInfo *devInfoAsyncCallbackInfo =
1827                 reinterpret_cast<DeviceInfoAsyncCallbackInfo *>(data);
1828             int32_t ret = 0;
1829             ret = DeviceManager::GetInstance().GetLocalDeviceInfo(devInfoAsyncCallbackInfo->bundleName,
1830                                                                   devInfoAsyncCallbackInfo->deviceInfo);
1831             if (ret != 0) {
1832                 LOGE("CallAsyncWork for bundleName %s failed, ret %d",
1833                      devInfoAsyncCallbackInfo->bundleName.c_str(), ret);
1834                 devInfoAsyncCallbackInfo->status = -1;
1835                 devInfoAsyncCallbackInfo->ret = ret;
1836             } else {
1837                 devInfoAsyncCallbackInfo->status = 0;
1838                 LOGI("CallAsyncWork status %d", devInfoAsyncCallbackInfo->status);
1839             }
1840         },
1841         [](napi_env env, napi_status status, void *data) {
1842             (void)status;
1843             DeviceInfoAsyncCallbackInfo *dInfoAsyncCallbackInfo =
1844                 reinterpret_cast<DeviceInfoAsyncCallbackInfo *>(data);
1845             CallGetLocalDeviceInfo(env, status, dInfoAsyncCallbackInfo);
1846             napi_delete_async_work(env, dInfoAsyncCallbackInfo->asyncWork);
1847             delete dInfoAsyncCallbackInfo;
1848         },
1849         (void *)deviceInfoAsyncCallbackInfo, &deviceInfoAsyncCallbackInfo->asyncWork);
1850     napi_queue_async_work_with_qos(env, deviceInfoAsyncCallbackInfo->asyncWork, napi_qos_user_initiated);
1851 }
1852 
CallAsyncWorkSync(napi_env env,DeviceInfoListAsyncCallbackInfo * deviceInfoListAsyncCallbackInfo)1853 void DeviceManagerNapi::CallAsyncWorkSync(napi_env env,
1854                                           DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo)
1855 {
1856     napi_value resourceName;
1857     napi_create_string_latin1(env, "GetTrustListInfo", NAPI_AUTO_LENGTH, &resourceName);
1858     napi_create_async_work(
1859         env, nullptr, resourceName,
1860         [](napi_env env, void *data) {
1861             (void)env;
1862             DeviceInfoListAsyncCallbackInfo *devInfoListAsyncCallbackInfo =
1863                 reinterpret_cast<DeviceInfoListAsyncCallbackInfo *>(data);
1864             int32_t ret = 0;
1865             ret = DeviceManager::GetInstance().GetTrustedDeviceList(devInfoListAsyncCallbackInfo->bundleName,
1866                                                                     devInfoListAsyncCallbackInfo->extra,
1867                                                                     devInfoListAsyncCallbackInfo->devList);
1868             if (ret != 0) {
1869                 LOGE("CallAsyncWorkSync for bundleName %s failed, ret %d",
1870                      devInfoListAsyncCallbackInfo->bundleName.c_str(), ret);
1871                      devInfoListAsyncCallbackInfo->status = -1;
1872                      devInfoListAsyncCallbackInfo->ret = ret;
1873             } else {
1874                 devInfoListAsyncCallbackInfo->status = 0;
1875             }
1876             LOGI("CallAsyncWorkSync status %d", devInfoListAsyncCallbackInfo->status);
1877         },
1878         [](napi_env env, napi_status status, void *data) {
1879             (void)status;
1880             DeviceInfoListAsyncCallbackInfo *dInfoListAsyncCallbackInfo =
1881                 reinterpret_cast<DeviceInfoListAsyncCallbackInfo *>(data);
1882             CallGetTrustedDeviceListStatusSync(env, status, dInfoListAsyncCallbackInfo);
1883             napi_delete_async_work(env, dInfoListAsyncCallbackInfo->asyncWork);
1884             delete dInfoListAsyncCallbackInfo;
1885         },
1886         (void *)deviceInfoListAsyncCallbackInfo, &deviceInfoListAsyncCallbackInfo->asyncWork);
1887     napi_queue_async_work_with_qos(env, deviceInfoListAsyncCallbackInfo->asyncWork, napi_qos_user_initiated);
1888 }
1889 
CallAsyncWork(napi_env env,DeviceInfoListAsyncCallbackInfo * deviceInfoListAsyncCallbackInfo)1890 void DeviceManagerNapi::CallAsyncWork(napi_env env, DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo)
1891 {
1892     napi_value resourceName;
1893     napi_create_string_latin1(env, "GetTrustListInfo", NAPI_AUTO_LENGTH, &resourceName);
1894     napi_create_async_work(
1895         env, nullptr, resourceName,
1896         [](napi_env env, void *data) {
1897             DeviceInfoListAsyncCallbackInfo *devInfoListAsyncCallbackInfo =
1898                 reinterpret_cast<DeviceInfoListAsyncCallbackInfo *>(data);
1899             int32_t ret = 0;
1900             ret = DeviceManager::GetInstance().GetTrustedDeviceList(devInfoListAsyncCallbackInfo->bundleName,
1901                                                                     devInfoListAsyncCallbackInfo->extra,
1902                                                                     devInfoListAsyncCallbackInfo->devList);
1903             if (ret != 0) {
1904                 LOGE("CallAsyncWork for bundleName %s failed, ret %d",
1905                     devInfoListAsyncCallbackInfo->bundleName.c_str(), ret);
1906                 devInfoListAsyncCallbackInfo->status = -1;
1907                 devInfoListAsyncCallbackInfo->ret = ret;
1908             } else {
1909                 devInfoListAsyncCallbackInfo->status = 0;
1910             }
1911             LOGI("CallAsyncWork status %d", devInfoListAsyncCallbackInfo->status);
1912         },
1913         [](napi_env env, napi_status status, void *data) {
1914             (void)status;
1915             DeviceInfoListAsyncCallbackInfo *dInfoListAsyncCallbackInfo =
1916                 reinterpret_cast<DeviceInfoListAsyncCallbackInfo *>(data);
1917             CallGetTrustedDeviceListStatus(env, status, dInfoListAsyncCallbackInfo);
1918             napi_delete_async_work(env, dInfoListAsyncCallbackInfo->asyncWork);
1919             delete dInfoListAsyncCallbackInfo;
1920             dInfoListAsyncCallbackInfo = nullptr;
1921         },
1922         (void *)deviceInfoListAsyncCallbackInfo, &deviceInfoListAsyncCallbackInfo->asyncWork);
1923     napi_queue_async_work_with_qos(env, deviceInfoListAsyncCallbackInfo->asyncWork, napi_qos_user_initiated);
1924 }
1925 
AsyncTaskCallback(napi_env env,void * data)1926 void DeviceManagerNapi::AsyncTaskCallback(napi_env env, void *data)
1927 {
1928     CredentialAsyncCallbackInfo *creAsyncCallbackInfo = reinterpret_cast<CredentialAsyncCallbackInfo *>(data);
1929     int32_t ret = DeviceManager::GetInstance().RequestCredential(creAsyncCallbackInfo->bundleName,
1930         creAsyncCallbackInfo->reqInfo, creAsyncCallbackInfo->returnJsonStr);
1931     if (ret != 0) {
1932         LOGE("CallCredentialAsyncWork for bundleName %s failed, ret %d",
1933             creAsyncCallbackInfo->bundleName.c_str(), ret);
1934         creAsyncCallbackInfo->status = -1;
1935         creAsyncCallbackInfo->ret = ret;
1936     } else {
1937         creAsyncCallbackInfo->status = 0;
1938     }
1939     LOGI("CallCredentialAsyncWork status %d", creAsyncCallbackInfo->status);
1940 }
1941 
AsyncAfterTaskCallback(napi_env env,napi_status status,void * data)1942 void DeviceManagerNapi::AsyncAfterTaskCallback(napi_env env, napi_status status, void *data)
1943 {
1944     (void)status;
1945     CredentialAsyncCallbackInfo *creAsyncCallbackInfo = reinterpret_cast<CredentialAsyncCallbackInfo *>(data);
1946     CallRequestCreInfoStatus(env, status, creAsyncCallbackInfo);
1947     napi_delete_async_work(env, creAsyncCallbackInfo->asyncWork);
1948     delete creAsyncCallbackInfo;
1949 }
1950 
CallCredentialAsyncWork(napi_env env,CredentialAsyncCallbackInfo * creAsyncCallbackInfo)1951 void DeviceManagerNapi::CallCredentialAsyncWork(napi_env env, CredentialAsyncCallbackInfo *creAsyncCallbackInfo)
1952 {
1953     napi_value resourceName;
1954     napi_create_string_latin1(env, "RequestCreInfo", NAPI_AUTO_LENGTH, &resourceName);
1955 
1956     napi_create_async_work(env, nullptr, resourceName, AsyncTaskCallback, AsyncAfterTaskCallback,
1957         (void *)creAsyncCallbackInfo, &creAsyncCallbackInfo->asyncWork);
1958     napi_queue_async_work_with_qos(env, creAsyncCallbackInfo->asyncWork, napi_qos_user_initiated);
1959 }
1960 
CallDeviceList(napi_env env,napi_callback_info info,DeviceInfoListAsyncCallbackInfo * deviceInfoListAsyncCallbackInfo)1961 napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info info,
1962                                              DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo)
1963 {
1964     napi_value result = nullptr;
1965     std::string extra = "";
1966     deviceInfoListAsyncCallbackInfo->extra = extra;
1967     GET_PARAMS(env, info, DM_NAPI_ARGS_ONE);
1968     napi_valuetype eventHandleType = napi_undefined;
1969     napi_typeof(env, argv[0], &eventHandleType);
1970     if (eventHandleType == napi_function) {
1971         LOGI("CallDeviceList for argc %d Type = %d", argc, (int)eventHandleType);
1972         napi_create_reference(env, argv[0], 1, &deviceInfoListAsyncCallbackInfo->callback);
1973         CallAsyncWork(env, deviceInfoListAsyncCallbackInfo);
1974         napi_get_undefined(env, &result);
1975         return result;
1976     } else {
1977         LOGI("CallDeviceList for argc %d Type = %d", argc, (int)eventHandleType);
1978         napi_deferred deferred;
1979         napi_value promise = 0;
1980         napi_create_promise(env, &deferred, &promise);
1981         deviceInfoListAsyncCallbackInfo->deferred = deferred;
1982         char extraString[20];
1983         JsObjectToString(env, argv[0], "extra", extraString, sizeof(extraString));
1984         deviceInfoListAsyncCallbackInfo->extra = extraString;
1985         CallAsyncWorkSync(env, deviceInfoListAsyncCallbackInfo);
1986         return promise;
1987     }
1988 }
1989 
GetTrustedDeviceListSync(napi_env env,napi_callback_info info)1990 napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callback_info info)
1991 {
1992     LOGI("GetTrustedDeviceListSync in");
1993     if (!IsSystemApp()) {
1994         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
1995         return nullptr;
1996     }
1997     int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission();
1998     if (ret != 0) {
1999         CreateBusinessError(env, ret);
2000         return nullptr;
2001     }
2002     napi_value result = nullptr;
2003     napi_value thisVar = nullptr;
2004     size_t argc = 0;
2005     bool isArray = false;
2006     napi_create_array(env, &result);
2007     napi_is_array(env, result, &isArray);
2008     if (!isArray) {
2009         LOGE("napi_create_array fail");
2010     }
2011     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr));
2012     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2013     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2014         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2015         return result;
2016     }
2017 
2018     std::vector<OHOS::DistributedHardware::DmDeviceInfo> devList;
2019     if (argc == DM_NAPI_ARGS_ZERO) {
2020         std::string extra = "";
2021         int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceManagerWrapper->bundleName_, extra,
2022             devList);
2023         if (ret != 0) {
2024             LOGE("GetTrustedDeviceList for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(),
2025                 ret);
2026             CreateBusinessError(env, ret);
2027             return result;
2028         }
2029     } else if (argc == DM_NAPI_ARGS_ONE) {
2030         GET_PARAMS(env, info, DM_NAPI_ARGS_ONE);
2031         napi_valuetype valueType;
2032         napi_typeof(env, argv[0], &valueType);
2033         if (!CheckArgsType(env, valueType == napi_boolean, "refreshList", "bool")) {
2034             return nullptr;
2035         }
2036         bool isRefresh = false;
2037         napi_get_value_bool(env, argv[0], &isRefresh);
2038         std::string extra = "";
2039         int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceManagerWrapper->bundleName_, extra,
2040             isRefresh, devList);
2041         if (ret != 0) {
2042             LOGE("GetTrustedDeviceList for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(),
2043                 ret);
2044             CreateBusinessError(env, ret);
2045             return result;
2046         }
2047     }
2048 
2049     LOGI("DeviceManager::GetTrustedDeviceListSync");
2050     if (devList.size() > 0) {
2051         for (size_t i = 0; i != devList.size(); ++i) {
2052             DeviceInfoToJsArray(env, devList, (int32_t)i, result);
2053         }
2054     }
2055     return result;
2056 }
2057 
GetTrustedDeviceListPromise(napi_env env,DeviceInfoListAsyncCallbackInfo * deviceInfoListAsyncCallbackInfo)2058 napi_value DeviceManagerNapi::GetTrustedDeviceListPromise(napi_env env,
2059     DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo)
2060 {
2061     std::string extra = "";
2062     deviceInfoListAsyncCallbackInfo->extra = extra;
2063     napi_deferred deferred;
2064     napi_value promise = 0;
2065     napi_create_promise(env, &deferred, &promise);
2066     deviceInfoListAsyncCallbackInfo->deferred = deferred;
2067     CallAsyncWorkSync(env, deviceInfoListAsyncCallbackInfo);
2068     return promise;
2069 }
2070 
GetTrustedDeviceListByFilter(napi_env env,napi_callback_info info,DeviceInfoListAsyncCallbackInfo * deviceInfoListAsyncCallbackInfo)2071 napi_value DeviceManagerNapi::GetTrustedDeviceListByFilter(napi_env env, napi_callback_info info,
2072     DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo)
2073 {
2074     napi_value result = nullptr;
2075     napi_get_undefined(env, &result);
2076     GET_PARAMS(env, info, DM_NAPI_ARGS_TWO);
2077     napi_valuetype valueType;
2078     napi_typeof(env, argv[0], &valueType);
2079     if (!CheckArgsType(env, valueType == napi_string, "extra", "string")) {
2080         DeleteAsyncCallbackInfo(deviceInfoListAsyncCallbackInfo);
2081         return nullptr;
2082     }
2083 
2084     if (!IsFunctionType(env, argv[1])) {
2085         DeleteAsyncCallbackInfo(deviceInfoListAsyncCallbackInfo);
2086         return result;
2087     }
2088     char extra[DM_NAPI_BUF_LENGTH];
2089     JsObjectToString(env, argv[0], "extra", extra, sizeof(extra));
2090     deviceInfoListAsyncCallbackInfo->extra = extra;
2091     napi_create_reference(env, argv[1], 1, &deviceInfoListAsyncCallbackInfo->callback);
2092     CallAsyncWork(env, deviceInfoListAsyncCallbackInfo);
2093     return result;
2094 }
2095 
GetTrustedDeviceList(napi_env env,napi_callback_info info)2096 napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_info info)
2097 {
2098     if (!IsSystemApp()) {
2099         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2100         return nullptr;
2101     }
2102     int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission();
2103     if (ret != 0) {
2104         CreateBusinessError(env, ret);
2105         return nullptr;
2106     }
2107     napi_value result = nullptr;
2108     napi_value thisVar = nullptr;
2109     size_t argc = 0;
2110     std::vector<DmDeviceInfo> devList;
2111     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr));
2112 
2113     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2114     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2115         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2116         return result;
2117     }
2118 
2119     auto *deviceInfoListAsyncCallbackInfo = new DeviceInfoListAsyncCallbackInfo();
2120     if (deviceInfoListAsyncCallbackInfo == nullptr) {
2121         return nullptr;
2122     }
2123     deviceInfoListAsyncCallbackInfo->env = env;
2124     deviceInfoListAsyncCallbackInfo->devList = devList;
2125     deviceInfoListAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_;
2126     if (argc == 0) {
2127         return GetTrustedDeviceListPromise(env, deviceInfoListAsyncCallbackInfo);
2128     } else if (argc == 1) {
2129         GET_PARAMS(env, info, DM_NAPI_ARGS_ONE);
2130         if (!IsFunctionType(env, argv[0])) {
2131             DeleteAsyncCallbackInfo(deviceInfoListAsyncCallbackInfo);
2132             return nullptr;
2133         }
2134         return CallDeviceList(env, info, deviceInfoListAsyncCallbackInfo);
2135     } else if (argc == DM_NAPI_ARGS_TWO) {
2136         return GetTrustedDeviceListByFilter(env, info, deviceInfoListAsyncCallbackInfo);
2137     }
2138     napi_get_undefined(env, &result);
2139     return result;
2140 }
2141 
GetLocalDeviceInfoSync(napi_env env,napi_callback_info info)2142 napi_value DeviceManagerNapi::GetLocalDeviceInfoSync(napi_env env, napi_callback_info info)
2143 {
2144     LOGI("GetLocalDeviceInfoSync in");
2145     if (!IsSystemApp()) {
2146         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2147         return nullptr;
2148     }
2149     int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission();
2150     if (ret != 0) {
2151         CreateBusinessError(env, ret);
2152         return nullptr;
2153     }
2154     napi_value result = nullptr;
2155     napi_value thisVar = nullptr;
2156     DmDeviceInfo deviceInfo;
2157     size_t argc = 0;
2158 
2159     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr));
2160     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2161     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2162         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2163         return result;
2164     }
2165 
2166     ret = DeviceManager::GetInstance().GetLocalDeviceInfo(deviceManagerWrapper->bundleName_, deviceInfo);
2167     if (ret != 0) {
2168         LOGE("GetLocalDeviceInfoSync for failed, ret %d", ret);
2169         CreateBusinessError(env, ret);
2170         return result;
2171     }
2172     LOGI("DeviceManager::GetLocalDeviceInfoSync deviceId:%s deviceName:%s deviceTypeId:%d ",
2173          GetAnonyString(std::string(deviceInfo.deviceId)).c_str(), deviceInfo.deviceName, deviceInfo.deviceTypeId);
2174     DmDeviceInfotoJsDeviceInfo(env, deviceInfo, result);
2175     return result;
2176 }
2177 
GetLocalDeviceInfo(napi_env env,napi_callback_info info)2178 napi_value DeviceManagerNapi::GetLocalDeviceInfo(napi_env env, napi_callback_info info)
2179 {
2180     LOGI("GetLocalDeviceInfo in");
2181     if (!IsSystemApp()) {
2182         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2183         return nullptr;
2184     }
2185     if (DeviceManager::GetInstance().CheckAPIAccessPermission() != 0) {
2186         CreateBusinessError(env, ERR_DM_NO_PERMISSION);
2187         return nullptr;
2188     }
2189     napi_value result = nullptr;
2190     napi_value thisVar = nullptr;
2191     size_t argc = 0;
2192     DmDeviceInfo deviceInfo;
2193     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr));
2194     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2195     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2196         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2197         return result;
2198     }
2199     auto *deviceInfoAsyncCallbackInfo = new DeviceInfoAsyncCallbackInfo();
2200     if (deviceInfoAsyncCallbackInfo == nullptr) {
2201         return nullptr;
2202     }
2203     deviceInfoAsyncCallbackInfo->env = env;
2204     deviceInfoAsyncCallbackInfo->deviceInfo = deviceInfo;
2205     deviceInfoAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_;
2206     if (argc == 0) {
2207         std::string extra = "";
2208         deviceInfoAsyncCallbackInfo->extra = extra;
2209         napi_deferred deferred;
2210         napi_value promise = 0;
2211         napi_create_promise(env, &deferred, &promise);
2212         deviceInfoAsyncCallbackInfo->deferred = deferred;
2213         CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo);
2214         return promise;
2215     } else if (argc == 1) {
2216         GET_PARAMS(env, info, DM_NAPI_ARGS_ONE);
2217         if (!IsFunctionType(env, argv[0])) {
2218             delete deviceInfoAsyncCallbackInfo;
2219             deviceInfoAsyncCallbackInfo = nullptr;
2220             return nullptr;
2221         }
2222         deviceInfoAsyncCallbackInfo->extra = "";
2223         napi_create_reference(env, argv[0], 1, &deviceInfoAsyncCallbackInfo->callback);
2224         CallAsyncWork(env, deviceInfoAsyncCallbackInfo);
2225     }
2226     napi_get_undefined(env, &result);
2227     return result;
2228 }
2229 
UnAuthenticateDevice(napi_env env,napi_callback_info info)2230 napi_value DeviceManagerNapi::UnAuthenticateDevice(napi_env env, napi_callback_info info)
2231 {
2232     LOGI("UnAuthenticateDevice");
2233     if (!IsSystemApp()) {
2234         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2235         return nullptr;
2236     }
2237     napi_value result = nullptr;
2238     GET_PARAMS(env, info, DM_NAPI_ARGS_ONE);
2239     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_ONE,  "Wrong number of arguments, required 1")) {
2240         return nullptr;
2241     }
2242     napi_valuetype deviceInfoType = napi_undefined;
2243     napi_typeof(env, argv[0], &deviceInfoType);
2244     if (!CheckArgsType(env, deviceInfoType == napi_object, "deviceInfo", "object")) {
2245         return nullptr;
2246     }
2247 
2248     DmDeviceInfo deviceInfo;
2249     JsToDmDeviceInfo(env, argv[0], deviceInfo);
2250     LOGI("UnAuthenticateDevice deviceId = %s", GetAnonyString(deviceInfo.deviceId).c_str());
2251     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2252     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2253         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2254         return result;
2255     }
2256 
2257     int32_t ret = DeviceManager::GetInstance().UnAuthenticateDevice(deviceManagerWrapper->bundleName_, deviceInfo);
2258     if (ret != 0) {
2259         LOGE("UnAuthenticateDevice for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
2260         CreateBusinessError(env, ret);
2261     }
2262 
2263     napi_create_int32(env, ret, &result);
2264     return result;
2265 }
2266 
StartArgCheck(napi_env env,napi_value & argv,OHOS::DistributedHardware::DmSubscribeInfo & subInfo)2267 bool DeviceManagerNapi::StartArgCheck(napi_env env, napi_value &argv,
2268     OHOS::DistributedHardware::DmSubscribeInfo &subInfo)
2269 {
2270     napi_valuetype valueType = napi_undefined;
2271     napi_typeof(env, argv, &valueType);
2272     if (!CheckArgsType(env, valueType == napi_object, "subscribeInfo", "object")) {
2273         return false;
2274     }
2275     int32_t res = JsToDmSubscribeInfo(env, argv, subInfo);
2276     if (!CheckArgsVal(env, res == 0, "subscribeId", "Wrong subscribeId")) {
2277         return false;
2278     }
2279     return true;
2280 }
2281 
StartDeviceDiscoverSync(napi_env env,napi_callback_info info)2282 napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callback_info info)
2283 {
2284     LOGI("StartDeviceDiscoverSync in");
2285     if (!IsSystemApp()) {
2286         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2287         return nullptr;
2288     }
2289     std::string extra = "";
2290     DmSubscribeInfo subInfo;
2291     napi_value result = nullptr;
2292     napi_value thisVar = nullptr;
2293     size_t argcNum = 0;
2294     NAPI_CALL(env, napi_get_cb_info(env, info, &argcNum, nullptr, &thisVar, nullptr));
2295     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2296     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2297         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2298         return result;
2299     }
2300     if (argcNum >= DM_NAPI_ARGS_ONE) {
2301         GET_PARAMS(env, info, DM_NAPI_ARGS_TWO);
2302         if (!StartArgCheck(env, argv[0], subInfo)) {
2303             return nullptr;
2304         }
2305         if (argcNum == DM_NAPI_ARGS_TWO) {
2306             napi_valuetype valueType1 = napi_undefined;
2307             napi_typeof(env, argv[1], &valueType1);
2308             if (!(CheckArgsType(env, (valueType1 == napi_undefined || valueType1 == napi_string), "filterOptions",
2309                 "string or undefined"))) {
2310                 return nullptr;
2311             }
2312             JsToDmDiscoveryExtra(env, argv[1], extra);
2313         }
2314     }
2315     std::shared_ptr<DmNapiDiscoveryCallback> DiscoveryCallback = nullptr;
2316     auto iter = g_DiscoveryCallbackMap.find(deviceManagerWrapper->bundleName_);
2317     if (iter == g_DiscoveryCallbackMap.end()) {
2318         DiscoveryCallback = std::make_shared<DmNapiDiscoveryCallback>(env, deviceManagerWrapper->bundleName_);
2319         g_DiscoveryCallbackMap[deviceManagerWrapper->bundleName_] = DiscoveryCallback;
2320     } else {
2321         DiscoveryCallback = iter->second;
2322     }
2323     int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(deviceManagerWrapper->bundleName_, subInfo, extra,
2324                                                                     DiscoveryCallback);
2325     if (ret != 0) {
2326         LOGE("StartDeviceDiscovery for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
2327         CreateBusinessError(env, ret);
2328         DiscoveryCallback->OnDiscoveryFailed(subInfo.subscribeId, ret);
2329     }
2330     napi_get_undefined(env, &result);
2331     return result;
2332 }
2333 
StopDeviceDiscoverSync(napi_env env,napi_callback_info info)2334 napi_value DeviceManagerNapi::StopDeviceDiscoverSync(napi_env env, napi_callback_info info)
2335 {
2336     LOGI("StopDeviceDiscoverSync in");
2337     if (!IsSystemApp()) {
2338         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2339         return nullptr;
2340     }
2341     GET_PARAMS(env, info, DM_NAPI_ARGS_ONE);
2342     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_ONE,  "Wrong number of arguments, required 1")) {
2343         return nullptr;
2344     }
2345 
2346     napi_value result = nullptr;
2347     napi_valuetype valueType = napi_undefined;
2348     napi_typeof(env, argv[0], &valueType);
2349     if (!CheckArgsType(env, valueType == napi_number, "subscribeId", "number")) {
2350         return nullptr;
2351     }
2352 
2353     int32_t subscribeId = 0;
2354     napi_get_value_int32(env, argv[0], &subscribeId);
2355     if (!CheckArgsVal(env, subscribeId <= DM_NAPI_SUB_ID_MAX, "subscribeId", "Wrong argument. subscribeId Too Big")) {
2356         return nullptr;
2357     }
2358     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2359     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2360         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2361         return result;
2362     }
2363     int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(deviceManagerWrapper->bundleName_,
2364                                                                    static_cast<int16_t>(subscribeId));
2365     if (ret != 0) {
2366         LOGE("StopDeviceDiscovery for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
2367         CreateBusinessError(env, ret);
2368         return result;
2369     }
2370 
2371     napi_get_undefined(env, &result);
2372     return result;
2373 }
2374 
PublishDeviceDiscoverySync(napi_env env,napi_callback_info info)2375 napi_value DeviceManagerNapi::PublishDeviceDiscoverySync(napi_env env, napi_callback_info info)
2376 {
2377     LOGI("PublishDeviceDiscoverySync in");
2378     if (!IsSystemApp()) {
2379         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2380         return nullptr;
2381     }
2382     GET_PARAMS(env, info, DM_NAPI_ARGS_ONE);
2383     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_ONE,  "Wrong number of arguments, required 1")) {
2384         return nullptr;
2385     }
2386 
2387     napi_value result = nullptr;
2388     napi_valuetype valueType = napi_undefined;
2389     napi_typeof(env, argv[0], &valueType);
2390     if (!CheckArgsType(env, valueType == napi_object, "publishInfo", "object")) {
2391         return nullptr;
2392     }
2393     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2394     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2395         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2396         return result;
2397     }
2398 
2399     std::shared_ptr<DmNapiPublishCallback> publishCallback = nullptr;
2400     auto iter = g_publishCallbackMap.find(deviceManagerWrapper->bundleName_);
2401     if (iter == g_publishCallbackMap.end()) {
2402         publishCallback = std::make_shared<DmNapiPublishCallback>(env, deviceManagerWrapper->bundleName_);
2403         g_publishCallbackMap[deviceManagerWrapper->bundleName_] = publishCallback;
2404     } else {
2405         publishCallback = iter->second;
2406     }
2407 
2408     DmPublishInfo publishInfo;
2409     JsToDmPublishInfo(env, argv[0], publishInfo);
2410     int32_t ret = DeviceManager::GetInstance().PublishDeviceDiscovery(deviceManagerWrapper->bundleName_, publishInfo,
2411         publishCallback);
2412     if (ret != 0) {
2413         LOGE("PublishDeviceDiscovery for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
2414         CreateBusinessError(env, ret);
2415         publishCallback->OnPublishResult(publishInfo.publishId, ret);
2416         return result;
2417     }
2418 
2419     napi_get_undefined(env, &result);
2420     return result;
2421 }
2422 
UnPublishDeviceDiscoverySync(napi_env env,napi_callback_info info)2423 napi_value DeviceManagerNapi::UnPublishDeviceDiscoverySync(napi_env env, napi_callback_info info)
2424 {
2425     LOGI("UnPublishDeviceDiscoverySync in");
2426     if (!IsSystemApp()) {
2427         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2428         return nullptr;
2429     }
2430     GET_PARAMS(env, info, DM_NAPI_ARGS_ONE);
2431     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_ONE,  "Wrong number of arguments, required 1")) {
2432         return nullptr;
2433     }
2434 
2435     napi_value result = nullptr;
2436     napi_valuetype valueType = napi_undefined;
2437     napi_typeof(env, argv[0], &valueType);
2438     if (!CheckArgsType(env, valueType == napi_number, "publishId", "number")) {
2439         return nullptr;
2440     }
2441     int32_t publishId = 0;
2442     napi_get_value_int32(env, argv[0], &publishId);
2443 
2444     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2445     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2446         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2447         return result;
2448     }
2449 
2450     int32_t ret = DeviceManager::GetInstance().UnPublishDeviceDiscovery(deviceManagerWrapper->bundleName_, publishId);
2451     if (ret != 0) {
2452         LOGE("UnPublishDeviceDiscovery bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
2453         CreateBusinessError(env, ret);
2454         return result;
2455     }
2456 
2457     napi_get_undefined(env, &result);
2458     return result;
2459 }
2460 
AuthenticateDevice(napi_env env,napi_callback_info info)2461 napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_info info)
2462 {
2463     if (!IsSystemApp()) {
2464         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2465         return nullptr;
2466     }
2467     GET_PARAMS(env, info, DM_NAPI_ARGS_THREE);
2468     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_THREE,  "Wrong number of arguments, required 3")) {
2469         return nullptr;
2470     }
2471     napi_value result = nullptr;
2472     if (!IsJSObjectType(env, argv[0], "deviceInfo")) {
2473         return nullptr;
2474     }
2475     if (!IsJSObjectType(env, argv[DM_NAPI_ARGS_ONE], "authParam")) {
2476         return nullptr;
2477     }
2478     if (!IsFunctionType(env, argv[DM_NAPI_ARGS_TWO])) {
2479         return nullptr;
2480     }
2481 
2482     authAsyncCallbackInfo_.env = env;
2483     napi_create_reference(env, argv[DM_NAPI_ARGS_TWO], 1, &authAsyncCallbackInfo_.callback);
2484     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2485     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2486         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2487         return result;
2488     }
2489 
2490     std::shared_ptr<DmNapiAuthenticateCallback> authCallback = nullptr;
2491     auto iter = g_authCallbackMap.find(deviceManagerWrapper->bundleName_);
2492     if (iter == g_authCallbackMap.end()) {
2493         authCallback = std::make_shared<DmNapiAuthenticateCallback>(env, deviceManagerWrapper->bundleName_);
2494         g_authCallbackMap[deviceManagerWrapper->bundleName_] = authCallback;
2495     } else {
2496         authCallback = iter->second;
2497     }
2498     DmDeviceInfo deviceInfo;
2499     JsToDmDeviceInfo(env, argv[0], deviceInfo);
2500     std::string extraString;
2501     JsToDmExtra(env, argv[DM_NAPI_ARGS_ONE], extraString, authAsyncCallbackInfo_.authType);
2502     int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_,
2503         authAsyncCallbackInfo_.authType, deviceInfo, extraString, authCallback);
2504     if (ret != 0) {
2505         LOGE("AuthenticateDevice for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
2506         CreateBusinessError(env, ret);
2507     }
2508     napi_get_undefined(env, &result);
2509     return result;
2510 }
2511 
VerifyAuthInfo(napi_env env,napi_callback_info info)2512 napi_value DeviceManagerNapi::VerifyAuthInfo(napi_env env, napi_callback_info info)
2513 {
2514     if (!IsSystemApp()) {
2515         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2516         return nullptr;
2517     }
2518     GET_PARAMS(env, info, DM_NAPI_ARGS_TWO);
2519 
2520     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_TWO,  "Wrong number of arguments, required 2")) {
2521         return nullptr;
2522     }
2523 
2524     napi_value result = nullptr;
2525     napi_valuetype valueType = napi_undefined;
2526     napi_typeof(env, argv[0], &valueType);
2527     if (!CheckArgsType(env, valueType == napi_object, "authInfo", "object")) {
2528         return nullptr;
2529     }
2530     if (!IsFunctionType(env, argv[1])) {
2531         return nullptr;
2532     }
2533 
2534     verifyAsyncCallbackInfo_.env = env;
2535     napi_create_reference(env, argv[1], 1, &verifyAsyncCallbackInfo_.callback);
2536     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2537     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2538         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2539         return result;
2540     }
2541 
2542     std::shared_ptr<DmNapiVerifyAuthCallback> verifyCallback = nullptr;
2543     auto iter = g_verifyAuthCallbackMap.find(deviceManagerWrapper->bundleName_);
2544     if (iter == g_verifyAuthCallbackMap.end()) {
2545         verifyCallback = std::make_shared<DmNapiVerifyAuthCallback>(env, deviceManagerWrapper->bundleName_);
2546         g_verifyAuthCallbackMap[deviceManagerWrapper->bundleName_] = verifyCallback;
2547     } else {
2548         verifyCallback = iter->second;
2549     }
2550     std::string authParam;
2551     JsToDmAuthInfo(env, argv[0], authParam);
2552 
2553     int32_t ret =
2554         DeviceManager::GetInstance().VerifyAuthentication(deviceManagerWrapper->bundleName_, authParam, verifyCallback);
2555     if (ret != 0) {
2556         LOGE("VerifyAuthInfo for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
2557         CreateBusinessError(env, ret);
2558     }
2559     napi_get_undefined(env, &result);
2560     return result;
2561 }
2562 
RequestCredential(napi_env env,napi_callback_info info)2563 napi_value DeviceManagerNapi::RequestCredential(napi_env env, napi_callback_info info)
2564 {
2565     LOGI("RequestCredential in");
2566     if (!IsSystemApp()) {
2567         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2568         return nullptr;
2569     }
2570     GET_PARAMS(env, info, DM_NAPI_ARGS_TWO);
2571 
2572     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_TWO, "Wrong number of arguments, required 2")) {
2573         return nullptr;
2574     }
2575 
2576     napi_value result = nullptr;
2577     napi_valuetype requestInfoValueType = napi_undefined;
2578     napi_typeof(env, argv[0], &requestInfoValueType);
2579     if (!CheckArgsType(env, requestInfoValueType == napi_string, "requestInfo", "string")) {
2580         return nullptr;
2581     }
2582 
2583     napi_valuetype funcValueType = napi_undefined;
2584     napi_typeof(env, argv[1], &funcValueType);
2585     if (!CheckArgsType(env, funcValueType == napi_function, "callback", "function")) {
2586         return nullptr;
2587     }
2588 
2589     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2590     napi_unwrap(env, thisVar, reinterpret_cast<void **>(&deviceManagerWrapper));
2591     if (deviceManagerWrapper == nullptr) {
2592         LOGE(" DeviceManagerNapi object is nullptr!");
2593         return result;
2594     }
2595 
2596     size_t typeLen = 0;
2597     napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen);
2598     NAPI_ASSERT(env, typeLen < DM_NAPI_BUF_LENGTH, "typeLen >= MAXLEN");
2599     char type[DM_NAPI_BUF_LENGTH] = {0};
2600     napi_get_value_string_utf8(env, argv[0], type, typeLen + 1, &typeLen);
2601 
2602     auto *creAsyncCallbackInfo = new CredentialAsyncCallbackInfo();
2603     creAsyncCallbackInfo->env = env;
2604     creAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_;
2605     creAsyncCallbackInfo->reqInfo = type;
2606 
2607     napi_create_reference(env, argv[1], 1, &creAsyncCallbackInfo->callback);
2608     CallCredentialAsyncWork(env, creAsyncCallbackInfo);
2609     napi_get_undefined(env, &result);
2610     return result;
2611 }
2612 
RegisterCredentialCallback(napi_env env,const std::string & pkgName)2613 int32_t DeviceManagerNapi::RegisterCredentialCallback(napi_env env, const std::string &pkgName)
2614 {
2615     std::shared_ptr<DmNapiCredentialCallback> creCallback = nullptr;
2616     {
2617         std::lock_guard<std::mutex> autoLock(creMapLocks_);
2618         auto iter = g_creCallbackMap.find(pkgName);
2619         if (iter == g_creCallbackMap.end()) {
2620             creCallback = std::make_shared<DmNapiCredentialCallback>(env, pkgName);
2621             g_creCallbackMap[pkgName] = creCallback;
2622         } else {
2623             creCallback = iter->second;
2624         }
2625     }
2626     int32_t ret = DeviceManager::GetInstance().RegisterCredentialCallback(pkgName,
2627         creCallback);
2628     if (ret != 0) {
2629         LOGE("RegisterCredentialCallback for bundleName %s failed, ret %d", pkgName.c_str(), ret);
2630         CreateBusinessError(env, ret);
2631     }
2632     return ret;
2633 }
2634 
ImportCredential(napi_env env,napi_callback_info info)2635 napi_value DeviceManagerNapi::ImportCredential(napi_env env, napi_callback_info info)
2636 {
2637     LOGI("ImportCredential in");
2638     if (!IsSystemApp()) {
2639         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2640         return nullptr;
2641     }
2642     GET_PARAMS(env, info, DM_NAPI_ARGS_TWO);
2643     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_TWO, "Wrong number of arguments, required 2")) {
2644         return nullptr;
2645     }
2646     napi_value result = nullptr;
2647     napi_valuetype importInfoValueType = napi_undefined;
2648     napi_typeof(env, argv[0], &importInfoValueType);
2649     if (!CheckArgsType(env, importInfoValueType == napi_string, "credentialInfo", "string")) {
2650         return nullptr;
2651     }
2652     if (!IsFunctionType(env, argv[1])) {
2653         return nullptr;
2654     }
2655 
2656     creAsyncCallbackInfo_.env = env;
2657     napi_create_reference(env, argv[1], 1, &creAsyncCallbackInfo_.callback);
2658 
2659     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2660     napi_unwrap(env, thisVar, reinterpret_cast<void **>(&deviceManagerWrapper));
2661     if (deviceManagerWrapper == nullptr) {
2662         LOGE(" DeviceManagerNapi object is nullptr!");
2663         return result;
2664     }
2665     if (RegisterCredentialCallback(env, deviceManagerWrapper->bundleName_) != 0) {
2666         LOGE("RegisterCredentialCallback failed!");
2667         return result;
2668     }
2669 
2670     size_t typeLen = 0;
2671     napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen);
2672     NAPI_ASSERT(env, typeLen > 0, "typeLen == 0");
2673     NAPI_ASSERT(env, typeLen < DM_NAPI_CREDENTIAL_BUF_LENGTH, "typeLen >= MAXLEN");
2674     char type[DM_NAPI_CREDENTIAL_BUF_LENGTH] = {0};
2675     napi_get_value_string_utf8(env, argv[0], type, typeLen + 1, &typeLen);
2676     std::string credentialInfo = type;
2677     int32_t ret = DeviceManager::GetInstance().ImportCredential(deviceManagerWrapper->bundleName_, credentialInfo);
2678     if (ret != 0) {
2679         LOGE("ImportCredential for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
2680         CreateBusinessError(env, ret);
2681     }
2682     napi_get_undefined(env, &result);
2683     return result;
2684 }
2685 
DeleteCredential(napi_env env,napi_callback_info info)2686 napi_value DeviceManagerNapi::DeleteCredential(napi_env env, napi_callback_info info)
2687 {
2688     LOGI("DeleteCredential in");
2689     if (!IsSystemApp()) {
2690         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2691         return nullptr;
2692     }
2693     GET_PARAMS(env, info, DM_NAPI_ARGS_TWO);
2694     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_TWO, "Wrong number of arguments, required 2")) {
2695         return nullptr;
2696     }
2697 
2698     napi_value result = nullptr;
2699     napi_valuetype queryInfoValueType = napi_undefined;
2700     napi_typeof(env, argv[0], &queryInfoValueType);
2701     if (!CheckArgsType(env, queryInfoValueType == napi_string, "queryInfo", "string")) {
2702         return nullptr;
2703     }
2704     if (!IsFunctionType(env, argv[1])) {
2705         return nullptr;
2706     }
2707 
2708     creAsyncCallbackInfo_.env = env;
2709     napi_create_reference(env, argv[1], 1, &creAsyncCallbackInfo_.callback);
2710     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2711     napi_unwrap(env, thisVar, reinterpret_cast<void **>(&deviceManagerWrapper));
2712     if (deviceManagerWrapper == nullptr) {
2713         LOGE(" DeviceManagerNapi object is nullptr!");
2714         return result;
2715     }
2716     if (RegisterCredentialCallback(env, deviceManagerWrapper->bundleName_) != 0) {
2717         LOGE("RegisterCredentialCallback failed!");
2718         return result;
2719     }
2720 
2721     size_t typeLen = 0;
2722     napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen);
2723     NAPI_ASSERT(env, typeLen > 0, "typeLen == 0");
2724     NAPI_ASSERT(env, typeLen < DM_NAPI_CREDENTIAL_BUF_LENGTH, "typeLen >= MAXLEN");
2725     char type[DM_NAPI_CREDENTIAL_BUF_LENGTH] = {0};
2726     napi_get_value_string_utf8(env, argv[0], type, typeLen + 1, &typeLen);
2727     std::string queryInfo = type;
2728     int32_t ret = DeviceManager::GetInstance().DeleteCredential(deviceManagerWrapper->bundleName_, queryInfo);
2729     if (ret != 0) {
2730         LOGE("DeleteCredential for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
2731         CreateBusinessError(env, ret);
2732     }
2733     napi_get_undefined(env, &result);
2734     return result;
2735 }
2736 
JsOnFrench(napi_env env,int32_t num,napi_value thisVar,napi_value argv[])2737 napi_value DeviceManagerNapi::JsOnFrench(napi_env env, int32_t num, napi_value thisVar, napi_value argv[])
2738 {
2739     size_t typeLen = 0;
2740     napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen);
2741 
2742     if (!CheckArgsVal(env, typeLen > 0, "type", "typeLen == 0")) {
2743         return nullptr;
2744     }
2745     if (!CheckArgsVal(env, typeLen < DM_NAPI_BUF_LENGTH, "type", "typeLen >= MAXLEN")) {
2746         return nullptr;
2747     }
2748     char type[DM_NAPI_BUF_LENGTH] = {0};
2749     napi_get_value_string_utf8(env, argv[0], type, typeLen + 1, &typeLen);
2750 
2751     std::string eventType = type;
2752     napi_value result = nullptr;
2753     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2754     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2755         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2756         return result;
2757     }
2758 
2759     LOGI("JsOn for bundleName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), eventType.c_str());
2760     deviceManagerWrapper->On(eventType, argv[num + 1]);
2761 
2762     if (eventType == DM_NAPI_EVENT_DEVICE_STATE_CHANGE) {
2763         if (num == 1) {
2764             size_t extraLen = 0;
2765             napi_get_value_string_utf8(env, argv[1], nullptr, 0, &extraLen);
2766             if (!CheckArgsVal(env, extraLen < DM_NAPI_BUF_LENGTH, "extra", "extraLen >= MAXLEN")) {
2767                 return nullptr;
2768             }
2769             char extra[DM_NAPI_BUF_LENGTH] = {0};
2770             napi_get_value_string_utf8(env, argv[1], extra, extraLen + 1, &extraLen);
2771             std::string extraString = extra;
2772             LOGI("extra = %s", extraString.c_str());
2773             CreateDmCallback(env, deviceManagerWrapper->bundleName_, eventType, extraString);
2774         } else {
2775             CreateDmCallback(env, deviceManagerWrapper->bundleName_, eventType);
2776         }
2777     } else {
2778         CreateDmCallback(env, deviceManagerWrapper->bundleName_, eventType);
2779     }
2780 
2781     napi_get_undefined(env, &result);
2782     return result;
2783 }
2784 
JsOn(napi_env env,napi_callback_info info)2785 napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info)
2786 {
2787     if (!IsSystemApp()) {
2788         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2789         return nullptr;
2790     }
2791     int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission();
2792     if (ret != 0) {
2793         CreateBusinessError(env, ret);
2794         return nullptr;
2795     }
2796     size_t argc = 0;
2797     napi_value thisVar = nullptr;
2798     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr));
2799     if (argc == DM_NAPI_ARGS_THREE) {
2800         GET_PARAMS(env, info, DM_NAPI_ARGS_THREE);
2801         if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_THREE, "Wrong number of arguments, required 3")) {
2802             return nullptr;
2803         }
2804         napi_valuetype eventValueType = napi_undefined;
2805         napi_typeof(env, argv[0], &eventValueType);
2806         if (!CheckArgsType(env, eventValueType == napi_string, "type", "string")) {
2807             return nullptr;
2808         }
2809         napi_valuetype valueType;
2810         napi_typeof(env, argv[1], &valueType);
2811         if (!CheckArgsType(env, (valueType == napi_string || valueType == napi_object),
2812             "extra", "string | object")) {
2813             return nullptr;
2814         }
2815         if (!IsFunctionType(env, argv[DM_NAPI_ARGS_TWO])) {
2816             return nullptr;
2817         }
2818         return JsOnFrench(env, 1, thisVar, argv);
2819     } else {
2820         GET_PARAMS(env, info, DM_NAPI_ARGS_TWO);
2821         if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_TWO, "Wrong number of arguments, required 2")) {
2822             return nullptr;
2823         }
2824         napi_valuetype eventValueType = napi_undefined;
2825         napi_typeof(env, argv[0], &eventValueType);
2826         if (!CheckArgsType(env, eventValueType == napi_string, "type", "string")) {
2827             return nullptr;
2828         }
2829         if (!IsFunctionType(env, argv[1])) {
2830             return nullptr;
2831         }
2832         return JsOnFrench(env, 0, thisVar, argv);
2833     }
2834 }
2835 
JsOffFrench(napi_env env,int32_t num,napi_value thisVar,napi_value argv[])2836 napi_value DeviceManagerNapi::JsOffFrench(napi_env env, int32_t num, napi_value thisVar, napi_value argv[])
2837 {
2838     int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission();
2839     if (ret != 0) {
2840         CreateBusinessError(env, ret);
2841         return nullptr;
2842     }
2843     size_t typeLen = 0;
2844     napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen);
2845     if (!CheckArgsVal(env, typeLen > 0, "type", "typeLen == 0")) {
2846         return nullptr;
2847     }
2848     if (!CheckArgsVal(env, typeLen < DM_NAPI_BUF_LENGTH, "type", "typeLen >= MAXLEN")) {
2849         return nullptr;
2850     }
2851     char type[DM_NAPI_BUF_LENGTH] = {0};
2852     napi_get_value_string_utf8(env, argv[0], type, typeLen + 1, &typeLen);
2853 
2854     napi_value result = nullptr;
2855     std::string eventType = type;
2856     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2857     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2858         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2859         return result;
2860     }
2861 
2862     LOGI("JsOff for bundleName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), eventType.c_str());
2863     deviceManagerWrapper->Off(eventType);
2864     ReleaseDmCallback(deviceManagerWrapper->bundleName_, eventType);
2865 
2866     napi_get_undefined(env, &result);
2867     return result;
2868 }
2869 
JsOff(napi_env env,napi_callback_info info)2870 napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info)
2871 {
2872     if (!IsSystemApp()) {
2873         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2874         return nullptr;
2875     }
2876     size_t argc = 0;
2877     napi_value thisVar = nullptr;
2878     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr));
2879     if (argc == DM_NAPI_ARGS_THREE) {
2880         LOGI("JsOff in argc == 3");
2881         GET_PARAMS(env, info, DM_NAPI_ARGS_THREE);
2882         if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_ONE, "Wrong number of arguments, required 1")) {
2883             return nullptr;
2884         }
2885         napi_valuetype eventValueType = napi_undefined;
2886         napi_typeof(env, argv[0], &eventValueType);
2887         if (!CheckArgsType(env, eventValueType == napi_string, "type", "string")) {
2888             return nullptr;
2889         }
2890         napi_valuetype valueType;
2891         napi_typeof(env, argv[1], &valueType);
2892         if (!CheckArgsType(env, (valueType == napi_string || valueType == napi_object), "extra", "string or object")) {
2893             return nullptr;
2894         }
2895         if (argc > DM_NAPI_ARGS_ONE) {
2896             if (!IsFunctionType(env, argv[DM_NAPI_ARGS_TWO])) {
2897                 return nullptr;
2898             }
2899         }
2900         return JsOffFrench(env, 1, thisVar, argv);
2901     } else {
2902         GET_PARAMS(env, info, DM_NAPI_ARGS_TWO);
2903         if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_ONE, "Wrong number of arguments, required 1")) {
2904             return nullptr;
2905         }
2906         napi_valuetype eventValueType = napi_undefined;
2907         napi_typeof(env, argv[0], &eventValueType);
2908         if (!CheckArgsType(env, eventValueType == napi_string, "type", "string")) {
2909             return nullptr;
2910         }
2911         if (argc > DM_NAPI_ARGS_ONE) {
2912             if (!IsFunctionType(env, argv[1])) {
2913                 return nullptr;
2914             }
2915         }
2916         return JsOffFrench(env, 0, thisVar, argv);
2917     }
2918 }
2919 
ReleaseDeviceManager(napi_env env,napi_callback_info info)2920 napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_info info)
2921 {
2922     LOGI("ReleaseDeviceManager in");
2923     if (!IsSystemApp()) {
2924         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
2925         return nullptr;
2926     }
2927     int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission();
2928     if (ret != 0) {
2929         CreateBusinessError(env, ret);
2930         return nullptr;
2931     }
2932     size_t argc = 0;
2933     napi_value thisVar = nullptr;
2934     napi_value result = nullptr;
2935     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr));
2936     DeviceManagerNapi *deviceManagerWrapper = nullptr;
2937     if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) {
2938         napi_create_uint32(env, ERR_DM_POINT_NULL, &result);
2939         return result;
2940     }
2941     LOGI("ReleaseDeviceManager for bundleName %s", deviceManagerWrapper->bundleName_.c_str());
2942     ret = DeviceManager::GetInstance().UnInitDeviceManager(deviceManagerWrapper->bundleName_);
2943     if (ret != 0) {
2944         LOGE("ReleaseDeviceManager for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret);
2945         CreateBusinessError(env, ret);
2946         napi_create_uint32(env, static_cast<uint32_t>(ret), &result);
2947         return result;
2948     }
2949     {
2950         std::lock_guard<std::mutex> autoLock(g_deviceManagerMapMutex);
2951         g_deviceManagerMap.erase(deviceManagerWrapper->bundleName_);
2952     }
2953     {
2954         std::lock_guard<std::mutex> autoLock(g_initCallbackMapMutex);
2955         g_initCallbackMap.erase(deviceManagerWrapper->bundleName_);
2956     }
2957     g_deviceStateCallbackMap.erase(deviceManagerWrapper->bundleName_);
2958     g_DiscoveryCallbackMap.erase(deviceManagerWrapper->bundleName_);
2959     g_publishCallbackMap.erase(deviceManagerWrapper->bundleName_);
2960     g_authCallbackMap.erase(deviceManagerWrapper->bundleName_);
2961     g_verifyAuthCallbackMap.erase(deviceManagerWrapper->bundleName_);
2962     {
2963         std::lock_guard<std::mutex> autoLock(creMapLocks_);
2964         g_creCallbackMap.erase(deviceManagerWrapper->bundleName_);
2965     }
2966     napi_get_undefined(env, &result);
2967     NAPI_CALL(env, napi_remove_wrap(env, thisVar, (void**)&deviceManagerWrapper));
2968     return result;
2969 }
2970 
HandleCreateDmCallBackCompletedCB(napi_env env,napi_status status,void * data)2971 void DeviceManagerNapi::HandleCreateDmCallBackCompletedCB(napi_env env, napi_status status, void *data)
2972 {
2973     (void)status;
2974     AsyncCallbackInfo *asyncCallbackInfo = reinterpret_cast<AsyncCallbackInfo *>(data);
2975     napi_value result[DM_NAPI_ARGS_TWO] = {0};
2976     if (asyncCallbackInfo->status == 0) {
2977         napi_value ctor = nullptr;
2978         napi_value argv = nullptr;
2979         napi_get_reference_value(env, sConstructor_, &ctor);
2980         napi_create_string_utf8(env, asyncCallbackInfo->bundleName, NAPI_AUTO_LENGTH, &argv);
2981         napi_status ret = napi_new_instance(env, ctor, DM_NAPI_ARGS_ONE, &argv, &result[1]);
2982         if (ret != napi_ok) {
2983                 LOGE("Create DeviceManagerNapi for bundleName %s failed", asyncCallbackInfo->bundleName);
2984         } else {
2985                 LOGI("InitDeviceManager for bundleName %s success", asyncCallbackInfo->bundleName);
2986                 napi_get_undefined(env, &result[0]);
2987         }
2988     } else {
2989         LOGI("InitDeviceManager for bundleName %s failed", asyncCallbackInfo->bundleName);
2990         result[0] = CreateBusinessError(env, asyncCallbackInfo->ret, false);
2991     }
2992     napi_value callback = nullptr;
2993     napi_value callResult = nullptr;
2994     napi_get_reference_value(env, asyncCallbackInfo->callback, &callback);
2995     if (callback != nullptr) {
2996         napi_call_function(env, nullptr, callback, DM_NAPI_ARGS_TWO, &result[0], &callResult);
2997         napi_delete_reference(env, asyncCallbackInfo->callback);
2998     }
2999 
3000     napi_delete_async_work(env, asyncCallbackInfo->asyncWork);
3001     delete asyncCallbackInfo;
3002     asyncCallbackInfo = nullptr;
3003 }
3004 
HandleCreateDmCallBack(const napi_env & env,AsyncCallbackInfo * asCallbackInfo)3005 void DeviceManagerNapi::HandleCreateDmCallBack(const napi_env &env, AsyncCallbackInfo *asCallbackInfo)
3006 {
3007     napi_value resourceName;
3008     napi_create_string_latin1(env, "createDeviceManagerCallback", NAPI_AUTO_LENGTH, &resourceName);
3009     napi_create_async_work(
3010         env, nullptr, resourceName,
3011         [](napi_env env, void *data) {
3012             (void)env;
3013             AsyncCallbackInfo *asyCallbackInfo = reinterpret_cast<AsyncCallbackInfo *>(data);
3014             std::string bundleName = std::string(asyCallbackInfo->bundleName);
3015             std::shared_ptr<DmNapiInitCallback> initCallback = std::make_shared<DmNapiInitCallback>(env, bundleName);
3016             int32_t ret = DeviceManager::GetInstance().InitDeviceManager(bundleName, initCallback);
3017             if (ret == 0) {
3018                 std::lock_guard<std::mutex> autoLock(g_initCallbackMapMutex);
3019                 g_initCallbackMap[bundleName] = initCallback;
3020                 asyCallbackInfo->status = 0;
3021             } else {
3022                 asyCallbackInfo->status = 1;
3023                 asyCallbackInfo->ret = ret;
3024             }
3025         }, HandleCreateDmCallBackCompletedCB, (void *)asCallbackInfo, &asCallbackInfo->asyncWork);
3026     napi_queue_async_work_with_qos(env, asCallbackInfo->asyncWork, napi_qos_user_initiated);
3027 }
3028 
CallGetDeviceInfo(napi_env env,NetworkIdAsyncCallbackInfo * networkIdAsyncCallbackInfo)3029 void DeviceManagerNapi::CallGetDeviceInfo(napi_env env, NetworkIdAsyncCallbackInfo *networkIdAsyncCallbackInfo)
3030 {
3031     napi_value resourceName;
3032     napi_create_string_latin1(env, "GetLocalDeviceInfo", NAPI_AUTO_LENGTH, &resourceName);
3033     napi_create_async_work(
3034         env, nullptr, resourceName,
3035         GetDeviceInfoCB,
3036         CompleteGetDeviceInfoCB,
3037         (void *)networkIdAsyncCallbackInfo, &networkIdAsyncCallbackInfo->asyncWork);
3038     napi_queue_async_work_with_qos(env, networkIdAsyncCallbackInfo->asyncWork, napi_qos_user_initiated);
3039 }
3040 
GetDeviceInfoCB(napi_env env,void * data)3041 void DeviceManagerNapi::GetDeviceInfoCB(napi_env env, void *data)
3042 {
3043     if (!data) {
3044         LOGE("Invalid async callback data");
3045         return;
3046     }
3047     (void)env;
3048     NetworkIdAsyncCallbackInfo *networkIdAsyncCallbackInfo = reinterpret_cast<NetworkIdAsyncCallbackInfo *>(data);
3049     int32_t ret = DeviceManager::GetInstance().GetDeviceInfo(networkIdAsyncCallbackInfo->bundleName,
3050                                                              networkIdAsyncCallbackInfo->networkId,
3051                                                              networkIdAsyncCallbackInfo->deviceInfo);
3052     if (ret != 0) {
3053         LOGE("GetDeviceInfoCB for bundleName %s networkId %s failed, ret %d",
3054              networkIdAsyncCallbackInfo->bundleName.c_str(),
3055              GetAnonyString(networkIdAsyncCallbackInfo->networkId).c_str(), ret);
3056         networkIdAsyncCallbackInfo->status = -1;
3057         networkIdAsyncCallbackInfo->ret = ret;
3058     } else {
3059         networkIdAsyncCallbackInfo->status = 0;
3060         LOGI("GetDeviceInfoCB status %d", networkIdAsyncCallbackInfo->status);
3061     }
3062 }
3063 
CompleteGetDeviceInfoCB(napi_env env,napi_status status,void * data)3064 void DeviceManagerNapi::CompleteGetDeviceInfoCB(napi_env env, napi_status status, void *data)
3065 {
3066     if (!data) {
3067         LOGE("Invalid async callback data");
3068         return;
3069     }
3070     (void)status;
3071     NetworkIdAsyncCallbackInfo *networkIdAsyncCallbackInfo = reinterpret_cast<NetworkIdAsyncCallbackInfo *>(data);
3072     if (networkIdAsyncCallbackInfo->deferred != nullptr) {
3073         CallGetDeviceInfoPromise(env, status, networkIdAsyncCallbackInfo);    // promise
3074     } else {
3075         CallGetDeviceInfoCB(env, status, networkIdAsyncCallbackInfo);         // callback
3076     }
3077     napi_delete_async_work(env, networkIdAsyncCallbackInfo->asyncWork);
3078     delete networkIdAsyncCallbackInfo;
3079 }
3080 
3081 // promise function
CallGetDeviceInfoPromise(napi_env env,napi_status & status,NetworkIdAsyncCallbackInfo * networkIdAsyncCallbackInfo)3082 void DeviceManagerNapi::CallGetDeviceInfoPromise(napi_env env, napi_status &status,
3083                                                  NetworkIdAsyncCallbackInfo *networkIdAsyncCallbackInfo)
3084 {
3085     napi_value result[DM_NAPI_ARGS_TWO] = {0};
3086 
3087     LOGI("DeviceManager::CallGetDeviceInfoSync deviceName:%s deviceTypeId:%d ",
3088          networkIdAsyncCallbackInfo->deviceInfo.deviceName,
3089          networkIdAsyncCallbackInfo->deviceInfo.deviceTypeId);
3090 
3091     if (networkIdAsyncCallbackInfo->status == 0) {
3092         DeviceInfotoJsByNetworkId(env, networkIdAsyncCallbackInfo->deviceInfo, result[1]);
3093         napi_resolve_deferred(env, networkIdAsyncCallbackInfo->deferred, result[1]);
3094     } else {
3095         result[0] = CreateBusinessError(env, networkIdAsyncCallbackInfo->ret, false);
3096         napi_reject_deferred(env, networkIdAsyncCallbackInfo->deferred, result[0]);
3097     }
3098 }
3099 
3100 // callback function
CallGetDeviceInfoCB(napi_env env,napi_status & status,NetworkIdAsyncCallbackInfo * networkIdAsyncCallbackInfo)3101 void DeviceManagerNapi::CallGetDeviceInfoCB(napi_env env, napi_status &status,
3102                                             NetworkIdAsyncCallbackInfo *networkIdAsyncCallbackInfo)
3103 {
3104     napi_value result[DM_NAPI_ARGS_TWO] = {0};
3105     LOGI("DeviceManager::CallGetDeviceInfo deviceName:%s deviceTypeId:%d ",
3106          networkIdAsyncCallbackInfo->deviceInfo.deviceName,
3107          networkIdAsyncCallbackInfo->deviceInfo.deviceTypeId);
3108     napi_value callResult = nullptr;
3109     napi_value handler = nullptr;
3110 
3111     if (networkIdAsyncCallbackInfo->status == 0) {
3112         DeviceInfotoJsByNetworkId(env, networkIdAsyncCallbackInfo->deviceInfo, result[1]);
3113     } else {
3114         result[0] = CreateBusinessError(env, networkIdAsyncCallbackInfo->ret, false);
3115     }
3116 
3117     napi_get_reference_value(env, networkIdAsyncCallbackInfo->callback, &handler);
3118     if (handler != nullptr) {
3119         napi_call_function(env, nullptr, handler, DM_NAPI_ARGS_TWO, &result[0], &callResult);
3120         napi_delete_reference(env, networkIdAsyncCallbackInfo->callback);
3121     } else {
3122         LOGE("handler is nullptr");
3123     }
3124 }
3125 
DeviceInfotoJsByNetworkId(const napi_env & env,const DmDeviceInfo & nidDevInfo,napi_value & result)3126 void DeviceManagerNapi::DeviceInfotoJsByNetworkId(const napi_env &env, const DmDeviceInfo &nidDevInfo,
3127                                                   napi_value &result)
3128 {
3129     napi_create_object(env, &result);
3130 
3131     SetValueUtf8String(env, "deviceName", nidDevInfo.deviceName, result);
3132     SetValueInt32(env, "deviceType", (int)nidDevInfo.deviceTypeId, result);
3133 }
3134 
GetDeviceInfo(napi_env env,napi_callback_info info)3135 napi_value DeviceManagerNapi::GetDeviceInfo(napi_env env, napi_callback_info info)
3136 {
3137     if (!IsSystemApp()) {
3138         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
3139         return nullptr;
3140     }
3141     napi_value result = nullptr;
3142     size_t argc = 2;
3143     napi_value argv[2] = {nullptr};
3144     napi_value thisVar = nullptr;
3145     DmDeviceInfo deviceInfo;
3146     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
3147     NAPI_ASSERT(env, ((argc >= DM_NAPI_ARGS_ONE) && (argc <= DM_NAPI_ARGS_TWO)), "requires 1 or 2 parameter");
3148 
3149     napi_valuetype networkIdValueType = napi_undefined;
3150     napi_typeof(env, argv[0], &networkIdValueType);
3151     if (!CheckArgsType(env, networkIdValueType == napi_string, "networkId", "string")) {
3152         return nullptr;
3153     }
3154     size_t networkIdLen = 0;
3155     napi_get_value_string_utf8(env, argv[0], nullptr, 0, &networkIdLen);
3156     NAPI_ASSERT(env, networkIdLen < DM_NAPI_BUF_LENGTH, "typeLen >= MAXLEN");
3157     char networkIdValue[DM_NAPI_BUF_LENGTH] = {0};
3158     napi_get_value_string_utf8(env, argv[0], networkIdValue, networkIdLen + 1, &networkIdLen);
3159     DeviceManagerNapi *deviceManagerWrapper = nullptr;
3160     napi_unwrap(env, thisVar, reinterpret_cast<void **>(&deviceManagerWrapper));
3161     auto *networkIdAsyncCallbackInfo = new NetworkIdAsyncCallbackInfo();
3162     networkIdAsyncCallbackInfo->env = env;
3163     networkIdAsyncCallbackInfo->deviceInfo = deviceInfo;
3164     networkIdAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_;
3165     networkIdAsyncCallbackInfo->networkId = std::string(networkIdValue);
3166 
3167     if (argc == DM_NAPI_ARGS_ONE) {    // promise
3168         napi_deferred deferred;
3169         napi_value promise = 0;
3170         napi_create_promise(env, &deferred, &promise);
3171         networkIdAsyncCallbackInfo->deferred = deferred;
3172         CallGetDeviceInfo(env, networkIdAsyncCallbackInfo);
3173         return promise;
3174     } else if (argc == DM_NAPI_ARGS_TWO) {    // callback
3175         if (!IsFunctionType(env, argv[1])) {
3176             delete networkIdAsyncCallbackInfo;
3177             networkIdAsyncCallbackInfo = nullptr;
3178             return nullptr;
3179         }
3180         napi_create_reference(env, argv[1], 1, &networkIdAsyncCallbackInfo->callback);
3181         CallGetDeviceInfo(env, networkIdAsyncCallbackInfo);
3182     }
3183     napi_get_undefined(env, &result);
3184     return result;
3185 }
CreateDeviceManager(napi_env env,napi_callback_info info)3186 napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_info info)
3187 {
3188     LOGI("CreateDeviceManager in");
3189     if (!IsSystemApp()) {
3190         CreateBusinessError(env, ERR_NOT_SYSTEM_APP);
3191         return nullptr;
3192     }
3193     GET_PARAMS(env, info, DM_NAPI_ARGS_TWO);
3194 
3195     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_TWO, "Wrong number of arguments, required 2")) {
3196         return nullptr;
3197     }
3198 
3199     napi_valuetype bundleNameValueType = napi_undefined;
3200     napi_typeof(env, argv[0], &bundleNameValueType);
3201     if (!CheckArgsType(env, bundleNameValueType == napi_string, "bundleName", "string")) {
3202         return nullptr;
3203     }
3204 
3205     napi_valuetype funcValueType = napi_undefined;
3206     napi_typeof(env, argv[1], &funcValueType);
3207     if (!CheckArgsType(env, funcValueType == napi_function, "callback", "function")) {
3208         return nullptr;
3209     }
3210 
3211     auto *asCallbackInfo = new AsyncCallbackInfo();
3212     if (asCallbackInfo == nullptr) {
3213         return nullptr;
3214     }
3215     asCallbackInfo->env = env;
3216     napi_get_value_string_utf8(env, argv[0], asCallbackInfo->bundleName, DM_NAPI_BUF_LENGTH - 1,
3217                                &asCallbackInfo->bundleNameLen);
3218 
3219     napi_create_reference(env, argv[1], 1, &asCallbackInfo->callback);
3220 
3221     HandleCreateDmCallBack(env, asCallbackInfo);
3222 
3223     napi_value result = nullptr;
3224     napi_get_undefined(env, &result);
3225     return result;
3226 }
3227 
Constructor(napi_env env,napi_callback_info info)3228 napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info)
3229 {
3230     LOGI("DeviceManagerNapi Constructor in");
3231     GET_PARAMS(env, info, DM_NAPI_ARGS_ONE);
3232     if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_ONE, "Wrong number of arguments, required 1")) {
3233         return nullptr;
3234     }
3235 
3236     napi_valuetype valueType = napi_undefined;
3237     napi_typeof(env, argv[0], &valueType);
3238     if (!CheckArgsType(env, valueType == napi_string, "bundleName", "string")) {
3239         return nullptr;
3240     }
3241 
3242     char bundleName[DM_NAPI_BUF_LENGTH] = {0};
3243     size_t typeLen = 0;
3244     napi_get_value_string_utf8(env, argv[0], bundleName, sizeof(bundleName), &typeLen);
3245 
3246     LOGI("create DeviceManagerNapi for packageName:%s", bundleName);
3247     DeviceManagerNapi *obj = new DeviceManagerNapi(env, thisVar);
3248     if (obj == nullptr) {
3249         return nullptr;
3250     }
3251 
3252     obj->bundleName_ = std::string(bundleName);
3253     std::lock_guard<std::mutex> autoLock(g_deviceManagerMapMutex);
3254     g_deviceManagerMap[obj->bundleName_] = obj;
3255     napi_wrap(
3256         env, thisVar, reinterpret_cast<void *>(obj),
3257         [](napi_env env, void *data, void *hint) {
3258             (void)env;
3259             (void)hint;
3260             DeviceManagerNapi *deviceManager = reinterpret_cast<DeviceManagerNapi *>(data);
3261             delete deviceManager;
3262             deviceManager = nullptr;
3263             LOGI("delete deviceManager");
3264         },
3265         nullptr, nullptr);
3266     return thisVar;
3267 }
3268 
Init(napi_env env,napi_value exports)3269 napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports)
3270 {
3271     napi_value dmClass = nullptr;
3272     napi_property_descriptor dmProperties[] = {
3273         DECLARE_NAPI_FUNCTION("release", ReleaseDeviceManager),
3274         DECLARE_NAPI_FUNCTION("getTrustedDeviceListSync", GetTrustedDeviceListSync),
3275         DECLARE_NAPI_FUNCTION("getTrustedDeviceList", GetTrustedDeviceList),
3276         DECLARE_NAPI_FUNCTION("startDeviceDiscovery", StartDeviceDiscoverSync),
3277         DECLARE_NAPI_FUNCTION("stopDeviceDiscovery", StopDeviceDiscoverSync),
3278         DECLARE_NAPI_FUNCTION("publishDeviceDiscovery", PublishDeviceDiscoverySync),
3279         DECLARE_NAPI_FUNCTION("unPublishDeviceDiscovery", UnPublishDeviceDiscoverySync),
3280         DECLARE_NAPI_FUNCTION("getLocalDeviceInfoSync", GetLocalDeviceInfoSync),
3281         DECLARE_NAPI_FUNCTION("getLocalDeviceInfo", GetLocalDeviceInfo),
3282         DECLARE_NAPI_FUNCTION("getDeviceInfo", GetDeviceInfo),
3283         DECLARE_NAPI_FUNCTION("unAuthenticateDevice", UnAuthenticateDevice),
3284         DECLARE_NAPI_FUNCTION("authenticateDevice", AuthenticateDevice),
3285         DECLARE_NAPI_FUNCTION("verifyAuthInfo", VerifyAuthInfo),
3286         DECLARE_NAPI_FUNCTION("setUserOperation", SetUserOperationSync),
3287         DECLARE_NAPI_FUNCTION("requestCredentialRegisterInfo", RequestCredential),
3288         DECLARE_NAPI_FUNCTION("importCredential", ImportCredential),
3289         DECLARE_NAPI_FUNCTION("deleteCredential", DeleteCredential),
3290         DECLARE_NAPI_FUNCTION("getFaParam", GetAuthenticationParamSync),
3291         DECLARE_NAPI_FUNCTION("getAuthenticationParam", GetAuthenticationParamSync),
3292         DECLARE_NAPI_FUNCTION("on", JsOn),
3293         DECLARE_NAPI_FUNCTION("off", JsOff)};
3294 
3295     napi_property_descriptor static_prop[] = {
3296         DECLARE_NAPI_STATIC_FUNCTION("createDeviceManager", CreateDeviceManager),
3297     };
3298 
3299     LOGI("DeviceManagerNapi::Init() is called!");
3300     NAPI_CALL(env, napi_define_class(env, DEVICE_MANAGER_NAPI_CLASS_NAME.c_str(), NAPI_AUTO_LENGTH, Constructor,
3301                                      nullptr, sizeof(dmProperties) / sizeof(dmProperties[0]), dmProperties, &dmClass));
3302     NAPI_CALL(env, napi_create_reference(env, dmClass, 1, &sConstructor_));
3303     NAPI_CALL(env, napi_set_named_property(env, exports, DEVICE_MANAGER_NAPI_CLASS_NAME.c_str(), dmClass));
3304     NAPI_CALL(env, napi_define_properties(env, exports, sizeof(static_prop) / sizeof(static_prop[0]), static_prop));
3305     LOGI("All props and functions are configured..");
3306     return exports;
3307 }
3308 
EnumTypeConstructor(napi_env env,napi_callback_info info)3309 napi_value DeviceManagerNapi::EnumTypeConstructor(napi_env env, napi_callback_info info)
3310 {
3311     size_t argc = 0;
3312     napi_value res = nullptr;
3313     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &res, nullptr));
3314     return res;
3315 }
3316 
InitDeviceTypeEnum(napi_env env,napi_value exports)3317 napi_value DeviceManagerNapi::InitDeviceTypeEnum(napi_env env, napi_value exports)
3318 {
3319     napi_value unknown_type;
3320     napi_value speaker;
3321     napi_value phone;
3322     napi_value tablet;
3323     napi_value wearable;
3324     napi_value car;
3325     napi_value tv;
3326     int32_t refCount = 1;
3327 
3328     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceType::DEVICE_TYPE_UNKNOWN),
3329         &unknown_type);
3330     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceType::DEVICE_TYPE_AUDIO),
3331         &speaker);
3332     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceType::DEVICE_TYPE_PHONE),
3333         &phone);
3334     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceType::DEVICE_TYPE_PAD),
3335         &tablet);
3336     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceType::DEVICE_TYPE_WATCH),
3337         &wearable);
3338     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceType::DEVICE_TYPE_CAR),
3339         &car);
3340     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceType::DEVICE_TYPE_TV),
3341         &tv);
3342 
3343     napi_property_descriptor desc[] = {
3344         DECLARE_NAPI_STATIC_PROPERTY("UNKNOWN_TYPE", unknown_type),
3345         DECLARE_NAPI_STATIC_PROPERTY("SPEAKER", speaker),
3346         DECLARE_NAPI_STATIC_PROPERTY("PHONE", phone),
3347         DECLARE_NAPI_STATIC_PROPERTY("TABLET", tablet),
3348         DECLARE_NAPI_STATIC_PROPERTY("WEARABLE", wearable),
3349         DECLARE_NAPI_STATIC_PROPERTY("CAR", car),
3350         DECLARE_NAPI_STATIC_PROPERTY("TV", tv),
3351     };
3352 
3353     napi_value result = nullptr;
3354     napi_define_class(env, "DeviceType", NAPI_AUTO_LENGTH, EnumTypeConstructor,
3355         nullptr, sizeof(desc) / sizeof(*desc), desc, &result);
3356     napi_create_reference(env, result, refCount, &deviceTypeEnumConstructor_);
3357     napi_set_named_property(env, exports, "DeviceType", result);
3358     return exports;
3359 }
3360 
InitDeviceStateChangeActionEnum(napi_env env,napi_value exports)3361 napi_value DeviceManagerNapi::InitDeviceStateChangeActionEnum(napi_env env, napi_value exports)
3362 {
3363     napi_value device_state_online;
3364     napi_value device_state_ready;
3365     napi_value device_state_offline;
3366     napi_value device_state_change;
3367     int32_t refCount = 1;
3368 
3369     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceState::DEVICE_STATE_ONLINE),
3370         &device_state_online);
3371     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceState::DEVICE_INFO_READY),
3372         &device_state_ready);
3373     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceState::DEVICE_STATE_OFFLINE),
3374         &device_state_offline);
3375     napi_create_uint32(env, static_cast<uint32_t>(DmDeviceState::DEVICE_INFO_CHANGED),
3376         &device_state_change);
3377 
3378     napi_property_descriptor desc[] = {
3379         DECLARE_NAPI_STATIC_PROPERTY("ONLINE", device_state_online),
3380         DECLARE_NAPI_STATIC_PROPERTY("READY", device_state_ready),
3381         DECLARE_NAPI_STATIC_PROPERTY("OFFLINE", device_state_offline),
3382         DECLARE_NAPI_STATIC_PROPERTY("CHANGE", device_state_change),
3383     };
3384 
3385     napi_value result = nullptr;
3386     napi_define_class(env, "DeviceStateChangeAction", NAPI_AUTO_LENGTH, EnumTypeConstructor,
3387         nullptr, sizeof(desc) / sizeof(*desc), desc, &result);
3388     napi_create_reference(env, result, refCount, &deviceStateChangeActionEnumConstructor_);
3389     napi_set_named_property(env, exports, "DeviceStateChangeAction", result);
3390     return exports;
3391 }
3392 
InitDiscoverModeEnum(napi_env env,napi_value exports)3393 napi_value DeviceManagerNapi::InitDiscoverModeEnum(napi_env env, napi_value exports)
3394 {
3395     napi_value discover_mode_passive;
3396     napi_value discover_mode_active;
3397     int32_t refCount = 1;
3398 
3399     napi_create_uint32(env, static_cast<uint32_t>(DmDiscoverMode::DM_DISCOVER_MODE_PASSIVE),
3400         &discover_mode_passive);
3401     napi_create_uint32(env, static_cast<uint32_t>(DmDiscoverMode::DM_DISCOVER_MODE_ACTIVE),
3402         &discover_mode_active);
3403 
3404     napi_property_descriptor desc[] = {
3405         DECLARE_NAPI_STATIC_PROPERTY("DISCOVER_MODE_PASSIVE", discover_mode_passive),
3406         DECLARE_NAPI_STATIC_PROPERTY("DISCOVER_MODE_ACTIVE", discover_mode_active),
3407     };
3408 
3409     napi_value result = nullptr;
3410     napi_define_class(env, "DiscoverMode", NAPI_AUTO_LENGTH, EnumTypeConstructor,
3411         nullptr, sizeof(desc) / sizeof(*desc), desc, &result);
3412     napi_create_reference(env, result, refCount, &discoverModeEnumConstructor_);
3413     napi_set_named_property(env, exports, "DiscoverMode", result);
3414     return exports;
3415 }
3416 
InitExchangeMediumEnum(napi_env env,napi_value exports)3417 napi_value DeviceManagerNapi::InitExchangeMediumEnum(napi_env env, napi_value exports)
3418 {
3419     napi_value medium_auto;
3420     napi_value medium_ble;
3421     napi_value medium_coap;
3422     napi_value medium_usb;
3423     int32_t refCount = 1;
3424 
3425     napi_create_uint32(env, static_cast<uint32_t>(DmExchangeMedium::DM_AUTO),
3426         &medium_auto);
3427     napi_create_uint32(env, static_cast<uint32_t>(DmExchangeMedium::DM_BLE),
3428         &medium_ble);
3429     napi_create_uint32(env, static_cast<uint32_t>(DmExchangeMedium::DM_COAP),
3430         &medium_coap);
3431     napi_create_uint32(env, static_cast<uint32_t>(DmExchangeMedium::DM_USB),
3432         &medium_usb);
3433 
3434     napi_property_descriptor desc[] = {
3435         DECLARE_NAPI_STATIC_PROPERTY("AUTO", medium_auto),
3436         DECLARE_NAPI_STATIC_PROPERTY("BLE", medium_ble),
3437         DECLARE_NAPI_STATIC_PROPERTY("COAP", medium_coap),
3438         DECLARE_NAPI_STATIC_PROPERTY("USB", medium_usb),
3439     };
3440 
3441     napi_value result = nullptr;
3442     napi_define_class(env, "ExchangeMedium", NAPI_AUTO_LENGTH, EnumTypeConstructor,
3443         nullptr, sizeof(desc) / sizeof(*desc), desc, &result);
3444     napi_create_reference(env, result, refCount, &exchangeMediumEnumConstructor_);
3445     napi_set_named_property(env, exports, "ExchangeMedium", result);
3446     return exports;
3447 }
3448 
InitExchangeFreqEnum(napi_env env,napi_value exports)3449 napi_value DeviceManagerNapi::InitExchangeFreqEnum(napi_env env, napi_value exports)
3450 {
3451     napi_value low;
3452     napi_value mid;
3453     napi_value high;
3454     napi_value super_high;
3455     int32_t refCount = 1;
3456 
3457     napi_create_uint32(env, static_cast<uint32_t>(DmExchangeFreq::DM_LOW),
3458         &low);
3459     napi_create_uint32(env, static_cast<uint32_t>(DmExchangeFreq::DM_MID),
3460         &mid);
3461     napi_create_uint32(env, static_cast<uint32_t>(DmExchangeFreq::DM_HIGH),
3462         &high);
3463     napi_create_uint32(env, static_cast<uint32_t>(DmExchangeFreq::DM_SUPER_HIGH),
3464         &super_high);
3465 
3466     napi_property_descriptor desc[] = {
3467         DECLARE_NAPI_STATIC_PROPERTY("LOW", low),
3468         DECLARE_NAPI_STATIC_PROPERTY("MID", mid),
3469         DECLARE_NAPI_STATIC_PROPERTY("HIGH", high),
3470         DECLARE_NAPI_STATIC_PROPERTY("SUPER_HIGH", super_high),
3471     };
3472 
3473     napi_value result = nullptr;
3474     napi_define_class(env, "ExchangeFreq", NAPI_AUTO_LENGTH, EnumTypeConstructor,
3475         nullptr, sizeof(desc) / sizeof(*desc), desc, &result);
3476     napi_create_reference(env, result, refCount, &exchangeFreqEnumConstructor_);
3477     napi_set_named_property(env, exports, "ExchangeFreq", result);
3478     return exports;
3479 }
3480 
InitSubscribeCapEnum(napi_env env,napi_value exports)3481 napi_value DeviceManagerNapi::InitSubscribeCapEnum(napi_env env, napi_value exports)
3482 {
3483     napi_value subscribe_capability_ddmp;
3484     napi_value subscribe_capability_osd;
3485     int32_t refCount = 1;
3486 
3487     napi_create_uint32(env, static_cast<uint32_t>(DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP),
3488         &subscribe_capability_ddmp);
3489     napi_create_uint32(env, static_cast<uint32_t>(DM_NAPI_SUBSCRIBE_CAPABILITY_OSD),
3490         &subscribe_capability_osd);
3491 
3492     napi_property_descriptor desc[] = {
3493         DECLARE_NAPI_STATIC_PROPERTY("SUBSCRIBE_CAPABILITY_DDMP", subscribe_capability_ddmp),
3494         DECLARE_NAPI_STATIC_PROPERTY("SUBSCRIBE_CAPABILITY_OSD", subscribe_capability_osd),
3495     };
3496 
3497     napi_value result = nullptr;
3498     napi_define_class(env, "SubscribeCap", NAPI_AUTO_LENGTH, EnumTypeConstructor,
3499         nullptr, sizeof(desc) / sizeof(*desc), desc, &result);
3500     napi_create_reference(env, result, refCount, &subscribeCapEnumConstructor_);
3501     napi_set_named_property(env, exports, "SubscribeCap", result);
3502     return exports;
3503 }
3504 
3505 /*
3506  * Function registering all props and functions of ohos.distributedhardware
3507  */
Export(napi_env env,napi_value exports)3508 static napi_value Export(napi_env env, napi_value exports)
3509 {
3510     LOGI("Export() is called!");
3511     DeviceManagerNapi::Init(env, exports);
3512     DeviceManagerNapi::InitDeviceTypeEnum(env, exports);
3513     DeviceManagerNapi::InitDeviceStateChangeActionEnum(env, exports);
3514     DeviceManagerNapi::InitDiscoverModeEnum(env, exports);
3515     DeviceManagerNapi::InitExchangeMediumEnum(env, exports);
3516     DeviceManagerNapi::InitExchangeFreqEnum(env, exports);
3517     DeviceManagerNapi::InitSubscribeCapEnum(env, exports);
3518     return exports;
3519 }
3520 
3521 /*
3522  * module define
3523  */
3524 static napi_module g_dmModule = {.nm_version = 1,
3525                                  .nm_flags = 0,
3526                                  .nm_filename = nullptr,
3527                                  .nm_register_func = Export,
3528                                  .nm_modname = "distributedHardware.deviceManager",
3529                                  .nm_priv = ((void *)0),
3530                                  .reserved = {0}};
3531 
3532 /*
3533  * module register
3534  */
RegisterModule(void)3535 extern "C" __attribute__((constructor)) void RegisterModule(void)
3536 {
3537     LOGI("RegisterModule() is called!");
3538     napi_module_register(&g_dmModule);
3539 }
3540