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