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