• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 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 "dm_native_util.h"
17 
18 #include "dm_anonymous.h"
19 #include "dm_constants.h"
20 #include "dm_log.h"
21 #include "ipc_skeleton.h"
22 #include "js_native_api.h"
23 #include "tokenid_kit.h"
24 
25 using namespace OHOS::Security::AccessToken;
26 
27 namespace OHOS {
28 namespace DistributedHardware {
29 namespace {
30 const std::string ERR_MESSAGE_NO_PERMISSION =
31     "Permission verification failed. The application does not have the permission required to call the API.";
32 const std::string ERR_MESSAGE_NOT_SYSTEM_APP =
33     "Permission verification failed. A non-system application calls a system API.";
34 const std::string ERR_MESSAGE_INVALID_PARAMS = "Parameter error.";
35 const std::string ERR_MESSAGE_FAILED = "Failed to execute the function.";
36 const std::string ERR_MESSAGE_OBTAIN_SERVICE = "Failed to obtain the service.";
37 const std::string ERR_MESSAGE_AUTHENTICALTION_INVALID = "Authentication unavailable.";
38 const std::string ERR_MESSAGE_DISCOVERY_INVALID = "Discovery unavailable.";
39 const std::string ERR_MESSAGE_PUBLISH_INVALID = "Publish unavailable.";
40 const std::string ERR_MESSAGE_FROM_CLOUD_FAILED = "Get data from cloud failed.";
41 const std::string ERR_MESSAGE_NEED_LOGIN = "A login account is required.";
42 
43 const int32_t DM_NAPI_DISCOVER_EXTRA_INIT_ONE = -1;
44 const int32_t DM_NAPI_DISCOVER_EXTRA_INIT_TWO = -2;
45 const int32_t DM_NAPI_DESCRIPTION_BUF_LENGTH = 16384;
46 const int32_t DM_NAPI_BUF_LENGTH = 256;
47 
JsObjectToString(const napi_env & env,const napi_value & object,const std::string & fieldStr,char * dest,const int32_t destLen)48 void JsObjectToString(const napi_env &env, const napi_value &object, const std::string &fieldStr,
49                       char *dest, const int32_t destLen)
50 {
51     bool hasProperty = false;
52     NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty));
53     if (hasProperty) {
54         napi_value field = nullptr;
55         napi_valuetype valueType = napi_undefined;
56 
57         napi_get_named_property(env, object, fieldStr.c_str(), &field);
58         NAPI_CALL_RETURN_VOID(env, napi_typeof(env, field, &valueType));
59         if (!CheckArgsType(env, valueType == napi_string, fieldStr.c_str(), "string")) {
60             return;
61         }
62         size_t result = 0;
63         NAPI_CALL_RETURN_VOID(env, napi_get_value_string_utf8(env, field, dest, destLen, &result));
64     } else {
65         LOGE("devicemanager napi js to str no property: %{public}s", fieldStr.c_str());
66     }
67 }
68 
JsObjectToBool(const napi_env & env,const napi_value & object,const std::string & fieldStr,bool & fieldRef)69 void JsObjectToBool(const napi_env &env, const napi_value &object, const std::string &fieldStr,
70                     bool &fieldRef)
71 {
72     bool hasProperty = false;
73     NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty));
74     if (hasProperty) {
75         napi_value field = nullptr;
76         napi_valuetype valueType = napi_undefined;
77 
78         napi_get_named_property(env, object, fieldStr.c_str(), &field);
79         NAPI_CALL_RETURN_VOID(env, napi_typeof(env, field, &valueType));
80         if (!CheckArgsType(env, valueType == napi_boolean, fieldStr.c_str(), "bool")) {
81             return;
82         }
83         napi_get_value_bool(env, field, &fieldRef);
84     } else {
85         LOGE("devicemanager napi js to bool no property: %{public}s", fieldStr.c_str());
86         std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + " no property " + fieldStr;
87         napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str());
88     }
89 }
90 
JsObjectToInt(const napi_env & env,const napi_value & object,const std::string & fieldStr,int32_t & fieldRef)91 void JsObjectToInt(const napi_env &env, const napi_value &object, const std::string &fieldStr,
92                    int32_t &fieldRef)
93 {
94     bool hasProperty = false;
95     NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty));
96     if (hasProperty) {
97         napi_value field = nullptr;
98         napi_valuetype valueType = napi_undefined;
99 
100         napi_get_named_property(env, object, fieldStr.c_str(), &field);
101         NAPI_CALL_RETURN_VOID(env, napi_typeof(env, field, &valueType));
102         if (!CheckArgsType(env, valueType == napi_number, fieldStr.c_str(), "number")) {
103             return;
104         }
105         napi_get_value_int32(env, field, &fieldRef);
106     } else {
107         LOGE("devicemanager napi js to int no property: %{public}s", fieldStr.c_str());
108     }
109 }
110 
GetDeviceTypeById(DmDeviceType type)111 std::string GetDeviceTypeById(DmDeviceType type)
112 {
113     const static std::pair<DmDeviceType, std::string> mapArray[] = {
114         {DEVICE_TYPE_UNKNOWN, DEVICE_TYPE_UNKNOWN_STRING},
115         {DEVICE_TYPE_PHONE, DEVICE_TYPE_PHONE_STRING},
116         {DEVICE_TYPE_PAD, DEVICE_TYPE_PAD_STRING},
117         {DEVICE_TYPE_TV, DEVICE_TYPE_TV_STRING},
118         {DEVICE_TYPE_CAR, DEVICE_TYPE_CAR_STRING},
119         {DEVICE_TYPE_WATCH, DEVICE_TYPE_WATCH_STRING},
120         {DEVICE_TYPE_WIFI_CAMERA, DEVICE_TYPE_WIFICAMERA_STRING},
121         {DEVICE_TYPE_PC, DEVICE_TYPE_PC_STRING},
122         {DEVICE_TYPE_SMART_DISPLAY, DEVICE_TYPE_SMART_DISPLAY_STRING},
123         {DEVICE_TYPE_2IN1, DEVICE_TYPE_2IN1_STRING},
124     };
125     for (const auto& item : mapArray) {
126         if (item.first == type) {
127             return item.second;
128         }
129     }
130     return DEVICE_TYPE_UNKNOWN_STRING;
131 }
132 
CheckArgsVal(napi_env env,bool assertion,const std::string & param,const std::string & msg)133 bool CheckArgsVal(napi_env env, bool assertion, const std::string &param, const std::string &msg)
134 {
135     if (!(assertion)) {
136         std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + "The value of " + param + ": " + msg;
137         napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str());
138         return false;
139     }
140     return true;
141 }
142 }
143 
GenerateBusinessError(napi_env env,int32_t err,const std::string & msg)144 napi_value GenerateBusinessError(napi_env env, int32_t err, const std::string &msg)
145 {
146     napi_value businessError = nullptr;
147     NAPI_CALL(env, napi_create_object(env, &businessError));
148     napi_value errorCode = nullptr;
149     NAPI_CALL(env, napi_create_int32(env, err, &errorCode));
150     napi_value errorMessage = nullptr;
151     NAPI_CALL(env, napi_create_string_utf8(env, msg.c_str(), NAPI_AUTO_LENGTH, &errorMessage));
152     NAPI_CALL(env, napi_set_named_property(env, businessError, "code", errorCode));
153     NAPI_CALL(env, napi_set_named_property(env, businessError, "message", errorMessage));
154 
155     return businessError;
156 }
157 
CheckArgsCount(napi_env env,bool assertion,const std::string & message)158 bool CheckArgsCount(napi_env env, bool assertion, const std::string &message)
159 {
160     if (!(assertion)) {
161         std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + message;
162         napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str());
163         return false;
164     }
165     return true;
166 }
167 
CheckArgsType(napi_env env,bool assertion,const std::string & paramName,const std::string & type)168 bool CheckArgsType(napi_env env, bool assertion, const std::string &paramName, const std::string &type)
169 {
170     if (!(assertion)) {
171         std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + "The type of " + paramName +
172                 " must be " + type;
173         napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str());
174         return false;
175     }
176     return true;
177 }
178 
CreateErrorForCall(napi_env env,int32_t code,const std::string & errMsg,bool isAsync)179 napi_value CreateErrorForCall(napi_env env, int32_t code, const std::string &errMsg, bool isAsync)
180 {
181     LOGI("CreateErrorForCall code:%{public}d, message:%{public}s", code, errMsg.c_str());
182     napi_value error = nullptr;
183     if (isAsync) {
184         napi_throw_error(env, std::to_string(code).c_str(), errMsg.c_str());
185     } else {
186         error = GenerateBusinessError(env, code, errMsg);
187     }
188     return error;
189 }
190 
CreateBusinessError(napi_env env,int32_t errCode,bool isAsync)191 napi_value CreateBusinessError(napi_env env, int32_t errCode, bool isAsync)
192 {
193     napi_value error = nullptr;
194     switch (errCode) {
195         case ERR_DM_NO_PERMISSION:
196             error = CreateErrorForCall(env, ERR_NO_PERMISSION, ERR_MESSAGE_NO_PERMISSION, isAsync);
197             break;
198         case ERR_DM_DISCOVERY_REPEATED:
199             error = CreateErrorForCall(env, DM_ERR_DISCOVERY_INVALID, ERR_MESSAGE_DISCOVERY_INVALID, isAsync);
200             break;
201         case ERR_DM_PUBLISH_REPEATED:
202             error = CreateErrorForCall(env, DM_ERR_PUBLISH_INVALID, ERR_MESSAGE_PUBLISH_INVALID, isAsync);
203             break;
204         case ERR_DM_AUTH_BUSINESS_BUSY:
205             error = CreateErrorForCall(env, DM_ERR_AUTHENTICALTION_INVALID,
206                 ERR_MESSAGE_AUTHENTICALTION_INVALID, isAsync);
207             break;
208         case ERR_DM_INPUT_PARA_INVALID:
209         case ERR_DM_UNSUPPORTED_AUTH_TYPE:
210         case ERR_DM_MAX_SIZE_FAIL:
211             error = CreateErrorForCall(env, ERR_INVALID_PARAMS, ERR_MESSAGE_INVALID_PARAMS, isAsync);
212             break;
213         case ERR_DM_INIT_FAILED:
214             error = CreateErrorForCall(env, DM_ERR_OBTAIN_SERVICE, ERR_MESSAGE_OBTAIN_SERVICE, isAsync);
215             break;
216         case ERR_NOT_SYSTEM_APP:
217             error = CreateErrorForCall(env, ERR_NOT_SYSTEM_APP, ERR_MESSAGE_NOT_SYSTEM_APP, isAsync);
218             break;
219         case ERR_DM_HILINKSVC_RSP_PARSE_FAILD:
220         case ERR_DM_HILINKSVC_REPLY_FAILED:
221         case ERR_DM_HILINKSVC_ICON_URL_EMPTY:
222         case ERR_DM_HILINKSVC_DISCONNECT:
223             error = CreateErrorForCall(env, DM_ERR_FROM_CLOUD_FAILED, ERR_MESSAGE_FROM_CLOUD_FAILED, isAsync);
224             break;
225         case ERR_DM_WISE_NEED_LOGIN:
226             error = CreateErrorForCall(env, DM_ERR_NEED_LOGIN, ERR_MESSAGE_NEED_LOGIN, isAsync);
227             break;
228         default:
229             error = CreateErrorForCall(env, DM_ERR_FAILED, ERR_MESSAGE_FAILED, isAsync);
230             break;
231     }
232     return error;
233 }
234 
IsFunctionType(napi_env env,napi_value value)235 bool IsFunctionType(napi_env env, napi_value value)
236 {
237     napi_valuetype eventHandleType = napi_undefined;
238     napi_typeof(env, value, &eventHandleType);
239     return CheckArgsType(env, eventHandleType == napi_function, "callback", "function");
240 }
241 
SetValueUtf8String(const napi_env & env,const std::string & fieldStr,const std::string & str,napi_value & result)242 void SetValueUtf8String(const napi_env &env, const std::string &fieldStr, const std::string &str,
243                         napi_value &result)
244 {
245     napi_value value = nullptr;
246     napi_create_string_utf8(env, str.c_str(), NAPI_AUTO_LENGTH, &value);
247     napi_set_named_property(env, result, fieldStr.c_str(), value);
248 }
249 
SetValueInt32(const napi_env & env,const std::string & fieldStr,const int32_t intValue,napi_value & result)250 void SetValueInt32(const napi_env &env, const std::string &fieldStr, const int32_t intValue,
251                    napi_value &result)
252 {
253     napi_value value = nullptr;
254     napi_create_int32(env, intValue, &value);
255     napi_set_named_property(env, result, fieldStr.c_str(), value);
256 }
257 
DeviceBasicInfoToJsArray(const napi_env & env,const std::vector<DmDeviceBasicInfo> & vecDevInfo,const int32_t idx,napi_value & arrayResult)258 void DeviceBasicInfoToJsArray(const napi_env &env,
259                               const std::vector<DmDeviceBasicInfo> &vecDevInfo, const int32_t idx,
260                               napi_value &arrayResult)
261 {
262     napi_value result = nullptr;
263     napi_create_object(env, &result);
264     DmDeviceBasicToJsObject(env, vecDevInfo[idx], result);
265 
266     napi_status status = napi_set_element(env, arrayResult, idx, result);
267     if (status != napi_ok) {
268         LOGE("DmDeviceBasicInfo To JsArray set element error: %{public}d", status);
269     }
270 }
271 
DmDeviceBasicToJsObject(napi_env env,const DmDeviceBasicInfo & devInfo,napi_value & result)272 void DmDeviceBasicToJsObject(napi_env env, const DmDeviceBasicInfo &devInfo, napi_value &result)
273 {
274     SetValueUtf8String(env, "deviceId", devInfo.deviceId, result);
275     SetValueUtf8String(env, "networkId", devInfo.networkId, result);
276     SetValueUtf8String(env, "deviceName", devInfo.deviceName, result);
277     std::string deviceType = GetDeviceTypeById(static_cast<DmDeviceType>(devInfo.deviceTypeId));
278     SetValueUtf8String(env, "deviceType", deviceType.c_str(), result);
279 }
280 
JsToDmPublishInfo(const napi_env & env,const napi_value & object,DmPublishInfo & info)281 void JsToDmPublishInfo(const napi_env &env, const napi_value &object, DmPublishInfo &info)
282 {
283     int32_t publishId = -1;
284     JsObjectToInt(env, object, "publishId", publishId);
285     info.publishId = publishId;
286 
287     int32_t mode = -1;
288     JsObjectToInt(env, object, "mode", mode);
289     info.mode = static_cast<DmDiscoverMode>(mode);
290 
291     int32_t freq = -1;
292     JsObjectToInt(env, object, "freq", freq);
293     info.freq = static_cast<DmExchangeFreq>(freq);
294 
295     JsObjectToBool(env, object, "ranging", info.ranging);
296     return;
297 }
298 
JsToBindParam(const napi_env & env,const napi_value & object,std::string & bindParam,int32_t & bindType,bool & isMetaType)299 void JsToBindParam(const napi_env &env, const napi_value &object, std::string &bindParam,
300                    int32_t &bindType, bool &isMetaType)
301 {
302     int32_t bindTypeTemp = -1;
303     JsObjectToInt(env, object, "bindType", bindTypeTemp);
304     bindType = bindTypeTemp;
305 
306     char appOperation[DM_NAPI_DESCRIPTION_BUF_LENGTH] = "";
307     JsObjectToString(env, object, "appOperation", appOperation, sizeof(appOperation));
308     char customDescription[DM_NAPI_DESCRIPTION_BUF_LENGTH] = "";
309     JsObjectToString(env, object, "customDescription", customDescription, sizeof(customDescription));
310     char targetPkgName[DM_NAPI_BUF_LENGTH] = "";
311     JsObjectToString(env, object, "targetPkgName", targetPkgName, sizeof(targetPkgName));
312     char metaType[DM_NAPI_BUF_LENGTH] = "";
313     JsObjectToString(env, object, "metaType", metaType, sizeof(metaType));
314     std::string metaTypeStr = metaType;
315     isMetaType = !metaTypeStr.empty();
316 
317     char pinCode[DM_NAPI_BUF_LENGTH] = "";
318     JsObjectToString(env, object, "pinCode", pinCode, sizeof(pinCode));
319     char authToken[DM_NAPI_BUF_LENGTH] = "";
320     JsObjectToString(env, object, "authToken", authToken, sizeof(authToken));
321     char brMac[DM_NAPI_BUF_LENGTH] = "";
322     JsObjectToString(env, object, "brMac", brMac, sizeof(brMac));
323     char bleMac[DM_NAPI_BUF_LENGTH] = "";
324     JsObjectToString(env, object, "bleMac", bleMac, sizeof(bleMac));
325     char wifiIP[DM_NAPI_BUF_LENGTH] = "";
326     JsObjectToString(env, object, "wifiIP", wifiIP, sizeof(wifiIP));
327 
328     int32_t wifiPort = -1;
329     JsObjectToInt(env, object, "wifiPort", wifiPort);
330     int32_t bindLevel = 0;
331     JsObjectToInt(env, object, "bindLevel", bindLevel);
332 
333     nlohmann::json jsonObj;
334     jsonObj[AUTH_TYPE] = bindType;
335     jsonObj[APP_OPERATION] = std::string(appOperation);
336     jsonObj[CUSTOM_DESCRIPTION] = std::string(customDescription);
337     jsonObj[PARAM_KEY_TARGET_PKG_NAME] = std::string(targetPkgName);
338     jsonObj[PARAM_KEY_META_TYPE] = metaTypeStr;
339     jsonObj[PARAM_KEY_PIN_CODE] = std::string(pinCode);
340     jsonObj[PARAM_KEY_AUTH_TOKEN] = std::string(authToken);
341     jsonObj[PARAM_KEY_BR_MAC] = std::string(brMac);
342     jsonObj[PARAM_KEY_BLE_MAC] = std::string(bleMac);
343     jsonObj[PARAM_KEY_WIFI_IP] = std::string(wifiIP);
344     jsonObj[PARAM_KEY_WIFI_PORT] = wifiPort;
345     jsonObj[BIND_LEVEL] = bindLevel;
346     jsonObj[TOKENID] = OHOS::IPCSkeleton::GetSelfTokenID();
347     bindParam = jsonObj.dump();
348 }
349 
IsSystemApp()350 bool IsSystemApp()
351 {
352     uint64_t tokenId = OHOS::IPCSkeleton::GetSelfTokenID();
353     return OHOS::Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(tokenId);
354 }
355 
JsToDiscoverTargetType(napi_env env,const napi_value & object,int32_t & discoverTargetType)356 bool JsToDiscoverTargetType(napi_env env, const napi_value &object, int32_t &discoverTargetType)
357 {
358     napi_valuetype objectType = napi_undefined;
359     napi_typeof(env, object, &objectType);
360     if (!(CheckArgsType(env, objectType == napi_object, "discoverParameter", "object or undefined"))) {
361         return false;
362     }
363     bool hasProperty = false;
364     napi_has_named_property(env, object, "discoverTargetType", &hasProperty);
365     if (hasProperty) {
366         napi_value field = nullptr;
367         napi_valuetype valueType = napi_undefined;
368         napi_get_named_property(env, object, "discoverTargetType", &field);
369         napi_typeof(env, field, &valueType);
370         if (!CheckArgsType(env, valueType == napi_number, "discoverTargetType", "number")) {
371             return false;
372         }
373         napi_get_value_int32(env, field, &discoverTargetType);
374         return true;
375     }
376     LOGE("discoverTargetType is invalid.");
377     return false;
378 }
379 
JsToDmDiscoveryExtra(const napi_env & env,const napi_value & object,std::string & extra)380 void JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::string &extra)
381 {
382     nlohmann::json jsonObj;
383     int32_t availableStatus = DM_NAPI_DISCOVER_EXTRA_INIT_ONE;
384     JsObjectToInt(env, object, "availableStatus", availableStatus);
385     if (availableStatus != DM_NAPI_DISCOVER_EXTRA_INIT_ONE) {
386         jsonObj["credible"] = availableStatus;
387     }
388 
389     int32_t discoverDistance = DM_NAPI_DISCOVER_EXTRA_INIT_ONE;
390     JsObjectToInt(env, object, "discoverDistance", discoverDistance);
391     if (discoverDistance != DM_NAPI_DISCOVER_EXTRA_INIT_ONE) {
392         jsonObj["range"] = discoverDistance;
393     }
394 
395     int32_t authenticationStatus = DM_NAPI_DISCOVER_EXTRA_INIT_ONE;
396     JsObjectToInt(env, object, "authenticationStatus", authenticationStatus);
397     if (authenticationStatus != DM_NAPI_DISCOVER_EXTRA_INIT_ONE) {
398         jsonObj["isTrusted"] = authenticationStatus;
399     }
400 
401     int32_t authorizationType = DM_NAPI_DISCOVER_EXTRA_INIT_TWO;
402     JsObjectToInt(env, object, "authorizationType", authorizationType);
403     if (authorizationType != DM_NAPI_DISCOVER_EXTRA_INIT_TWO) {
404         jsonObj["authForm"] = authorizationType;
405     }
406 
407     int32_t deviceType = DM_NAPI_DISCOVER_EXTRA_INIT_ONE;
408     JsObjectToInt(env, object, "deviceType", deviceType);
409     if (deviceType != DM_NAPI_DISCOVER_EXTRA_INIT_ONE) {
410         jsonObj["deviceType"] = deviceType;
411     }
412     extra = jsonObj.dump();
413     LOGI("JsToDmDiscoveryExtra, extra :%{public}s", extra.c_str());
414 }
415 
InsertMapParames(nlohmann::json & bindParamObj,std::map<std::string,std::string> & bindParamMap)416 void InsertMapParames(nlohmann::json &bindParamObj, std::map<std::string, std::string> &bindParamMap)
417 {
418     LOGI("Insert map parames start");
419     if (IsInt32(bindParamObj, AUTH_TYPE)) {
420         int32_t authType = bindParamObj[AUTH_TYPE].get<int32_t>();
421         bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_AUTH_TYPE, std::to_string(authType)));
422     }
423     if (IsString(bindParamObj, APP_OPERATION)) {
424         std::string appOperation = bindParamObj[APP_OPERATION].get<std::string>();
425         bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_APP_OPER, appOperation));
426     }
427     if (IsString(bindParamObj, CUSTOM_DESCRIPTION)) {
428         std::string appDescription = bindParamObj[CUSTOM_DESCRIPTION].get<std::string>();
429         bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_APP_DESC, appDescription));
430     }
431     if (IsString(bindParamObj, PARAM_KEY_TARGET_PKG_NAME)) {
432         std::string targetPkgName = bindParamObj[PARAM_KEY_TARGET_PKG_NAME].get<std::string>();
433         bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_TARGET_PKG_NAME, targetPkgName));
434     }
435     if (IsString(bindParamObj, PARAM_KEY_META_TYPE)) {
436         std::string metaType = bindParamObj[PARAM_KEY_META_TYPE].get<std::string>();
437         bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_META_TYPE, metaType));
438     }
439     if (IsString(bindParamObj, PARAM_KEY_PIN_CODE)) {
440         std::string pinCode = bindParamObj[PARAM_KEY_PIN_CODE].get<std::string>();
441         bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_PIN_CODE, pinCode));
442     }
443     if (IsString(bindParamObj, PARAM_KEY_AUTH_TOKEN)) {
444         std::string authToken = bindParamObj[PARAM_KEY_AUTH_TOKEN].get<std::string>();
445         bindParamMap.insert(std::pair<std::string, std::string>(PARAM_KEY_AUTH_TOKEN, authToken));
446     }
447 }
448 
JsToStringAndCheck(napi_env env,napi_value value,const std::string & valueName,std::string & strValue)449 bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &valueName, std::string &strValue)
450 {
451     napi_valuetype deviceIdType = napi_undefined;
452     napi_typeof(env, value, &deviceIdType);
453     if (!CheckArgsType(env, deviceIdType == napi_string, valueName, "string")) {
454         return false;
455     }
456     size_t valueLen = 0;
457     napi_get_value_string_utf8(env, value, nullptr, 0, &valueLen);
458     if (!CheckArgsVal(env, valueLen > 0, valueName, "len == 0")) {
459         return false;
460     }
461     if (!CheckArgsVal(env, valueLen < DM_NAPI_BUF_LENGTH, valueName, "len >= MAXLEN")) {
462         return false;
463     }
464     char temp[DM_NAPI_BUF_LENGTH] = {0};
465     napi_get_value_string_utf8(env, value, temp, valueLen + 1, &valueLen);
466     strValue = temp;
467     return true;
468 }
469 
JsObjectToStrVector(const napi_env & env,const napi_value & object,const std::string & fieldStr,std::vector<std::string> & fieldRef)470 void JsObjectToStrVector(const napi_env &env, const napi_value &object, const std::string &fieldStr,
471     std::vector<std::string> &fieldRef)
472 {
473     bool hasProperty = false;
474     NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty));
475     if (!hasProperty) {
476         LOGE("no property: %{public}s", fieldStr.c_str());
477         return;
478     }
479 
480     napi_value field = nullptr;
481     napi_get_named_property(env, object, fieldStr.c_str(), &field);
482     bool isArr = false;
483     napi_is_array(env, field, &isArr);
484     if (!isArr) {
485         LOGE("property: %{public}s is not array", fieldStr.c_str());
486         return;
487     }
488     uint32_t length = 0;
489     napi_get_array_length(env, field, &length);
490     for (size_t i = 0; i < length; i++) {
491         napi_value element;
492         napi_get_element(env, field, i, &element);
493         size_t strLen = 0;
494         napi_get_value_string_utf8(env, element, nullptr, 0, &strLen);
495         if (strLen == 0) {
496             continue;
497         }
498         char buf[DEVICE_UUID_LENGTH] = {0};
499         napi_get_value_string_utf8(env, element, buf, strLen + 1, &strLen);
500         fieldRef.emplace_back(buf);
501     }
502 }
503 
JsToDmDeviceProfileInfoFilterOptions(const napi_env & env,const napi_value & object,DmDeviceProfileInfoFilterOptions & info)504 void JsToDmDeviceProfileInfoFilterOptions(const napi_env &env, const napi_value &object,
505     DmDeviceProfileInfoFilterOptions &info)
506 {
507     napi_valuetype filterOptionsType;
508     napi_typeof(env, object, &filterOptionsType);
509     if (filterOptionsType != napi_object) {
510         LOGE("filterOptions is not object");
511         std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + " The type of filterOptions must be object";
512         napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str());
513         return;
514     }
515     bool isCloud = false;
516     JsObjectToBool(env, object, "isCloud", isCloud);
517     info.isCloud = isCloud;
518     std::vector<std::string> deviceIdList;
519     JsObjectToStrVector(env, object, "deviceIdList", deviceIdList);
520     info.deviceIdList = deviceIdList;
521 }
522 
DmServiceProfileInfoToJsArray(const napi_env & env,const std::vector<DmServiceProfileInfo> & svrInfos,napi_value & arrayResult)523 void DmServiceProfileInfoToJsArray(const napi_env &env, const std::vector<DmServiceProfileInfo> &svrInfos,
524     napi_value &arrayResult)
525 {
526     for (uint32_t i = 0; i < svrInfos.size(); i++) {
527         napi_value item = nullptr;
528         napi_create_object(env, &item);
529         SetValueUtf8String(env, "deviceId", svrInfos[i].deviceId, item);
530         SetValueUtf8String(env, "serviceId", svrInfos[i].serviceId, item);
531         SetValueUtf8String(env, "serviceType", svrInfos[i].serviceType, item);
532         napi_value data = nullptr;
533         napi_create_object(env, &data);
534         for (const auto& [key, value] : svrInfos[i].data) {
535             SetValueUtf8String(env, key, value, data);
536         }
537         napi_set_named_property(env, item, "data", data);
538         napi_status status = napi_set_element(env, arrayResult, i, item);
539         if (status != napi_ok) {
540             LOGE("DmServiceProfileInfoToJsArray To JsArray set element error: %{public}d", status);
541         }
542     }
543 }
544 
DmProductInfoToJs(const napi_env & env,const DmProductInfo & prodInfo,napi_value & jsObj)545 void DmProductInfoToJs(const napi_env &env, const DmProductInfo &prodInfo, napi_value &jsObj)
546 {
547     SetValueUtf8String(env, "prodId", prodInfo.prodId, jsObj);
548     SetValueUtf8String(env, "model", prodInfo.model, jsObj);
549     SetValueUtf8String(env, "prodName", prodInfo.prodName, jsObj);
550     SetValueUtf8String(env, "prodShortName", prodInfo.prodShortName, jsObj);
551 }
552 
DmDeviceProfileInfoToJs(const napi_env & env,const DmDeviceProfileInfo & devInfo,napi_value & jsObj)553 void DmDeviceProfileInfoToJs(const napi_env &env, const DmDeviceProfileInfo &devInfo, napi_value &jsObj)
554 {
555     SetValueUtf8String(env, "deviceId", devInfo.deviceId, jsObj);
556     SetValueUtf8String(env, "deviceSn", devInfo.deviceSn, jsObj);
557     SetValueUtf8String(env, "mac", devInfo.mac, jsObj);
558     SetValueUtf8String(env, "model", devInfo.model, jsObj);
559     SetValueUtf8String(env, "deviceType", devInfo.deviceType, jsObj);
560     SetValueUtf8String(env, "manufacturer", devInfo.manufacturer, jsObj);
561     SetValueUtf8String(env, "deviceName", devInfo.deviceName, jsObj);
562     SetValueUtf8String(env, "productId", devInfo.productId, jsObj);
563     SetValueUtf8String(env, "subProductId", devInfo.subProductId, jsObj);
564     SetValueUtf8String(env, "sdkVersion", devInfo.sdkVersion, jsObj);
565     SetValueUtf8String(env, "bleMac", devInfo.bleMac, jsObj);
566     SetValueUtf8String(env, "brMac", devInfo.brMac, jsObj);
567     SetValueUtf8String(env, "sleMac", devInfo.sleMac, jsObj);
568     SetValueUtf8String(env, "firmwareVersion", devInfo.firmwareVersion, jsObj);
569     SetValueUtf8String(env, "hardwareVersion", devInfo.hardwareVersion, jsObj);
570     SetValueUtf8String(env, "softwareVersion", devInfo.softwareVersion, jsObj);
571     SetValueInt32(env, "protocolType", devInfo.protocolType, jsObj);
572     SetValueInt32(env, "setupType", devInfo.setupType, jsObj);
573     SetValueUtf8String(env, "wiseDeviceId", devInfo.wiseDeviceId, jsObj);
574     SetValueUtf8String(env, "wiseUserId", devInfo.wiseUserId, jsObj);
575     SetValueUtf8String(env, "registerTime", devInfo.registerTime, jsObj);
576     SetValueUtf8String(env, "modifyTime", devInfo.modifyTime, jsObj);
577     SetValueUtf8String(env, "shareTime", devInfo.shareTime, jsObj);
578     SetValueInt32(env, "isLocalDevice", devInfo.isLocalDevice ? 1 : 0, jsObj);
579 }
580 
DmDeviceProfileInfoToJsArray(const napi_env & env,const std::vector<DmDeviceProfileInfo> & devInfos,napi_value & arrayResult)581 void DmDeviceProfileInfoToJsArray(const napi_env &env, const std::vector<DmDeviceProfileInfo> &devInfos,
582     napi_value &arrayResult)
583 {
584     for (unsigned int i = 0; i < devInfos.size(); i++) {
585         napi_value item = nullptr;
586         napi_create_object(env, &item);
587         DmDeviceProfileInfoToJs(env, devInfos[i], item);
588         if (!devInfos[i].services.empty()) {
589             napi_value services = nullptr;
590             napi_create_array(env, &services);
591             bool isArray = false;
592             napi_is_array(env, services, &isArray);
593             if (!isArray) {
594                 LOGE("napi_create_array failed");
595             }
596             DmServiceProfileInfoToJsArray(env, devInfos[i].services, services);
597             napi_set_named_property(env, item, "services", services);
598         }
599         napi_status status = napi_set_element(env, arrayResult, i, item);
600         if (status != napi_ok) {
601             LOGE("DmDeviceProfileInfo To JsArray set element error: %{public}d", status);
602         }
603     }
604 }
605 } // namespace DistributedHardware
606 } // namespace OHOS
607