• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "bundle_mgr.h"
16 
17 #include <string>
18 #include <unordered_map>
19 
20 #include "app_log_wrapper.h"
21 #include "appexecfwk_errors.h"
22 #include "bundle_constants.h"
23 #include "bundle_mgr_client.h"
24 #include "bundle_mgr_interface.h"
25 #include "bundle_mgr_proxy.h"
26 #include "cleancache_callback.h"
27 #include "common_func.h"
28 #include "if_system_ability_manager.h"
29 #include "installer_callback.h"
30 #include "ipc_skeleton.h"
31 #include "iservice_registry.h"
32 #include "napi/native_api.h"
33 #include "napi/native_node_api.h"
34 #ifdef BUNDLE_FRAMEWORK_GRAPHICS
35 #include "bundle_graphics_client.h"
36 #include "pixel_map_napi.h"
37 #endif
38 #include "securec.h"
39 #include "system_ability_definition.h"
40 
41 namespace OHOS {
42 namespace AppExecFwk {
43 using namespace OHOS;
44 using namespace OHOS::AAFwk;
45 using namespace OHOS::AppExecFwk;
46 using namespace OHOS::AbilityRuntime;
47 
48 namespace {
49 constexpr size_t NAPI_ERR_NO_ERROR = 0;
50 constexpr size_t ARGS_ASYNC_COUNT = 1;
51 constexpr size_t ARGS_MAX_COUNT = 10;
52 constexpr size_t CALLBACK_SIZE = 1;
53 constexpr size_t ARGS_SIZE_ONE = 1;
54 constexpr size_t ARGS_SIZE_TWO = 2;
55 constexpr size_t ARGS_SIZE_THREE = 3;
56 constexpr size_t ARGS_SIZE_FOUR = 4;
57 constexpr size_t ARGS_SIZE_FIVE = 5;
58 constexpr int32_t PARAM0 = 0;
59 constexpr int32_t PARAM1 = 1;
60 constexpr int32_t PARAM2 = 2;
61 constexpr int32_t PARAM3 = 3;
62 constexpr int32_t NAPI_RETURN_FAILED = -1;
63 constexpr int32_t NAPI_RETURN_ZERO = 0;
64 constexpr int32_t NAPI_RETURN_ONE = 1;
65 constexpr int32_t NAPI_RETURN_TWO = 2;
66 constexpr int32_t NAPI_RETURN_THREE = 3;
67 constexpr int32_t CODE_SUCCESS = 0;
68 constexpr int32_t CODE_FAILED = -1;
69 constexpr int32_t OPERATION_FAILED = 1;
70 constexpr int32_t INVALID_PARAM = 2;
71 constexpr int32_t PARAM_TYPE_ERROR = 1;
72 constexpr int32_t UNDEFINED_ERROR = -1;
73 #ifndef BUNDLE_FRAMEWORK_GRAPHICS
74 constexpr int32_t UNSUPPORTED_FEATURE_ERRCODE = 801;
75 const std::string UNSUPPORTED_FEATURE_MESSAGE = "unsupported BundleManagerService feature";
76 #endif
77 enum class InstallErrorCode {
78     SUCCESS = 0,
79     STATUS_INSTALL_FAILURE = 1,
80     STATUS_INSTALL_FAILURE_ABORTED = 2,
81     STATUS_INSTALL_FAILURE_INVALID = 3,
82     STATUS_INSTALL_FAILURE_CONFLICT = 4,
83     STATUS_INSTALL_FAILURE_STORAGE = 5,
84     STATUS_INSTALL_FAILURE_INCOMPATIBLE = 6,
85     STATUS_UNINSTALL_FAILURE = 7,
86     STATUS_UNINSTALL_FAILURE_BLOCKED = 8,
87     STATUS_UNINSTALL_FAILURE_ABORTED = 9,
88     STATUS_UNINSTALL_FAILURE_CONFLICT = 10,
89     STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT = 0x0B,
90     STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED = 0x0C,
91     STATUS_RECOVER_FAILURE_INVALID = 0x0D,
92     STATUS_ABILITY_NOT_FOUND = 0x40,
93     STATUS_BMS_SERVICE_ERROR = 0x41,
94     STATUS_FAILED_NO_SPACE_LEFT = 0X42,
95     STATUS_GRANT_REQUEST_PERMISSIONS_FAILED = 0X43,
96     STATUS_INSTALL_PERMISSION_DENIED = 0X44,
97     STATUS_UNINSTALL_PERMISSION_DENIED = 0X45,
98     STATUS_USER_NOT_EXIST = 0X50,
99     STATUS_USER_FAILURE_INVALID = 0X51,
100     STATUS_USER_CREATE_FAILED = 0X52,
101     STATUS_USER_REMOVE_FAILED = 0X53,
102 };
103 
104 const std::string PERMISSION_CHANGE = "permissionChange";
105 const std::string ANY_PERMISSION_CHANGE = "anyPermissionChange";
106 
107 const std::string GET_APPLICATION_INFO = "getApplicationInfo";
108 const std::string GET_BUNDLE_INFO = "getBundleInfo";
109 const std::string QUERY_ABILITY_BY_WANT = "queryAbilityByWant";
110 
111 const std::vector<int32_t> PACKINFO_FLAGS = {
112     BundlePackFlag::GET_PACK_INFO_ALL,
113     BundlePackFlag::GET_PACKAGES,
114     BundlePackFlag::GET_BUNDLE_SUMMARY,
115     BundlePackFlag::GET_MODULE_SUMMARY,
116 };
117 
118 thread_local std::mutex g_permissionsCallbackMutex;
119 thread_local std::mutex g_anyPermissionsCallbackMutex;
120 
121 struct PermissionsKey {
122     napi_ref callback = 0;
123     std::vector<int32_t> uids;
operator <OHOS::AppExecFwk::__anon9e59f0310111::PermissionsKey124     bool operator<(const PermissionsKey &other) const
125     {
126         return this->callback < other.callback;
127     }
128 };
129 
130 static OHOS::sptr<OHOS::AppExecFwk::IBundleMgr> bundleMgr_ = nullptr;
131 static std::unordered_map<Query, napi_ref, QueryHash> cache;
132 static std::unordered_map<Query, napi_ref, QueryHash> abilityInfoCache;
133 static std::unordered_map<Query, NativeReference*, QueryHash> nativeAbilityInfoCache;
134 static std::mutex abilityInfoCacheMutex_;
135 static std::mutex bundleMgrMutex_;
136 static sptr<BundleMgrDeathRecipient> bundleMgrDeathRecipient(new (std::nothrow) BundleMgrDeathRecipient());
137 }  // namespace
138 
OnRemoteDied(const wptr<IRemoteObject> & remote)139 void BundleMgrDeathRecipient::OnRemoteDied([[maybe_unused]] const wptr<IRemoteObject>& remote)
140 {
141     APP_LOGD("BundleManagerService dead.");
142     std::lock_guard<std::mutex> lock(bundleMgrMutex_);
143     bundleMgr_ = nullptr;
144 };
145 
AsyncWorkData(napi_env napiEnv)146 AsyncWorkData::AsyncWorkData(napi_env napiEnv) : env(napiEnv) {}
147 
~AsyncWorkData()148 AsyncWorkData::~AsyncWorkData()
149 {
150     if (callback) {
151         APP_LOGD("AsyncWorkData::~AsyncWorkData delete callback");
152         napi_delete_reference(env, callback);
153         callback = nullptr;
154     }
155     if (asyncWork) {
156         APP_LOGD("AsyncWorkData::~AsyncWorkData delete asyncWork");
157         napi_delete_async_work(env, asyncWork);
158         asyncWork = nullptr;
159     }
160 }
161 napi_ref thread_local g_classBundleInstaller;
162 
GetBundleMgr()163 static OHOS::sptr<OHOS::AppExecFwk::IBundleMgr> GetBundleMgr()
164 {
165     if (bundleMgr_ == nullptr) {
166         std::lock_guard<std::mutex> lock(bundleMgrMutex_);
167         if (bundleMgr_ == nullptr) {
168             auto systemAbilityManager = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
169             if (systemAbilityManager == nullptr) {
170                 APP_LOGE("GetBundleMgr GetSystemAbilityManager is null");
171                 return nullptr;
172             }
173             auto bundleMgrSa = systemAbilityManager->GetSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
174             if (bundleMgrSa == nullptr) {
175                 APP_LOGE("GetBundleMgr GetSystemAbility is null");
176                 return nullptr;
177             }
178             auto bundleMgr = OHOS::iface_cast<IBundleMgr>(bundleMgrSa);
179             if (bundleMgr == nullptr) {
180                 APP_LOGE("GetBundleMgr iface_cast get null");
181             }
182             bundleMgr_ = bundleMgr;
183             bundleMgr_->AsObject()->AddDeathRecipient(bundleMgrDeathRecipient);
184         }
185     }
186     return bundleMgr_;
187 }
188 
HandleAbilityInfoCache(napi_env env,const Query & query,const AsyncAbilityInfoCallbackInfo * info,napi_value jsObject)189 static void HandleAbilityInfoCache(
190     napi_env env, const Query &query, const AsyncAbilityInfoCallbackInfo *info, napi_value jsObject)
191 {
192     if (info == nullptr) {
193         return;
194     }
195     ElementName element = info->want.GetElement();
196     if (element.GetBundleName().empty() || element.GetAbilityName().empty()) {
197         return;
198     }
199     uint32_t explicitQueryResultLen = 1;
200     if (info->abilityInfos.size() != explicitQueryResultLen ||
201         info->abilityInfos[0].uid != IPCSkeleton::GetCallingUid()) {
202         return;
203     }
204     napi_ref cacheAbilityInfo = nullptr;
205     NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, jsObject, NAPI_RETURN_ONE, &cacheAbilityInfo));
206     abilityInfoCache.clear();
207     abilityInfoCache[query] = cacheAbilityInfo;
208 }
209 
CheckIsSystemApp()210 static bool CheckIsSystemApp()
211 {
212     auto iBundleMgr = GetBundleMgr();
213     if (iBundleMgr == nullptr) {
214         APP_LOGE("can not get iBundleMgr");
215         return false;
216     }
217 
218     int32_t uid = IPCSkeleton::GetCallingUid();
219     return iBundleMgr->CheckIsSystemAppByUid(uid);
220 }
221 
ConvertCustomizeData(napi_env env,napi_value objCustomizeData,const CustomizeData & customizeData)222 static void ConvertCustomizeData(napi_env env, napi_value objCustomizeData, const CustomizeData &customizeData)
223 {
224     napi_value nName;
225     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, customizeData.name.c_str(), NAPI_AUTO_LENGTH, &nName));
226     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objCustomizeData, "name", nName));
227     napi_value nValue;
228     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, customizeData.value.c_str(), NAPI_AUTO_LENGTH, &nValue));
229     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objCustomizeData, "value", nValue));
230     napi_value nExtra;
231     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, customizeData.extra.c_str(), NAPI_AUTO_LENGTH, &nExtra));
232     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objCustomizeData, "extra", nExtra));
233 }
234 
ConvertInnerMetadata(napi_env env,napi_value value,const Metadata & metadata)235 static void ConvertInnerMetadata(napi_env env, napi_value value, const Metadata &metadata)
236 {
237     napi_value nName;
238     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, metadata.name.c_str(), NAPI_AUTO_LENGTH, &nName));
239     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "name", nName));
240     napi_value nValue;
241     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, metadata.value.c_str(), NAPI_AUTO_LENGTH, &nValue));
242     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "value", nValue));
243     napi_value nResource;
244     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, metadata.resource.c_str(), NAPI_AUTO_LENGTH, &nResource));
245     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "resource", nResource));
246 }
247 
ConvertResource(napi_env env,napi_value objResource,const Resource & resource)248 static void ConvertResource(napi_env env, napi_value objResource, const Resource &resource)
249 {
250     napi_value nBundleName;
251     NAPI_CALL_RETURN_VOID(
252         env, napi_create_string_utf8(env, resource.bundleName.c_str(), NAPI_AUTO_LENGTH, &nBundleName));
253     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objResource, "bundleName", nBundleName));
254 
255     napi_value nModuleName;
256     NAPI_CALL_RETURN_VOID(
257         env, napi_create_string_utf8(env, resource.moduleName.c_str(), NAPI_AUTO_LENGTH, &nModuleName));
258     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objResource, "moduleName", nModuleName));
259 
260     napi_value nId;
261     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, resource.id, &nId));
262     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objResource, "id", nId));
263 }
264 
ConvertApplicationInfo(napi_env env,napi_value objAppInfo,const ApplicationInfo & appInfo)265 static void ConvertApplicationInfo(napi_env env, napi_value objAppInfo, const ApplicationInfo &appInfo)
266 {
267     napi_value nName;
268     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.name.c_str(), NAPI_AUTO_LENGTH, &nName));
269     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "name", nName));
270     APP_LOGI("ConvertApplicationInfo name=%{public}s.", appInfo.name.c_str());
271 
272     napi_value nCodePath;
273     NAPI_CALL_RETURN_VOID(
274         env, napi_create_string_utf8(env, appInfo.codePath.c_str(), NAPI_AUTO_LENGTH, &nCodePath));
275     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "codePath", nCodePath));
276 
277     napi_value nAccessTokenId;
278     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, appInfo.accessTokenId, &nAccessTokenId));
279     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "accessTokenId", nAccessTokenId));
280 
281     napi_value nDescription;
282     NAPI_CALL_RETURN_VOID(
283         env, napi_create_string_utf8(env, appInfo.description.c_str(), NAPI_AUTO_LENGTH, &nDescription));
284     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "description", nDescription));
285 
286     napi_value nDescriptionId;
287     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.descriptionId, &nDescriptionId));
288     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "descriptionId", nDescriptionId));
289 
290     napi_value nIconPath;
291     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.iconPath.c_str(), NAPI_AUTO_LENGTH, &nIconPath));
292     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "icon", nIconPath));
293 
294     napi_value nIconId;
295     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.iconId, &nIconId));
296     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "iconId", nIconId));
297 
298     napi_value nLabel;
299     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.label.c_str(), NAPI_AUTO_LENGTH, &nLabel));
300     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "label", nLabel));
301 
302     napi_value nLabelId;
303     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.labelId, &nLabelId));
304     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "labelId", nLabelId));
305 
306     napi_value nIsSystemApp;
307     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, appInfo.isSystemApp, &nIsSystemApp));
308     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "systemApp", nIsSystemApp));
309 
310     napi_value nSupportedModes;
311     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.supportedModes, &nSupportedModes));
312     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "supportedModes", nSupportedModes));
313 
314     napi_value nProcess;
315     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.process.c_str(), NAPI_AUTO_LENGTH, &nProcess));
316     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "process", nProcess));
317 
318     napi_value nIconIndex;
319     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.iconId, &nIconIndex));
320     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "iconIndex", nIconIndex));
321 
322     napi_value nLabelIndex;
323     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.labelId, &nLabelIndex));
324     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "labelIndex", nLabelIndex));
325 
326     napi_value nEntryDir;
327     NAPI_CALL_RETURN_VOID(
328         env, napi_create_string_utf8(env, appInfo.entryDir.c_str(), NAPI_AUTO_LENGTH, &nEntryDir));
329     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "entryDir", nEntryDir));
330 
331     napi_value nPermissions;
332     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nPermissions));
333     for (size_t idx = 0; idx < appInfo.permissions.size(); idx++) {
334         napi_value nPermission;
335         NAPI_CALL_RETURN_VOID(
336             env, napi_create_string_utf8(env, appInfo.permissions[idx].c_str(), NAPI_AUTO_LENGTH, &nPermission));
337         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nPermissions, idx, nPermission));
338     }
339     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "permissions", nPermissions));
340 
341     napi_value nModuleSourceDirs;
342     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nModuleSourceDirs));
343     for (size_t idx = 0; idx < appInfo.moduleSourceDirs.size(); idx++) {
344         napi_value nModuleSourceDir;
345         NAPI_CALL_RETURN_VOID(env,
346             napi_create_string_utf8(env, appInfo.moduleSourceDirs[idx].c_str(), NAPI_AUTO_LENGTH, &nModuleSourceDir));
347         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nModuleSourceDirs, idx, nModuleSourceDir));
348     }
349     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "moduleSourceDirs", nModuleSourceDirs));
350 
351     napi_value nModuleInfos;
352     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nModuleInfos));
353     for (size_t idx = 0; idx < appInfo.moduleInfos.size(); idx++) {
354         napi_value objModuleInfos;
355         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objModuleInfos));
356 
357         napi_value nModuleName;
358         NAPI_CALL_RETURN_VOID(env,
359             napi_create_string_utf8(env, appInfo.moduleInfos[idx].moduleName.c_str(), NAPI_AUTO_LENGTH, &nModuleName));
360         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleInfos, "moduleName", nModuleName));
361 
362         napi_value nModuleSourceDir;
363         NAPI_CALL_RETURN_VOID(env,
364             napi_create_string_utf8(
365                 env, appInfo.moduleInfos[idx].moduleSourceDir.c_str(), NAPI_AUTO_LENGTH, &nModuleSourceDir));
366         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleInfos, "moduleSourceDir", nModuleSourceDir));
367 
368         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nModuleInfos, idx, objModuleInfos));
369     }
370     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "moduleInfos", nModuleInfos));
371 
372     napi_value nMetaData;
373     NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nMetaData));
374     for (const auto &item : appInfo.metaData) {
375         napi_value nCustomizeDataArray;
376         NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nCustomizeDataArray));
377         for (size_t j = 0; j < item.second.size(); j++) {
378             napi_value nCustomizeData;
379             NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nCustomizeData));
380             ConvertCustomizeData(env, nCustomizeData, item.second[j]);
381             NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nCustomizeDataArray, j, nCustomizeData));
382         }
383         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, nMetaData, item.first.c_str(), nCustomizeDataArray));
384     }
385     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "metaData", nMetaData));
386 
387     napi_value nMetadata;
388     NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nMetadata));
389     for (const auto &item : appInfo.metadata) {
390         napi_value nInnerMetadata;
391         size_t len = item.second.size();
392         NAPI_CALL_RETURN_VOID(env, napi_create_array_with_length(env, len, &nInnerMetadata));
393         for (size_t index = 0; index < len; ++index) {
394             napi_value nMeta;
395             NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nMeta));
396             ConvertInnerMetadata(env, nMeta, item.second[index]);
397             NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nInnerMetadata, index, nMeta));
398         }
399         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, nMetadata, item.first.c_str(), nInnerMetadata));
400     }
401     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "metadata", nMetadata));
402 
403     napi_value nEnabled;
404     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, appInfo.enabled, &nEnabled));
405     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "enabled", nEnabled));
406 
407     napi_value nUid;
408     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.uid, &nUid));
409     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "uid", nUid));
410 
411     napi_value nEntityType;
412     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.entityType.c_str(), NAPI_AUTO_LENGTH,
413         &nEntityType));
414     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "entityType", nEntityType));
415 
416     napi_value nRemovable;
417     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, appInfo.removable, &nRemovable));
418     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "removable", nRemovable));
419 
420     napi_value nFingerprint;
421     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.fingerprint.c_str(), NAPI_AUTO_LENGTH,
422         &nFingerprint));
423     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "fingerprint", nFingerprint));
424 
425     napi_value nIconResource;
426     NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nIconResource));
427     ConvertResource(env, nIconResource, appInfo.iconResource);
428     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "iconResource", nIconResource));
429 
430     napi_value nLabelResource;
431     NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nLabelResource));
432     ConvertResource(env, nLabelResource, appInfo.labelResource);
433     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "labelResource", nLabelResource));
434 
435     napi_value nDescriptionResource;
436     NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nDescriptionResource));
437     ConvertResource(env, nDescriptionResource, appInfo.descriptionResource);
438     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "descriptionResource", nDescriptionResource));
439 
440     napi_value nAppDistributionType;
441     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.appDistributionType.c_str(), NAPI_AUTO_LENGTH,
442         &nAppDistributionType));
443     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "appDistributionType", nAppDistributionType));
444 
445     napi_value nAppProvisionType;
446     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.appProvisionType.c_str(), NAPI_AUTO_LENGTH,
447         &nAppProvisionType));
448     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "appProvisionType", nAppProvisionType));
449 }
450 
ConvertMetaData(napi_env env,napi_value objMetaData,const MetaData & metaData)451 static void ConvertMetaData(napi_env env, napi_value objMetaData, const MetaData &metaData)
452 {
453     for (size_t idx = 0; idx < metaData.customizeData.size(); idx++) {
454         napi_value nCustomizeData;
455         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nCustomizeData));
456         ConvertCustomizeData(env, nCustomizeData, metaData.customizeData[idx]);
457         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, objMetaData, idx, nCustomizeData));
458     }
459 }
460 
ConvertAbilityInfo(napi_env env,napi_value objAbilityInfo,const AbilityInfo & abilityInfo)461 static void ConvertAbilityInfo(napi_env env, napi_value objAbilityInfo, const AbilityInfo &abilityInfo)
462 {
463     napi_value nName;
464     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, abilityInfo.name.c_str(), NAPI_AUTO_LENGTH, &nName));
465     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "name", nName));
466 
467     napi_value nLabel;
468     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, abilityInfo.label.c_str(), NAPI_AUTO_LENGTH, &nLabel));
469     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "label", nLabel));
470 
471     napi_value nDescription;
472     NAPI_CALL_RETURN_VOID(
473         env, napi_create_string_utf8(env, abilityInfo.description.c_str(), NAPI_AUTO_LENGTH, &nDescription));
474     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "description", nDescription));
475 
476     napi_value nIconPath;
477     NAPI_CALL_RETURN_VOID(
478         env, napi_create_string_utf8(env, abilityInfo.iconPath.c_str(), NAPI_AUTO_LENGTH, &nIconPath));
479     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "icon", nIconPath));
480 
481     napi_value nVisible;
482     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, abilityInfo.visible, &nVisible));
483     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "isVisible", nVisible));
484 
485     napi_value nPermissions;
486     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nPermissions));
487     for (size_t idx = 0; idx < abilityInfo.permissions.size(); idx++) {
488         napi_value nPermission;
489         NAPI_CALL_RETURN_VOID(
490             env, napi_create_string_utf8(env, abilityInfo.permissions[idx].c_str(), NAPI_AUTO_LENGTH, &nPermission));
491         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nPermissions, idx, nPermission));
492     }
493     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "permissions", nPermissions));
494 
495     napi_value nDeviceCapabilities;
496     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nDeviceCapabilities));
497     for (size_t idx = 0; idx < abilityInfo.deviceCapabilities.size(); idx++) {
498         napi_value nDeviceCapability;
499         NAPI_CALL_RETURN_VOID(env,
500             napi_create_string_utf8(
501                 env, abilityInfo.deviceCapabilities[idx].c_str(), NAPI_AUTO_LENGTH, &nDeviceCapability));
502         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nDeviceCapabilities, idx, nDeviceCapability));
503     }
504     NAPI_CALL_RETURN_VOID(
505         env, napi_set_named_property(env, objAbilityInfo, "deviceCapabilities", nDeviceCapabilities));
506 
507     napi_value nDeviceTypes;
508     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nDeviceTypes));
509     for (size_t idx = 0; idx < abilityInfo.deviceTypes.size(); idx++) {
510         napi_value nDeviceType;
511         NAPI_CALL_RETURN_VOID(
512             env, napi_create_string_utf8(env, abilityInfo.deviceTypes[idx].c_str(), NAPI_AUTO_LENGTH, &nDeviceType));
513         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nDeviceTypes, idx, nDeviceType));
514     }
515     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "deviceTypes", nDeviceTypes));
516 
517     napi_value nProcess;
518     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, abilityInfo.process.c_str(), NAPI_AUTO_LENGTH, &nProcess));
519     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "process", nProcess));
520 
521     napi_value nUri;
522     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, abilityInfo.uri.c_str(), NAPI_AUTO_LENGTH, &nUri));
523     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "uri", nUri));
524 
525     napi_value nBundleName;
526     NAPI_CALL_RETURN_VOID(
527         env, napi_create_string_utf8(env, abilityInfo.bundleName.c_str(), NAPI_AUTO_LENGTH, &nBundleName));
528     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "bundleName", nBundleName));
529 
530     napi_value nModuleName;
531     NAPI_CALL_RETURN_VOID(
532         env, napi_create_string_utf8(env, abilityInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &nModuleName));
533     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "moduleName", nModuleName));
534 
535     napi_value nAppInfo;
536     NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nAppInfo));
537     ConvertApplicationInfo(env, nAppInfo, abilityInfo.applicationInfo);
538     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "applicationInfo", nAppInfo));
539 
540     napi_value nType;
541     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast<int32_t>(abilityInfo.type), &nType));
542     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "type", nType));
543 
544     napi_value nOrientation;
545     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast<int32_t>(abilityInfo.orientation), &nOrientation));
546     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "orientation", nOrientation));
547 
548     napi_value nLaunchMode;
549     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast<int32_t>(abilityInfo.launchMode), &nLaunchMode));
550     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "launchMode", nLaunchMode));
551 
552     napi_value nBackgroundModes;
553     if (!abilityInfo.isModuleJson) {
554         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, abilityInfo.backgroundModes, &nBackgroundModes));
555     } else {
556         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nBackgroundModes));
557     }
558     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "backgroundModes", nBackgroundModes));
559 
560     napi_value nDescriptionId;
561     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, abilityInfo.descriptionId, &nDescriptionId));
562     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "descriptionId", nDescriptionId));
563 
564     napi_value nFormEnabled;
565     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, abilityInfo.formEnabled, &nFormEnabled));
566     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "formEnabled", nFormEnabled));
567 
568     napi_value nIconId;
569     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, abilityInfo.iconId, &nIconId));
570     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "iconId", nIconId));
571 
572     napi_value nLabelId;
573     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, abilityInfo.labelId, &nLabelId));
574     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "labelId", nLabelId));
575 
576     napi_value nSubType;
577     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast<int32_t>(abilityInfo.subType), &nSubType));
578     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "subType", nSubType));
579 
580     napi_value nReadPermission;
581     NAPI_CALL_RETURN_VOID(
582         env, napi_create_string_utf8(env, abilityInfo.readPermission.c_str(), NAPI_AUTO_LENGTH, &nReadPermission));
583     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "readPermission", nReadPermission));
584 
585     napi_value nWritePermission;
586     NAPI_CALL_RETURN_VOID(
587         env, napi_create_string_utf8(env, abilityInfo.writePermission.c_str(), NAPI_AUTO_LENGTH, &nWritePermission));
588     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "writePermission", nWritePermission));
589 
590     napi_value nTargetAbility;
591     NAPI_CALL_RETURN_VOID(env,
592         napi_create_string_utf8(env, abilityInfo.targetAbility.c_str(), NAPI_AUTO_LENGTH, &nTargetAbility));
593     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "targetAbility", nTargetAbility));
594 
595     napi_value nMetaData;
596     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nMetaData));
597     ConvertMetaData(env, nMetaData, abilityInfo.metaData);
598     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "metaData", nMetaData));
599 
600     napi_value nMetadata;
601     size_t size = abilityInfo.metadata.size();
602     NAPI_CALL_RETURN_VOID(env, napi_create_array_with_length(env, size, &nMetadata));
603     for (size_t index = 0; index < size; ++index) {
604         napi_value innerMeta;
605         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &innerMeta));
606         ConvertInnerMetadata(env, innerMeta, abilityInfo.metadata[index]);
607         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nMetadata, index, innerMeta));
608     }
609     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "metadata", nMetadata));
610 
611     napi_value nEnabled;
612     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, abilityInfo.enabled, &nEnabled));
613     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "enabled", nEnabled));
614 
615     napi_value nMaxWindowRatio;
616     NAPI_CALL_RETURN_VOID(env, napi_create_double(env, abilityInfo.maxWindowRatio, &nMaxWindowRatio));
617     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "maxWindowRatio", nMaxWindowRatio));
618 
619     napi_value mMinWindowRatio;
620     NAPI_CALL_RETURN_VOID(env, napi_create_double(env, abilityInfo.minWindowRatio, &mMinWindowRatio));
621     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "minWindowRatio", mMinWindowRatio));
622 
623     napi_value nMaxWindowWidth;
624     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, abilityInfo.maxWindowWidth, &nMaxWindowWidth));
625     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "maxWindowWidth", nMaxWindowWidth));
626 
627     napi_value nMinWindowWidth;
628     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, abilityInfo.minWindowWidth, &nMinWindowWidth));
629     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "minWindowWidth", nMinWindowWidth));
630 
631     napi_value nMaxWindowHeight;
632     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, abilityInfo.maxWindowHeight, &nMaxWindowHeight));
633     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "maxWindowHeight", nMaxWindowHeight));
634 
635     napi_value nMinWindowHeight;
636     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, abilityInfo.minWindowHeight, &nMinWindowHeight));
637     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "minWindowHeight", nMinWindowHeight));
638 }
639 
ProcessAbilityInfos(napi_env env,napi_value result,const std::vector<OHOS::AppExecFwk::AbilityInfo> & abilityInfos)640 static void ProcessAbilityInfos(
641     napi_env env, napi_value result, const std::vector<OHOS::AppExecFwk::AbilityInfo> &abilityInfos)
642 {
643     if (abilityInfos.size() > 0) {
644         APP_LOGI("-----abilityInfos is not null-----");
645         size_t index = 0;
646         for (const auto &item : abilityInfos) {
647             APP_LOGI("name{%s} ", item.name.c_str());
648             napi_value objAbilityInfo = nullptr;
649             napi_create_object(env, &objAbilityInfo);
650             ConvertAbilityInfo(env, objAbilityInfo, item);
651             napi_set_element(env, result, index, objAbilityInfo);
652             index++;
653         }
654     } else {
655         APP_LOGI("-----abilityInfos is null-----");
656     }
657 }
658 
ConvertHapModuleInfo(napi_env env,napi_value objHapModuleInfo,const HapModuleInfo & hapModuleInfo)659 static void ConvertHapModuleInfo(napi_env env, napi_value objHapModuleInfo, const HapModuleInfo &hapModuleInfo)
660 {
661     napi_value nName;
662     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, hapModuleInfo.name.c_str(), NAPI_AUTO_LENGTH, &nName));
663     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "name", nName));
664 
665     napi_value nModuleName;
666     NAPI_CALL_RETURN_VOID(
667         env, napi_create_string_utf8(env, hapModuleInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &nModuleName));
668     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "moduleName", nModuleName));
669 
670     napi_value nDescription;
671     NAPI_CALL_RETURN_VOID(
672         env, napi_create_string_utf8(env, hapModuleInfo.description.c_str(), NAPI_AUTO_LENGTH, &nDescription));
673     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "description", nDescription));
674 
675     napi_value ndescriptionId;
676     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, hapModuleInfo.descriptionId, &ndescriptionId));
677     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "descriptionId", ndescriptionId));
678 
679     napi_value nIcon;
680     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, hapModuleInfo.iconPath.c_str(), NAPI_AUTO_LENGTH, &nIcon));
681     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "icon", nIcon));
682 
683     napi_value nLabel;
684     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, hapModuleInfo.label.c_str(), NAPI_AUTO_LENGTH, &nLabel));
685     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "label", nLabel));
686 
687     napi_value nHashValue;
688     NAPI_CALL_RETURN_VOID(
689         env, napi_create_string_utf8(env, hapModuleInfo.hashValue.c_str(), NAPI_AUTO_LENGTH, &nHashValue));
690     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "hashValue", nHashValue));
691 
692     napi_value nLabelId;
693     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, hapModuleInfo.labelId, &nLabelId));
694     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "labelId", nLabelId));
695 
696     napi_value nIconId;
697     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, hapModuleInfo.iconId, &nIconId));
698     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "iconId", nIconId));
699 
700     napi_value nBackgroundImg;
701     NAPI_CALL_RETURN_VOID(
702         env, napi_create_string_utf8(env, hapModuleInfo.backgroundImg.c_str(), NAPI_AUTO_LENGTH, &nBackgroundImg));
703     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "backgroundImg", nBackgroundImg));
704 
705     napi_value nSupportedModes;
706     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, hapModuleInfo.supportedModes, &nSupportedModes));
707     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "supportedModes", nSupportedModes));
708 
709     napi_value nReqCapabilities;
710     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nReqCapabilities));
711     for (size_t idx = 0; idx < hapModuleInfo.reqCapabilities.size(); idx++) {
712         napi_value nReqCapabilitie;
713         NAPI_CALL_RETURN_VOID(env,
714             napi_create_string_utf8(
715                 env, hapModuleInfo.reqCapabilities[idx].c_str(), NAPI_AUTO_LENGTH, &nReqCapabilitie));
716         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nReqCapabilities, idx, nReqCapabilitie));
717     }
718     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "reqCapabilities", nReqCapabilities));
719 
720     napi_value nDeviceTypes;
721     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nDeviceTypes));
722     for (size_t idx = 0; idx < hapModuleInfo.deviceTypes.size(); idx++) {
723         napi_value nDeviceType;
724         NAPI_CALL_RETURN_VOID(
725             env, napi_create_string_utf8(env, hapModuleInfo.deviceTypes[idx].c_str(), NAPI_AUTO_LENGTH, &nDeviceType));
726         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nDeviceTypes, idx, nDeviceType));
727     }
728     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "deviceTypes", nDeviceTypes));
729 
730     napi_value nAbilityInfos;
731     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nAbilityInfos));
732     for (size_t idx = 0; idx < hapModuleInfo.abilityInfos.size(); idx++) {
733         napi_value objAbilityInfo;
734         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objAbilityInfo));
735         ConvertAbilityInfo(env, objAbilityInfo, hapModuleInfo.abilityInfos[idx]);
736         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nAbilityInfos, idx, objAbilityInfo));
737     }
738     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "abilityInfo", nAbilityInfos));
739 
740     napi_value nMainAbilityName;
741     NAPI_CALL_RETURN_VOID(
742         env, napi_create_string_utf8(env, hapModuleInfo.mainAbility.c_str(), NAPI_AUTO_LENGTH, &nMainAbilityName));
743     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "mainAbilityName", nMainAbilityName));
744 
745     napi_value nInstallationFree;
746     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, hapModuleInfo.installationFree, &nInstallationFree));
747     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "installationFree", nInstallationFree));
748 
749     napi_value nMainElementName;
750     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, hapModuleInfo.mainElementName.c_str(), NAPI_AUTO_LENGTH,
751         &nMainElementName));
752     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "mainElementName", nMainElementName));
753 
754     napi_value nMetadata;
755     size_t size = hapModuleInfo.metadata.size();
756     NAPI_CALL_RETURN_VOID(env, napi_create_array_with_length(env, size, &nMetadata));
757     for (size_t index = 0; index < size; ++index) {
758         napi_value innerMeta;
759         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &innerMeta));
760         ConvertInnerMetadata(env, innerMeta, hapModuleInfo.metadata[index]);
761         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nMetadata, index, innerMeta));
762     }
763     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "metadata", nMetadata));
764 }
765 
ConvertRequestPermissionUsedScene(napi_env env,napi_value result,const RequestPermissionUsedScene & requestPermissionUsedScene)766 static void ConvertRequestPermissionUsedScene(napi_env env, napi_value result,
767     const RequestPermissionUsedScene &requestPermissionUsedScene)
768 {
769     napi_value nAbilities;
770     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nAbilities));
771     for (size_t idx = 0; idx < requestPermissionUsedScene.abilities.size(); idx++) {
772         napi_value objAbility;
773         NAPI_CALL_RETURN_VOID(env,
774             napi_create_string_utf8(env, requestPermissionUsedScene.abilities[idx].c_str(),
775                                     NAPI_AUTO_LENGTH, &objAbility));
776         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nAbilities, idx, objAbility));
777     }
778     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, "abilities", nAbilities));
779 
780     napi_value nWhen;
781     NAPI_CALL_RETURN_VOID(env,
782         napi_create_string_utf8(env, requestPermissionUsedScene.when.c_str(), NAPI_AUTO_LENGTH, &nWhen));
783     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, "when", nWhen));
784 }
785 
ConvertRequestPermission(napi_env env,napi_value result,const RequestPermission & requestPermission)786 static void ConvertRequestPermission(napi_env env, napi_value result, const RequestPermission &requestPermission)
787 {
788     napi_value nPermissionName;
789     NAPI_CALL_RETURN_VOID(
790         env, napi_create_string_utf8(env, requestPermission.name.c_str(), NAPI_AUTO_LENGTH, &nPermissionName));
791     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, "name", nPermissionName));
792 
793     napi_value nReason;
794     NAPI_CALL_RETURN_VOID(
795         env, napi_create_string_utf8(env, requestPermission.reason.c_str(), NAPI_AUTO_LENGTH, &nReason));
796     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, "reason", nReason));
797 
798     napi_value nReasonId;
799     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, requestPermission.reasonId, &nReasonId));
800     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, "reasonId", nReasonId));
801 
802     napi_value nUsedScene;
803     NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nUsedScene));
804     ConvertRequestPermissionUsedScene(env, nUsedScene, requestPermission.usedScene);
805     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, "usedScene", nUsedScene));
806 }
807 
ConvertBundleInfo(napi_env env,napi_value objBundleInfo,const BundleInfo & bundleInfo)808 static void ConvertBundleInfo(napi_env env, napi_value objBundleInfo, const BundleInfo &bundleInfo)
809 {
810     napi_value nName;
811     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, bundleInfo.name.c_str(), NAPI_AUTO_LENGTH, &nName));
812     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "name", nName));
813 
814     napi_value nVendor;
815     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, bundleInfo.vendor.c_str(), NAPI_AUTO_LENGTH, &nVendor));
816     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "vendor", nVendor));
817 
818     napi_value nVersionCode;
819     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, bundleInfo.versionCode, &nVersionCode));
820     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "versionCode", nVersionCode));
821 
822     napi_value nVersionName;
823     NAPI_CALL_RETURN_VOID(
824         env, napi_create_string_utf8(env, bundleInfo.versionName.c_str(), NAPI_AUTO_LENGTH, &nVersionName));
825     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "versionName", nVersionName));
826 
827     napi_value nCpuAbi;
828     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, bundleInfo.cpuAbi.c_str(), NAPI_AUTO_LENGTH, &nCpuAbi));
829     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "cpuAbi", nCpuAbi));
830 
831     napi_value nAppId;
832     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, bundleInfo.appId.c_str(), NAPI_AUTO_LENGTH, &nAppId));
833     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "appId", nAppId));
834 
835     napi_value nEntryModuleName;
836     NAPI_CALL_RETURN_VOID(
837         env, napi_create_string_utf8(env, bundleInfo.entryModuleName.c_str(), NAPI_AUTO_LENGTH, &nEntryModuleName));
838     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "entryModuleName", nEntryModuleName));
839 
840     napi_value nCompatibleVersion;
841     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, bundleInfo.compatibleVersion, &nCompatibleVersion));
842     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "compatibleVersion", nCompatibleVersion));
843 
844     napi_value nTargetVersion;
845     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, bundleInfo.targetVersion, &nTargetVersion));
846     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "targetVersion", nTargetVersion));
847 
848     napi_value nUid;
849     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, bundleInfo.uid, &nUid));
850     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "uid", nUid));
851 
852     napi_value nInstallTime;
853     NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, bundleInfo.installTime, &nInstallTime));
854     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "installTime", nInstallTime));
855 
856     napi_value nUpdateTime;
857     NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, bundleInfo.updateTime, &nUpdateTime));
858     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "updateTime", nUpdateTime));
859 
860     napi_value nAppInfo;
861     NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nAppInfo));
862     ConvertApplicationInfo(env, nAppInfo, bundleInfo.applicationInfo);
863     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "appInfo", nAppInfo));
864 
865     napi_value nAbilityInfos;
866     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nAbilityInfos));
867     for (size_t idx = 0; idx < bundleInfo.abilityInfos.size(); idx++) {
868         napi_value objAbilityInfo;
869         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objAbilityInfo));
870         ConvertAbilityInfo(env, objAbilityInfo, bundleInfo.abilityInfos[idx]);
871         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nAbilityInfos, idx, objAbilityInfo));
872     }
873     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "abilityInfos", nAbilityInfos));
874 
875     napi_value nHapModuleInfos;
876     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nHapModuleInfos));
877     for (size_t idx = 0; idx < bundleInfo.hapModuleInfos.size(); idx++) {
878         napi_value objHapModuleInfo;
879         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objHapModuleInfo));
880         ConvertHapModuleInfo(env, objHapModuleInfo, bundleInfo.hapModuleInfos[idx]);
881         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nHapModuleInfos, idx, objHapModuleInfo));
882     }
883     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "hapModuleInfos", nHapModuleInfos));
884 
885     napi_value nReqPermissions;
886     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nReqPermissions));
887     for (size_t idx = 0; idx < bundleInfo.reqPermissions.size(); idx++) {
888         napi_value nReqPermission;
889         NAPI_CALL_RETURN_VOID(env,
890             napi_create_string_utf8(env, bundleInfo.reqPermissions[idx].c_str(), NAPI_AUTO_LENGTH, &nReqPermission));
891         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nReqPermissions, idx, nReqPermission));
892     }
893     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "reqPermissions", nReqPermissions));
894 
895     napi_value nReqPermissionStates;
896     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nReqPermissionStates));
897     for (size_t idx = 0; idx < bundleInfo.reqPermissionStates.size(); idx++) {
898         napi_value nReqPermissionState;
899         NAPI_CALL_RETURN_VOID(env,
900             napi_create_int32(env, bundleInfo.reqPermissionStates[idx], &nReqPermissionState));
901         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nReqPermissionStates, idx, nReqPermissionState));
902     }
903     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "reqPermissionStates",
904         nReqPermissionStates));
905 
906     napi_value nIsCompressNativeLibs;
907     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, bundleInfo.applicationInfo.isCompressNativeLibs,
908         &nIsCompressNativeLibs));
909     NAPI_CALL_RETURN_VOID(
910         env, napi_set_named_property(env, objBundleInfo, "isCompressNativeLibs", nIsCompressNativeLibs));
911 
912     napi_value nIsSilentInstallation;
913     NAPI_CALL_RETURN_VOID(
914         env, napi_create_string_utf8(env, std::string().c_str(), NAPI_AUTO_LENGTH, &nIsSilentInstallation));
915     NAPI_CALL_RETURN_VOID(
916         env, napi_set_named_property(env, objBundleInfo, "isSilentInstallation", nIsSilentInstallation));
917 
918     napi_value nType;
919     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, std::string().c_str(), NAPI_AUTO_LENGTH, &nType));
920     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "type", nType));
921 
922     napi_value nReqPermissionDetails;
923     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nReqPermissionDetails));
924     for (size_t idx = 0; idx < bundleInfo.reqPermissionDetails.size(); idx++) {
925         napi_value objReqPermission;
926         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objReqPermission));
927         ConvertRequestPermission(env, objReqPermission, bundleInfo.reqPermissionDetails[idx]);
928         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nReqPermissionDetails, idx, objReqPermission));
929     }
930     NAPI_CALL_RETURN_VOID(
931         env, napi_set_named_property(env, objBundleInfo, "reqPermissionDetails", nReqPermissionDetails));
932 
933     napi_value nMinCompatibleVersionCode;
934     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, bundleInfo.minCompatibleVersionCode, &nMinCompatibleVersionCode));
935     NAPI_CALL_RETURN_VOID(
936         env, napi_set_named_property(env, objBundleInfo, "minCompatibleVersionCode", nMinCompatibleVersionCode));
937 
938     napi_value nEntryInstallationFree;
939     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, bundleInfo.entryInstallationFree, &nEntryInstallationFree));
940     NAPI_CALL_RETURN_VOID(
941         env, napi_set_named_property(env, objBundleInfo, "entryInstallationFree", nEntryInstallationFree));
942 }
943 
ConvertFormCustomizeData(napi_env env,napi_value objformInfo,const FormCustomizeData & customizeData)944 static void ConvertFormCustomizeData(napi_env env, napi_value objformInfo, const FormCustomizeData &customizeData)
945 {
946     napi_value nName;
947     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, customizeData.name.c_str(), NAPI_AUTO_LENGTH, &nName));
948     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "name", nName));
949     napi_value nValue;
950     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, customizeData.value.c_str(), NAPI_AUTO_LENGTH, &nValue));
951     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "value", nValue));
952 }
953 
ConvertFormWindow(napi_env env,napi_value objWindowInfo,const FormWindow & formWindow)954 static void ConvertFormWindow(napi_env env, napi_value objWindowInfo, const FormWindow &formWindow)
955 {
956     napi_value nDesignWidth;
957     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, formWindow.designWidth, &nDesignWidth));
958     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objWindowInfo, "designWidth", nDesignWidth));
959     napi_value nAutoDesignWidth;
960     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, formWindow.autoDesignWidth, &nAutoDesignWidth));
961     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objWindowInfo, "autoDesignWidth", nAutoDesignWidth));
962 }
963 
ConvertFormInfo(napi_env env,napi_value objformInfo,const FormInfo & formInfo)964 static void ConvertFormInfo(napi_env env, napi_value objformInfo, const FormInfo &formInfo)
965 {
966     napi_value nName;
967     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, formInfo.name.c_str(), NAPI_AUTO_LENGTH, &nName));
968     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "name", nName));
969     APP_LOGI("ConvertFormInfo name=%{public}s.", formInfo.name.c_str());
970 
971     napi_value nDescription;
972     NAPI_CALL_RETURN_VOID(
973         env, napi_create_string_utf8(env, formInfo.description.c_str(), NAPI_AUTO_LENGTH, &nDescription));
974     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "description", nDescription));
975 
976     napi_value nDescriptionId;
977     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, formInfo.descriptionId, &nDescriptionId));
978     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "descriptionId", nDescriptionId));
979 
980     napi_value nBundleName;
981     NAPI_CALL_RETURN_VOID(
982         env, napi_create_string_utf8(env, formInfo.bundleName.c_str(), NAPI_AUTO_LENGTH, &nBundleName));
983     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "bundleName", nBundleName));
984 
985     napi_value nModuleName;
986     NAPI_CALL_RETURN_VOID(
987         env, napi_create_string_utf8(env, formInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &nModuleName));
988     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "moduleName", nModuleName));
989 
990     napi_value nAbilityName;
991     NAPI_CALL_RETURN_VOID(
992         env, napi_create_string_utf8(env, formInfo.abilityName.c_str(), NAPI_AUTO_LENGTH, &nAbilityName));
993     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "abilityName", nAbilityName));
994 
995     napi_value nRelatedBundleName;
996     NAPI_CALL_RETURN_VOID(
997         env, napi_create_string_utf8(env, formInfo.relatedBundleName.c_str(), NAPI_AUTO_LENGTH, &nRelatedBundleName));
998     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "relatedBundleName", nRelatedBundleName));
999 
1000     napi_value nDefaultFlag;
1001     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, formInfo.defaultFlag, &nDefaultFlag));
1002     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "defaultFlag", nDefaultFlag));
1003 
1004     napi_value nFormVisibleNotify;
1005     NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, formInfo.formVisibleNotify, &nFormVisibleNotify));
1006     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "formVisibleNotify", nFormVisibleNotify));
1007 
1008     napi_value nFormConfigAbility;
1009     NAPI_CALL_RETURN_VOID(
1010         env, napi_create_string_utf8(env, formInfo.formConfigAbility.c_str(), NAPI_AUTO_LENGTH, &nFormConfigAbility));
1011     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "formConfigAbility", nFormConfigAbility));
1012 
1013     napi_value nType;
1014     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast<int32_t>(formInfo.type), &nType));
1015     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "type", nType));
1016 
1017     napi_value nColorMode;
1018     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast<int32_t>(formInfo.colorMode), &nColorMode));
1019     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "colorMode", nColorMode));
1020 
1021     napi_value nSupportDimensions;
1022     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nSupportDimensions));
1023     for (size_t idx = 0; idx < formInfo.supportDimensions.size(); idx++) {
1024         napi_value nSupportDimension;
1025         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, formInfo.supportDimensions[idx], &nSupportDimension));
1026         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nSupportDimensions, idx, nSupportDimension));
1027     }
1028     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "supportDimensions", nSupportDimensions));
1029 
1030     napi_value nDefaultDimension;
1031     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, formInfo.defaultDimension, &nDefaultDimension));
1032     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "defaultDimension", nDefaultDimension));
1033 
1034     napi_value nJsComponentName;
1035     NAPI_CALL_RETURN_VOID(
1036         env, napi_create_string_utf8(env, formInfo.jsComponentName.c_str(), NAPI_AUTO_LENGTH, &nJsComponentName));
1037     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "jsComponentName", nJsComponentName));
1038 
1039     napi_value nUpdateDuration;
1040     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, formInfo.updateDuration, &nUpdateDuration));
1041     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "updateDuration", nUpdateDuration));
1042 
1043     napi_value nCustomizeDatas;
1044     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nCustomizeDatas));
1045     for (size_t idx = 0; idx < formInfo.customizeDatas.size(); idx++) {
1046         napi_value nCustomizeData;
1047         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nCustomizeData));
1048         ConvertFormCustomizeData(env, nCustomizeData, formInfo.customizeDatas[idx]);
1049         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nCustomizeDatas, idx, nCustomizeData));
1050     }
1051     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "customizeDatas", nCustomizeDatas));
1052 
1053     napi_value nSrc;
1054     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, formInfo.src.c_str(), NAPI_AUTO_LENGTH, &nSrc));
1055     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "src", nSrc));
1056     APP_LOGI("ConvertFormInfo src=%{public}s.", formInfo.src.c_str());
1057 
1058     napi_value nWindow;
1059     NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &nWindow));
1060     ConvertFormWindow(env, nWindow, formInfo.window);
1061     APP_LOGI("ConvertFormInfo window.designWidth=%{public}d.", formInfo.window.designWidth);
1062     APP_LOGI("ConvertFormInfo window.autoDesignWidth=%{public}d.", formInfo.window.autoDesignWidth);
1063     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objformInfo, "window", nWindow));
1064 }
1065 
GetStringFromNAPI(napi_env env,napi_value value)1066 static std::string GetStringFromNAPI(napi_env env, napi_value value)
1067 {
1068     napi_valuetype valueType = napi_undefined;
1069     napi_typeof(env, value, &valueType);
1070     if (valueType != napi_string) {
1071         return "";
1072     }
1073     std::string result;
1074     size_t size = 0;
1075 
1076     if (napi_get_value_string_utf8(env, value, nullptr, NAPI_RETURN_ZERO, &size) != napi_ok) {
1077         return "";
1078     }
1079     result.reserve(size + NAPI_RETURN_ONE);
1080     result.resize(size);
1081     if (napi_get_value_string_utf8(env, value, result.data(), (size + NAPI_RETURN_ONE), &size) != napi_ok) {
1082         return "";
1083     }
1084     return result;
1085 }
1086 
ParseInt(napi_env env,int & param,napi_value args)1087 static napi_value ParseInt(napi_env env, int &param, napi_value args)
1088 {
1089     napi_valuetype valuetype = napi_undefined;
1090     NAPI_CALL(env, napi_typeof(env, args, &valuetype));
1091     APP_LOGD("valuetype=%{public}d.", valuetype);
1092     NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. int32 expected.");
1093     int32_t value = 0;
1094     napi_get_value_int32(env, args, &value);
1095     APP_LOGD("param=%{public}d.", value);
1096     param = value;
1097     // create result code
1098     napi_value result = nullptr;
1099     napi_status status = napi_create_int32(env, NAPI_RETURN_ONE, &result);
1100     NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!");
1101     return result;
1102 }
1103 
GetCallbackErrorValue(napi_env env,int errCode)1104 static napi_value GetCallbackErrorValue(napi_env env, int errCode)
1105 {
1106     napi_value result = nullptr;
1107     napi_value eCode = nullptr;
1108     NAPI_CALL(env, napi_create_int32(env, errCode, &eCode));
1109     NAPI_CALL(env, napi_create_object(env, &result));
1110     NAPI_CALL(env, napi_set_named_property(env, result, "code", eCode));
1111     return result;
1112 }
1113 
InnerGetApplicationInfos(napi_env env,int32_t flags,const int userId,std::vector<OHOS::AppExecFwk::ApplicationInfo> & appInfos)1114 static bool InnerGetApplicationInfos(napi_env env, int32_t flags, const int userId,
1115     std::vector<OHOS::AppExecFwk::ApplicationInfo> &appInfos)
1116 {
1117     auto iBundleMgr = GetBundleMgr();
1118     if (iBundleMgr == nullptr) {
1119         APP_LOGE("can not get iBundleMgr");
1120         return false;
1121     }
1122     return iBundleMgr->GetApplicationInfos(flags, userId, appInfos);
1123 }
1124 
ProcessApplicationInfos(napi_env env,napi_value result,const std::vector<OHOS::AppExecFwk::ApplicationInfo> & appInfos)1125 static void ProcessApplicationInfos(
1126     napi_env env, napi_value result, const std::vector<OHOS::AppExecFwk::ApplicationInfo> &appInfos)
1127 {
1128     if (appInfos.size() > 0) {
1129         APP_LOGI("-----appInfos is not null-----");
1130         size_t index = 0;
1131         for (const auto &item : appInfos) {
1132             APP_LOGI("name{%s} ", item.name.c_str());
1133             APP_LOGI("bundleName{%s} ", item.bundleName.c_str());
1134             for (const auto &moduleInfo : item.moduleInfos) {
1135                 APP_LOGI("moduleName{%s} ", moduleInfo.moduleName.c_str());
1136                 APP_LOGI("bundleName{%s} ", moduleInfo.moduleSourceDir.c_str());
1137             }
1138             napi_value objAppInfo;
1139             NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objAppInfo));
1140             ConvertApplicationInfo(env, objAppInfo, item);
1141             NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, objAppInfo));
1142             index++;
1143         }
1144     } else {
1145         APP_LOGI("-----appInfos is null-----");
1146     }
1147 }
1148 /**
1149  * Promise and async callback
1150  */
GetApplicationInfos(napi_env env,napi_callback_info info)1151 napi_value GetApplicationInfos(napi_env env, napi_callback_info info)
1152 {
1153     APP_LOGD("NAPI_GetApplicationInfos called");
1154     size_t argc = ARGS_SIZE_THREE;
1155     napi_value argv[ARGS_SIZE_THREE] = {nullptr};
1156     napi_value thisArg = nullptr;
1157     void *data = nullptr;
1158     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data));
1159     APP_LOGI("argc = [%{public}zu]", argc);
1160     AsyncApplicationInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncApplicationInfosCallbackInfo(env);
1161     if (asyncCallbackInfo == nullptr) {
1162         return nullptr;
1163     }
1164     std::unique_ptr<AsyncApplicationInfosCallbackInfo> callbackPtr {asyncCallbackInfo};
1165     for (size_t i = 0; i < argc; ++i) {
1166         napi_valuetype valueType = napi_undefined;
1167         napi_typeof(env, argv[i], &valueType);
1168         if ((i == 0) && (valueType == napi_number)) {
1169             ParseInt(env, asyncCallbackInfo->flags, argv[i]);
1170             if (argc == ARGS_SIZE_ONE) {
1171                 asyncCallbackInfo->userId = IPCSkeleton::GetCallingUid() / Constants::BASE_USER_RANGE;
1172             }
1173         } else if ((i == ARGS_SIZE_ONE) && (valueType == napi_number)) {
1174             ParseInt(env, asyncCallbackInfo->userId, argv[i]);
1175         } else if ((i == ARGS_SIZE_ONE) && (valueType == napi_function)) {
1176             asyncCallbackInfo->userId = IPCSkeleton::GetCallingUid() / Constants::BASE_USER_RANGE;
1177             NAPI_CALL(env, napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
1178         } else if ((i == ARGS_SIZE_TWO) && (valueType == napi_function)) {
1179             NAPI_CALL(env, napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
1180             break;
1181         } else {
1182             asyncCallbackInfo->err = PARAM_TYPE_ERROR;
1183             asyncCallbackInfo->message = "type mismatch";
1184         }
1185     }
1186 
1187     if (argc == 0) {
1188         asyncCallbackInfo->err = PARAM_TYPE_ERROR;
1189         asyncCallbackInfo->message = "type mismatch";
1190     }
1191 
1192     napi_value promise = nullptr;
1193     if (asyncCallbackInfo->callback == nullptr) {
1194         NAPI_CALL(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise));
1195     } else {
1196         NAPI_CALL(env, napi_get_undefined(env,  &promise));
1197     }
1198 
1199     napi_value resource = nullptr;
1200     NAPI_CALL(env, napi_create_string_utf8(env, "GetApplicationInfo", NAPI_AUTO_LENGTH, &resource));
1201 
1202     NAPI_CALL(env, napi_create_async_work(
1203         env, nullptr, resource,
1204         [](napi_env env, void* data) {
1205             AsyncApplicationInfosCallbackInfo* asyncCallbackInfo =
1206                 reinterpret_cast<AsyncApplicationInfosCallbackInfo*>(data);
1207             if (!asyncCallbackInfo->err) {
1208                 asyncCallbackInfo->ret = InnerGetApplicationInfos(asyncCallbackInfo->env,
1209                                                                   asyncCallbackInfo->flags,
1210                                                                   asyncCallbackInfo->userId,
1211                                                                   asyncCallbackInfo->appInfos);
1212             }
1213         },
1214         [](napi_env env, napi_status status, void* data) {
1215             AsyncApplicationInfosCallbackInfo* asyncCallbackInfo =
1216                 reinterpret_cast<AsyncApplicationInfosCallbackInfo*>(data);
1217             std::unique_ptr<AsyncApplicationInfosCallbackInfo> callbackPtr {asyncCallbackInfo};
1218             napi_value result[2] = { 0 };
1219             if (asyncCallbackInfo->err) {
1220                 NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, static_cast<uint32_t>(asyncCallbackInfo->err),
1221                     &result[0]));
1222                 NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, asyncCallbackInfo->message.c_str(),
1223                     NAPI_AUTO_LENGTH, &result[1]));
1224             } else {
1225                 if (asyncCallbackInfo->ret) {
1226                     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, 0, &result[0]));
1227                     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result[1]));
1228                     ProcessApplicationInfos(env, result[1], asyncCallbackInfo->appInfos);
1229                 } else {
1230                     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 1, &result[0]));
1231                     NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &result[1]));
1232                 }
1233             }
1234             if (asyncCallbackInfo->deferred) {
1235               if (asyncCallbackInfo->ret) {
1236                   NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]));
1237               } else {
1238                   NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]));
1239               }
1240             } else {
1241                 napi_value callback = nullptr;
1242                 napi_value placeHolder = nullptr;
1243                 NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callback, &callback));
1244                 NAPI_CALL_RETURN_VOID(env, napi_call_function(env, nullptr, callback,
1245                     sizeof(result) / sizeof(result[0]), result, &placeHolder));
1246             }
1247         },
1248         reinterpret_cast<void*>(asyncCallbackInfo), &asyncCallbackInfo->asyncWork));
1249     NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
1250     callbackPtr.release();
1251     return promise;
1252 }
1253 
ParseStringArray(napi_env env,std::vector<std::string> & stringArray,napi_value args)1254 static napi_value ParseStringArray(napi_env env, std::vector<std::string> &stringArray, napi_value args)
1255 {
1256     APP_LOGD("begin to parse string array");
1257     bool isArray = false;
1258     NAPI_CALL(env, napi_is_array(env, args, &isArray));
1259     if (!isArray) {
1260         APP_LOGE("args not array");
1261         return nullptr;
1262     }
1263     uint32_t arrayLength = 0;
1264     NAPI_CALL(env, napi_get_array_length(env, args, &arrayLength));
1265     APP_LOGD("length=%{public}ud", arrayLength);
1266     for (uint32_t j = 0; j < arrayLength; j++) {
1267         napi_value value = nullptr;
1268         NAPI_CALL(env, napi_get_element(env, args, j, &value));
1269         napi_valuetype valueType = napi_undefined;
1270         NAPI_CALL(env, napi_typeof(env, value, &valueType));
1271         if (valueType != napi_string) {
1272             APP_LOGE("array inside not string type");
1273             stringArray.clear();
1274             return nullptr;
1275         }
1276         stringArray.push_back(GetStringFromNAPI(env, value));
1277     }
1278     // create result code
1279     napi_value result;
1280     napi_status status;
1281     status = napi_create_int32(env, NAPI_RETURN_ONE, &result);
1282     NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!");
1283     return result;
1284 }
1285 
1286 // QueryAbilityInfos(want)
InnerQueryAbilityInfos(napi_env env,const Want & want,int32_t flags,int32_t userId,std::vector<AbilityInfo> & abilityInfos)1287 static bool InnerQueryAbilityInfos(napi_env env, const Want &want,
1288     int32_t flags, int32_t userId, std::vector<AbilityInfo> &abilityInfos)
1289 {
1290     auto iBundleMgr = GetBundleMgr();
1291     if (iBundleMgr == nullptr) {
1292         APP_LOGE("can not get iBundleMgr");
1293         return false;
1294     }
1295     return iBundleMgr->QueryAbilityInfos(want, flags, userId, abilityInfos);
1296 }
1297 
ParseBundleOptions(napi_env env,BundleOptions & bundleOptions,napi_value args)1298 static bool ParseBundleOptions(napi_env env, BundleOptions &bundleOptions, napi_value args)
1299 {
1300     APP_LOGD("begin to parse bundleOptions");
1301     napi_valuetype valueType;
1302     NAPI_CALL_BASE(env, napi_typeof(env, args, &valueType), false);
1303     if (valueType != napi_object) {
1304         APP_LOGE("args not object type");
1305         return false;
1306     }
1307 
1308     napi_value prop = nullptr;
1309     napi_get_named_property(env, args, "userId", &prop);
1310     napi_typeof(env, prop, &valueType);
1311     if (valueType == napi_number) {
1312         napi_get_value_int32(env, prop, &bundleOptions.userId);
1313     }
1314     return true;
1315 }
1316 
ParseWant(napi_env env,Want & want,napi_value args)1317 static bool ParseWant(napi_env env, Want &want, napi_value args)
1318 {
1319     APP_LOGD("begin to parse want");
1320     napi_valuetype valueType;
1321     NAPI_CALL_BASE(env, napi_typeof(env, args, &valueType), false);
1322     if (valueType != napi_object) {
1323         APP_LOGE("args not object type");
1324         return false;
1325     }
1326     int32_t wantFlags = 0;
1327     std::vector<std::string> wantEntities;
1328     std::string elementUri;
1329     std::string elementDeviceId;
1330     std::string elementBundleName;
1331     std::string elementModuleName;
1332     std::string elementAbilityName;
1333 
1334     napi_value prop = nullptr;
1335     napi_get_named_property(env, args, "bundleName", &prop);
1336     std::string wantBundleName = GetStringFromNAPI(env, prop);
1337 
1338     prop = nullptr;
1339     napi_get_named_property(env, args, "moduleName", &prop);
1340     std::string wantModuleName = GetStringFromNAPI(env, prop);
1341 
1342     prop = nullptr;
1343     napi_get_named_property(env, args, "abilityName", &prop);
1344     std::string wantAbilityName = GetStringFromNAPI(env, prop);
1345 
1346     prop = nullptr;
1347     napi_get_named_property(env, args, "deviceId", &prop);
1348     std::string wantDeviceId = GetStringFromNAPI(env, prop);
1349 
1350     prop = nullptr;
1351     napi_get_named_property(env, args, "type", &prop);
1352     std::string wantType = GetStringFromNAPI(env, prop);
1353 
1354     prop = nullptr;
1355     napi_get_named_property(env, args, "flags", &prop);
1356     napi_typeof(env, prop, &valueType);
1357     if (valueType == napi_number) {
1358         napi_get_value_int32(env, prop, &wantFlags);
1359     }
1360 
1361     prop = nullptr;
1362     napi_get_named_property(env, args, "action", &prop);
1363     std::string wantAction = GetStringFromNAPI(env, prop);
1364 
1365     prop = nullptr;
1366     napi_get_named_property(env, args, "uri", &prop);
1367     std::string wantUri = GetStringFromNAPI(env, prop);
1368 
1369     prop = nullptr;
1370     napi_get_named_property(env, args, "entities", &prop);
1371     ParseStringArray(env, wantEntities, prop);
1372     for (size_t idx = 0; idx < wantEntities.size(); idx++) {
1373         APP_LOGD("entity:%{public}s", wantEntities[idx].c_str());
1374         want.AddEntity(wantEntities[idx]);
1375     }
1376 
1377     napi_value elementProp = nullptr;
1378     napi_get_named_property(env, args, "elementName", &elementProp);
1379     napi_typeof(env, elementProp, &valueType);
1380     if (valueType == napi_object) {
1381         APP_LOGD("begin to parse want elementName");
1382         prop = nullptr;
1383         napi_get_named_property(env, elementProp, "deviceId", &prop);
1384         elementDeviceId = GetStringFromNAPI(env, prop);
1385 
1386         prop = nullptr;
1387         napi_get_named_property(env, elementProp, "uri", &prop);
1388         elementUri = GetStringFromNAPI(env, prop);
1389 
1390         prop = nullptr;
1391         napi_status status = napi_get_named_property(env, elementProp, "bundleName", &prop);
1392         napi_typeof(env, prop, &valueType);
1393         if ((status != napi_ok) || (valueType != napi_string)) {
1394             APP_LOGE("elementName bundleName incorrect!");
1395             return false;
1396         }
1397         elementBundleName = GetStringFromNAPI(env, prop);
1398 
1399         prop = nullptr;
1400         status = napi_get_named_property(env, elementProp, "abilityName", &prop);
1401         napi_typeof(env, prop, &valueType);
1402         if ((status != napi_ok) || (valueType != napi_string)) {
1403             APP_LOGE("elementName abilityName incorrect!");
1404             return false;
1405         }
1406         elementAbilityName = GetStringFromNAPI(env, prop);
1407 
1408         prop = nullptr;
1409         bool hasKey = false;
1410         napi_has_named_property(env, elementProp, "moduleName", &hasKey);
1411         if (hasKey) {
1412             status = napi_get_named_property(env, elementProp, "moduleName", &prop);
1413             napi_typeof(env, prop, &valueType);
1414             if ((status != napi_ok) || (valueType != napi_string)) {
1415                 APP_LOGE("elementName moduleName incorrect!");
1416                 return false;
1417             }
1418             elementModuleName = GetStringFromNAPI(env, prop);
1419         }
1420     }
1421     if (elementBundleName.empty()) {
1422         elementBundleName = wantBundleName;
1423     }
1424     if (elementModuleName.empty()) {
1425         elementModuleName = wantModuleName;
1426     }
1427     if (elementAbilityName.empty()) {
1428         elementAbilityName = wantAbilityName;
1429     }
1430     if (elementDeviceId.empty()) {
1431         elementDeviceId = wantDeviceId;
1432     }
1433     if (elementUri.empty()) {
1434         elementUri = wantUri;
1435     }
1436     APP_LOGD("bundleName:%{public}s, moduleName: %{public}s, abilityName:%{public}s",
1437              elementBundleName.c_str(), elementModuleName.c_str(), elementAbilityName.c_str());
1438     APP_LOGD("action:%{public}s, uri:%{private}s, type:%{public}s, flags:%{public}d",
1439         wantAction.c_str(), elementUri.c_str(), wantType.c_str(), wantFlags);
1440     want.SetAction(wantAction);
1441     want.SetUri(elementUri);
1442     want.SetType(wantType);
1443     want.SetFlags(wantFlags);
1444     ElementName elementName(elementDeviceId, elementBundleName, elementAbilityName, elementModuleName);
1445     want.SetElement(elementName);
1446     return true;
1447 }
1448 
1449 /**
1450  * Promise and async callback
1451  */
QueryAbilityInfos(napi_env env,napi_callback_info info)1452 napi_value QueryAbilityInfos(napi_env env, napi_callback_info info)
1453 {
1454     APP_LOGI("QueryAbilityInfos called");
1455     size_t argc = ARGS_SIZE_FOUR;
1456     napi_value argv[ARGS_SIZE_FOUR] = {nullptr};
1457     napi_value thisArg = nullptr;
1458     void *data = nullptr;
1459     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data));
1460     APP_LOGI("argc = [%{public}zu]", argc);
1461     Want want;
1462     AsyncAbilityInfoCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncAbilityInfoCallbackInfo(env);
1463     if (asyncCallbackInfo == nullptr) {
1464         return nullptr;
1465     }
1466     std::unique_ptr<AsyncAbilityInfoCallbackInfo> callbackPtr {asyncCallbackInfo};
1467     asyncCallbackInfo->want = want;
1468     asyncCallbackInfo->userId = IPCSkeleton::GetCallingUid() / Constants::BASE_USER_RANGE;
1469 
1470     for (size_t i = 0; i < argc; ++i) {
1471         napi_valuetype valueType = napi_undefined;
1472         napi_typeof(env, argv[i], &valueType);
1473         if ((i == 0) && (valueType == napi_object)) {
1474             bool ret = ParseWant(env, asyncCallbackInfo->want, argv[i]);
1475             if (!ret) {
1476                 asyncCallbackInfo->err = PARAM_TYPE_ERROR;
1477             }
1478         } else if ((i == ARGS_SIZE_ONE) && (valueType == napi_number)) {
1479             ParseInt(env, asyncCallbackInfo->flags, argv[i]);
1480         } else if (i == ARGS_SIZE_TWO) {
1481             if (valueType == napi_number) {
1482                 ParseInt(env, asyncCallbackInfo->userId, argv[i]);
1483             } else if (valueType == napi_function) {
1484                 NAPI_CALL(env, napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
1485                 break;
1486             } else {
1487                 asyncCallbackInfo->err = PARAM_TYPE_ERROR;
1488             }
1489         } else if ((i == ARGS_SIZE_THREE) && (valueType == napi_function)) {
1490             NAPI_CALL(env, napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
1491         } else {
1492             asyncCallbackInfo->err = PARAM_TYPE_ERROR;
1493         }
1494     }
1495     napi_value promise = nullptr;
1496     if (asyncCallbackInfo->callback == nullptr) {
1497         NAPI_CALL(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise));
1498     } else {
1499         NAPI_CALL(env, napi_get_undefined(env,  &promise));
1500     }
1501     napi_value resource = nullptr;
1502     NAPI_CALL(env, napi_create_string_utf8(env, "QueryAbilityInfos", NAPI_AUTO_LENGTH, &resource));
1503     NAPI_CALL(env, napi_create_async_work(
1504         env, nullptr, resource,
1505         [](napi_env env, void *data) {
1506             AsyncAbilityInfoCallbackInfo *asyncCallbackInfo =
1507                 reinterpret_cast<AsyncAbilityInfoCallbackInfo *>(data);
1508             if (!asyncCallbackInfo->err) {
1509                 {
1510                     std::lock_guard<std::mutex> lock(abilityInfoCacheMutex_);
1511                     auto item = abilityInfoCache.find(Query(asyncCallbackInfo->want.ToString(),
1512                         QUERY_ABILITY_BY_WANT, asyncCallbackInfo->flags, asyncCallbackInfo->userId, env));
1513                     if (item != abilityInfoCache.end()) {
1514                         APP_LOGD("has cache,no need to query from host");
1515                         asyncCallbackInfo->ret = true;
1516                         return;
1517                     }
1518                 }
1519                 asyncCallbackInfo->ret = InnerQueryAbilityInfos(env, asyncCallbackInfo->want, asyncCallbackInfo->flags,
1520                     asyncCallbackInfo->userId, asyncCallbackInfo->abilityInfos);
1521             }
1522         },
1523         [](napi_env env, napi_status status, void *data) {
1524             AsyncAbilityInfoCallbackInfo *asyncCallbackInfo =
1525                 reinterpret_cast<AsyncAbilityInfoCallbackInfo *>(data);
1526             std::unique_ptr<AsyncAbilityInfoCallbackInfo> callbackPtr {asyncCallbackInfo};
1527             napi_value result[2] = { 0 };
1528             if (asyncCallbackInfo->err) {
1529                 NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, static_cast<uint32_t>(asyncCallbackInfo->err),
1530                     &result[0]));
1531                 NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, "type mismatch",
1532                     NAPI_AUTO_LENGTH, &result[1]));
1533             } else {
1534                 if (asyncCallbackInfo->ret) {
1535                     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, 0, &result[0]));
1536                     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result[1]));
1537                     // get from cache first
1538                     std::lock_guard<std::mutex> lock(abilityInfoCacheMutex_);
1539                     Query query(asyncCallbackInfo->want.ToString(), QUERY_ABILITY_BY_WANT,
1540                         asyncCallbackInfo->flags, asyncCallbackInfo->userId, env);
1541                     auto item = abilityInfoCache.find(query);
1542                     if (item != abilityInfoCache.end()) {
1543                         APP_LOGD("get abilityInfo from cache");
1544                         NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, item->second, &result[1]));
1545                     } else {
1546                         ProcessAbilityInfos(env, result[1], asyncCallbackInfo->abilityInfos);
1547                         HandleAbilityInfoCache(env, query, asyncCallbackInfo, result[1]);
1548                     }
1549                 } else {
1550                     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, 1, &result[0]));
1551                     NAPI_CALL_RETURN_VOID(env,
1552                         napi_create_string_utf8(env, "QueryAbilityInfos failed", NAPI_AUTO_LENGTH, &result[1]));
1553                 }
1554             }
1555             if (asyncCallbackInfo->deferred) {
1556                 if (asyncCallbackInfo->ret) {
1557                     NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]));
1558                 } else {
1559                     NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]));
1560                 }
1561             } else {
1562                 napi_value callback = nullptr;
1563                 napi_value placeHolder = nullptr;
1564                 NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callback, &callback));
1565                 NAPI_CALL_RETURN_VOID(env, napi_call_function(env, nullptr, callback,
1566                     sizeof(result) / sizeof(result[0]), result, &placeHolder));
1567             }
1568         },
1569         reinterpret_cast<void*>(asyncCallbackInfo), &asyncCallbackInfo->asyncWork));
1570     NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
1571     callbackPtr.release();
1572     return promise;
1573 }
1574 
ParseString(napi_env env,std::string & param,napi_value args)1575 static napi_value ParseString(napi_env env, std::string &param, napi_value args)
1576 {
1577     napi_status status;
1578     napi_valuetype valuetype;
1579     NAPI_CALL(env, napi_typeof(env, args, &valuetype));
1580     NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected.");
1581     param = GetStringFromNAPI(env, args);
1582     APP_LOGD("param=%{public}s.", param.c_str());
1583     // create result code
1584     napi_value result;
1585     status = napi_create_int32(env, NAPI_RETURN_ONE, &result);
1586     NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!");
1587     return result;
1588 }
1589 
InnerGetBundleInfos(napi_env env,int32_t flags,int32_t userId,std::vector<OHOS::AppExecFwk::BundleInfo> & bundleInfos)1590 static bool InnerGetBundleInfos(
1591     napi_env env, int32_t flags, int32_t userId, std::vector<OHOS::AppExecFwk::BundleInfo> &bundleInfos)
1592 {
1593     auto iBundleMgr = GetBundleMgr();
1594     if (iBundleMgr == nullptr) {
1595         APP_LOGE("can not get iBundleMgr");
1596         return false;
1597     }
1598     return iBundleMgr->GetBundleInfos(flags, bundleInfos, userId);
1599 }
1600 
ProcessBundleInfos(napi_env env,napi_value result,const std::vector<OHOS::AppExecFwk::BundleInfo> & bundleInfos)1601 static void ProcessBundleInfos(
1602     napi_env env, napi_value result, const std::vector<OHOS::AppExecFwk::BundleInfo> &bundleInfos)
1603 {
1604     if (bundleInfos.size() > 0) {
1605         APP_LOGI("-----bundleInfos is not null-----");
1606         size_t index = 0;
1607         for (const auto &item : bundleInfos) {
1608             APP_LOGD("name{%s} ", item.name.c_str());
1609             APP_LOGD("bundleName{%s} ", item.applicationInfo.bundleName.c_str());
1610             for (const auto &moduleInfo : item.applicationInfo.moduleInfos) {
1611                 APP_LOGD("moduleName{%s} ", moduleInfo.moduleName.c_str());
1612                 APP_LOGD("moduleSourceDir{%s} ", moduleInfo.moduleSourceDir.c_str());
1613             }
1614             napi_value objBundleInfo = nullptr;
1615             napi_create_object(env, &objBundleInfo);
1616             ConvertBundleInfo(env, objBundleInfo, item);
1617             napi_set_element(env, result, index, objBundleInfo);
1618             index++;
1619         }
1620     } else {
1621         APP_LOGI("-----bundleInfos is null-----");
1622     }
1623 }
1624 /**
1625  * Promise and async callback
1626  */
GetBundleInfos(napi_env env,napi_callback_info info)1627 napi_value GetBundleInfos(napi_env env, napi_callback_info info)
1628 {
1629     APP_LOGD("NAPI GetBundleInfos called");
1630     size_t argc = ARGS_SIZE_THREE;
1631     napi_value argv[ARGS_SIZE_THREE] = {0};
1632     napi_value thisArg = nullptr;
1633     void *data = nullptr;
1634     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data));
1635     APP_LOGD("argc = [%{public}zu]", argc);
1636     AsyncBundleInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncBundleInfosCallbackInfo(env);
1637     if (asyncCallbackInfo == nullptr) {
1638         APP_LOGE("asyncCallbackInfo is nullptr");
1639         return nullptr;
1640     }
1641     std::unique_ptr<AsyncBundleInfosCallbackInfo> callbackPtr {asyncCallbackInfo};
1642     for (size_t i = 0; i < argc; ++i) {
1643         napi_valuetype valueType = napi_undefined;
1644         NAPI_CALL(env, napi_typeof(env, argv[i], &valueType));
1645         if ((i == PARAM0) && (valueType == napi_number)) {
1646             ParseInt(env, asyncCallbackInfo->flags, argv[i]);
1647         } else if ((i == PARAM1) && (valueType == napi_number)) {
1648             ParseInt(env, asyncCallbackInfo->userId, argv[i]);
1649         } else if ((i == PARAM1) && (valueType == napi_function)) {
1650             NAPI_CALL(env, napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
1651             break;
1652         } else if ((i == PARAM2) && (valueType == napi_function)) {
1653             NAPI_CALL(env, napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
1654             break;
1655         } else {
1656             asyncCallbackInfo->err = PARAM_TYPE_ERROR;
1657             asyncCallbackInfo->message = "type mismatch";
1658         }
1659     }
1660 
1661     napi_value promise = nullptr;
1662     if (asyncCallbackInfo->callback == nullptr) {
1663         NAPI_CALL(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise));
1664     } else {
1665         NAPI_CALL(env, napi_get_undefined(env,  &promise));
1666     }
1667 
1668     napi_value resource = nullptr;
1669     NAPI_CALL(env, napi_create_string_utf8(env, "GetBundleInfos", NAPI_AUTO_LENGTH, &resource));
1670 
1671     NAPI_CALL(env, napi_create_async_work(
1672         env, nullptr, resource,
1673         [](napi_env env, void* data) {
1674             AsyncBundleInfosCallbackInfo* asyncCallbackInfo = reinterpret_cast<AsyncBundleInfosCallbackInfo*>(data);
1675             if (!asyncCallbackInfo->err) {
1676                 asyncCallbackInfo->ret = InnerGetBundleInfos(
1677                     env, asyncCallbackInfo->flags, asyncCallbackInfo->userId, asyncCallbackInfo->bundleInfos);
1678             }
1679         },
1680         [](napi_env env, napi_status status, void* data) {
1681             AsyncBundleInfosCallbackInfo* asyncCallbackInfo = reinterpret_cast<AsyncBundleInfosCallbackInfo*>(data);
1682             std::unique_ptr<AsyncBundleInfosCallbackInfo> callbackPtr {asyncCallbackInfo};
1683             napi_value result[2] = { 0 };
1684             if (asyncCallbackInfo->err) {
1685                 NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, static_cast<uint32_t>(asyncCallbackInfo->err),
1686                     &result[0]));
1687                 NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, asyncCallbackInfo->message.c_str(),
1688                     NAPI_AUTO_LENGTH, &result[1]));
1689             } else {
1690                 if (asyncCallbackInfo->ret) {
1691                     NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, 0, &result[0]));
1692                     NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result[1]));
1693                     ProcessBundleInfos(env, result[1], asyncCallbackInfo->bundleInfos);
1694                 } else {
1695                     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 1, &result[0]));
1696                     NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &result[1]));
1697                 }
1698             }
1699             if (asyncCallbackInfo->deferred) {
1700               if (asyncCallbackInfo->ret) {
1701                   NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]));
1702               } else {
1703                   NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]));
1704               }
1705             } else {
1706                 napi_value callback = nullptr;
1707                 napi_value placeHolder = nullptr;
1708                 NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callback, &callback));
1709                 NAPI_CALL_RETURN_VOID(env, napi_call_function(env, nullptr, callback,
1710                     sizeof(result) / sizeof(result[0]), result, &placeHolder));
1711             }
1712         },
1713         reinterpret_cast<void*>(asyncCallbackInfo), &asyncCallbackInfo->asyncWork));
1714     NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
1715     callbackPtr.release();
1716     return promise;
1717 }
1718 
InnerGetPermissionDef(const std::string & permissionName,PermissionDef & permissionDef)1719 static bool InnerGetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef)
1720 {
1721     auto iBundleMgr = GetBundleMgr();
1722     if (iBundleMgr == nullptr) {
1723         APP_LOGE("can not get iBundleMgr");
1724         return false;
1725     };
1726     ErrCode ret = iBundleMgr->GetPermissionDef(permissionName, permissionDef);
1727     if (ret != NO_ERROR) {
1728         APP_LOGE("permissionName is not find");
1729         return false;
1730     }
1731     return true;
1732 }
1733 
VerifyCallingPermission(std::string permissionName)1734 static bool VerifyCallingPermission(std::string permissionName)
1735 {
1736     auto iBundleMgr = GetBundleMgr();
1737     if (iBundleMgr == nullptr) {
1738         APP_LOGE("can not get iBundleMgr");
1739         return false;
1740     }
1741     return iBundleMgr->VerifyCallingPermission(permissionName);
1742 }
1743 
VerifySystemApi()1744 static bool VerifySystemApi()
1745 {
1746     auto iBundleMgr = GetBundleMgr();
1747     if (iBundleMgr == nullptr) {
1748         APP_LOGE("can not get iBundleMgr");
1749         return false;
1750     }
1751     return iBundleMgr->VerifySystemApi();
1752 }
1753 
ParseHashParam(napi_env env,std::string & key,std::string & value,napi_value args)1754 static bool ParseHashParam(napi_env env, std::string &key, std::string &value, napi_value args)
1755 {
1756     napi_valuetype valueType;
1757     NAPI_CALL_BASE(env, napi_typeof(env, args, &valueType), false);
1758     if (valueType != napi_object) {
1759         APP_LOGE("args type incorrect!");
1760         return false;
1761     }
1762     napi_value property = nullptr;
1763     bool hasKey = false;
1764     napi_has_named_property(env, args, "moduleName", &hasKey);
1765     if (!hasKey) {
1766         APP_LOGE("parse HashParam failed due to moduleName is not exist!");
1767         return false;
1768     }
1769     napi_status status = napi_get_named_property(env, args, "moduleName", &property);
1770     if (status != napi_ok) {
1771         APP_LOGE("napi get named moduleName property error!");
1772         return false;
1773     }
1774     ParseString(env, key, property);
1775     if (key.empty()) {
1776         APP_LOGE("param string moduleName is empty.");
1777         return false;
1778     }
1779     APP_LOGD("ParseHashParam moduleName=%{public}s.", key.c_str());
1780 
1781     property = nullptr;
1782     hasKey = false;
1783     napi_has_named_property(env, args, "hashValue", &hasKey);
1784     if (!hasKey) {
1785         APP_LOGE("parse HashParam failed due to hashValue is not exist!");
1786         return false;
1787     }
1788     status = napi_get_named_property(env, args, "hashValue", &property);
1789     if (status != napi_ok) {
1790         APP_LOGE("napi get named hashValue property error!");
1791         return false;
1792     }
1793     ParseString(env, value, property);
1794     if (value.empty()) {
1795         APP_LOGE("param string hashValue is empty.");
1796         return false;
1797     }
1798     APP_LOGD("ParseHashParam hashValue=%{public}s.", value.c_str());
1799     return true;
1800 }
1801 
ParseHashParams(napi_env env,napi_value args,std::map<std::string,std::string> & hashParams)1802 static bool ParseHashParams(napi_env env, napi_value args, std::map<std::string, std::string> &hashParams)
1803 {
1804     bool hasKey = false;
1805     napi_has_named_property(env, args, "hashParams", &hasKey);
1806     if (hasKey) {
1807         napi_value property = nullptr;
1808         napi_status status = napi_get_named_property(env, args, "hashParams", &property);
1809         if (status != napi_ok) {
1810             APP_LOGE("napi get named hashParams property error!");
1811             return false;
1812         }
1813         bool isArray = false;
1814         uint32_t arrayLength = 0;
1815         napi_value valueAry = 0;
1816         napi_valuetype valueAryType = napi_undefined;
1817         NAPI_CALL_BASE(env, napi_is_array(env, property, &isArray), false);
1818         if (!isArray) {
1819             APP_LOGE("hashParams is not array!");
1820             return false;
1821         }
1822 
1823         NAPI_CALL_BASE(env, napi_get_array_length(env, property, &arrayLength), false);
1824         APP_LOGD("ParseHashParams property is array, length=%{public}ud", arrayLength);
1825         for (uint32_t j = 0; j < arrayLength; j++) {
1826             NAPI_CALL_BASE(env, napi_get_element(env, property, j, &valueAry), false);
1827             NAPI_CALL_BASE(env, napi_typeof(env, valueAry, &valueAryType), false);
1828             std::string key;
1829             std::string value;
1830             if (!ParseHashParam(env, key, value, valueAry)) {
1831                 APP_LOGD("parse hash param failed");
1832                 return false;
1833             }
1834             if (hashParams.find(key) != hashParams.end()) {
1835                 APP_LOGD("moduleName(%{public}s) is duplicate", key.c_str());
1836                 return false;
1837             }
1838             hashParams.emplace(key, value);
1839         }
1840     }
1841     return true;
1842 }
1843 
ParseUserId(napi_env env,napi_value args,int32_t & userId)1844 static bool ParseUserId(napi_env env, napi_value args, int32_t &userId)
1845 {
1846     bool hasKey = false;
1847     napi_has_named_property(env, args, "userId", &hasKey);
1848     if (hasKey) {
1849         napi_value property = nullptr;
1850         napi_status status = napi_get_named_property(env, args, "userId", &property);
1851         if (status != napi_ok) {
1852             APP_LOGE("napi get named userId property error!");
1853             return false;
1854         }
1855         napi_valuetype valueType;
1856         napi_typeof(env, property, &valueType);
1857         if (valueType != napi_number) {
1858             APP_LOGE("param(userId) type incorrect!");
1859             return false;
1860         }
1861 
1862         userId = Constants::UNSPECIFIED_USERID;
1863         NAPI_CALL_BASE(env, napi_get_value_int32(env, property, &userId), false);
1864     }
1865     return true;
1866 }
1867 
ParseInstallFlag(napi_env env,napi_value args,InstallFlag & installFlag)1868 static bool ParseInstallFlag(napi_env env, napi_value args, InstallFlag &installFlag)
1869 {
1870     bool hasKey = false;
1871     napi_has_named_property(env, args, "installFlag", &hasKey);
1872     if (hasKey) {
1873         napi_value property = nullptr;
1874         napi_status status = napi_get_named_property(env, args, "installFlag", &property);
1875         if (status != napi_ok) {
1876             APP_LOGE("napi get named installFlag property error!");
1877             return false;
1878         }
1879         napi_valuetype valueType;
1880         napi_typeof(env, property, &valueType);
1881         if (valueType != napi_number) {
1882             APP_LOGE("param(installFlag) type incorrect!");
1883             return false;
1884         }
1885 
1886         int32_t flag = 0;
1887         NAPI_CALL_BASE(env, napi_get_value_int32(env, property, &flag), false);
1888         installFlag = static_cast<OHOS::AppExecFwk::InstallFlag>(flag);
1889     }
1890     return true;
1891 }
1892 
ParseIsKeepData(napi_env env,napi_value args,bool & isKeepData)1893 static bool ParseIsKeepData(napi_env env, napi_value args, bool &isKeepData)
1894 {
1895     bool hasKey = false;
1896     napi_has_named_property(env, args, "isKeepData", &hasKey);
1897     if (hasKey) {
1898         napi_value property = nullptr;
1899         napi_status status = napi_get_named_property(env, args, "isKeepData", &property);
1900         if (status != napi_ok) {
1901             APP_LOGE("napi get named isKeepData property error!");
1902             return false;
1903         }
1904         napi_valuetype valueType;
1905         napi_typeof(env, property, &valueType);
1906         if (valueType != napi_boolean) {
1907             APP_LOGE("param(isKeepData) type incorrect!");
1908             return false;
1909         }
1910 
1911         NAPI_CALL_BASE(env, napi_get_value_bool(env, property, &isKeepData), false);
1912     }
1913     return true;
1914 }
1915 
ParseCrowdtestDeadline(napi_env env,napi_value args,int64_t & crowdtestDeadline)1916 static bool ParseCrowdtestDeadline(napi_env env, napi_value args, int64_t &crowdtestDeadline)
1917 {
1918     bool hasKey = false;
1919     napi_has_named_property(env, args, "crowdtestDeadline", &hasKey);
1920     if (hasKey) {
1921         napi_value property = nullptr;
1922         napi_status status = napi_get_named_property(env, args, "crowdtestDeadline", &property);
1923         if (status != napi_ok) {
1924             APP_LOGE("napi get named crowdtestDeadline property error!");
1925             return false;
1926         }
1927         napi_valuetype valueType;
1928         napi_typeof(env, property, &valueType);
1929         if (valueType != napi_number) {
1930             APP_LOGE("param(crowdtestDeadline) type incorrect!");
1931             return false;
1932         }
1933         NAPI_CALL_BASE(env, napi_get_value_int64(env, property, &crowdtestDeadline), false);
1934     }
1935     return true;
1936 }
1937 
ParseInstallParam(napi_env env,InstallParam & installParam,napi_value args)1938 static bool ParseInstallParam(napi_env env, InstallParam &installParam, napi_value args)
1939 {
1940     napi_valuetype valueType;
1941     NAPI_CALL_BASE(env, napi_typeof(env, args, &valueType), false);
1942     if (valueType != napi_object) {
1943         APP_LOGE("args type incorrect!");
1944         return false;
1945     }
1946 
1947     if (!ParseUserId(env, args, installParam.userId) || !ParseInstallFlag(env, args, installParam.installFlag) ||
1948         !ParseIsKeepData(env, args, installParam.isKeepData) || !ParseHashParams(env, args, installParam.hashParams) ||
1949         !ParseCrowdtestDeadline(env, args, installParam.crowdtestDeadline)) {
1950         APP_LOGE("ParseInstallParam failed");
1951         return false;
1952     }
1953     return true;
1954 }
1955 
InnerGetAllFormsInfo(napi_env env,std::vector<OHOS::AppExecFwk::FormInfo> & formInfos)1956 static bool InnerGetAllFormsInfo(napi_env env, std::vector<OHOS::AppExecFwk::FormInfo> &formInfos)
1957 {
1958     auto iBundleMgr = GetBundleMgr();
1959     if (iBundleMgr == nullptr) {
1960         APP_LOGE("can not get iBundleMgr");
1961         return false;
1962     }
1963     return iBundleMgr->GetAllFormsInfo(formInfos);
1964 }
1965 
ProcessFormsInfo(napi_env env,napi_value result,const std::vector<OHOS::AppExecFwk::FormInfo> & formInfos)1966 static void ProcessFormsInfo(napi_env env, napi_value result, const std::vector<OHOS::AppExecFwk::FormInfo> &formInfos)
1967 {
1968     if (formInfos.size() > 0) {
1969         APP_LOGI("-----formInfos is not null-----");
1970         size_t index = 0;
1971         for (const auto &item : formInfos) {
1972             APP_LOGI("name{%s} ", item.name.c_str());
1973             APP_LOGI("bundleName{%s} ", item.bundleName.c_str());
1974             napi_value objFormInfo;
1975             NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objFormInfo));
1976             ConvertFormInfo(env, objFormInfo, item);
1977             NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, objFormInfo));
1978             index++;
1979         }
1980     } else {
1981         APP_LOGI("-----formInfos is null-----");
1982     }
1983 }
1984 /**
1985  * Promise and async callback
1986  */
GetAllFormsInfo(napi_env env,napi_callback_info info)1987 napi_value GetAllFormsInfo(napi_env env, napi_callback_info info)
1988 {
1989     size_t argc = ARGS_SIZE_ONE;
1990     napi_value argv[ARGS_SIZE_ONE] = {nullptr};
1991     napi_value thisArg;
1992     void *data = nullptr;
1993     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data));
1994     APP_LOGI("ARGCSIZE is =%{public}zu.", argc);
1995 
1996     AsyncFormInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncFormInfosCallbackInfo(env);
1997     if (asyncCallbackInfo == nullptr) {
1998         return nullptr;
1999     }
2000     std::unique_ptr<AsyncFormInfosCallbackInfo> callbackPtr {asyncCallbackInfo};
2001     if (argc > (ARGS_SIZE_ONE - CALLBACK_SIZE)) {
2002         APP_LOGI("GetAllFormsInfo asyncCallback.");
2003         napi_value resourceName;
2004         NAPI_CALL(env, napi_create_string_latin1(env, "GetAllFormsInfo", NAPI_AUTO_LENGTH, &resourceName));
2005         napi_valuetype valuetype = napi_undefined;
2006         NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype));
2007         NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
2008         NAPI_CALL(env, napi_create_reference(env, argv[PARAM0], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
2009 
2010         NAPI_CALL(env, napi_create_async_work(
2011             env,
2012             nullptr,
2013             resourceName,
2014             [](napi_env env, void *data) {
2015                 AsyncFormInfosCallbackInfo *asyncCallbackInfo =
2016                     reinterpret_cast<AsyncFormInfosCallbackInfo *>(data);
2017                 asyncCallbackInfo->ret = InnerGetAllFormsInfo(env, asyncCallbackInfo->formInfos);
2018             },
2019             [](napi_env env, napi_status status, void *data) {
2020                 AsyncFormInfosCallbackInfo *asyncCallbackInfo =
2021                     reinterpret_cast<AsyncFormInfosCallbackInfo *>(data);
2022                 std::unique_ptr<AsyncFormInfosCallbackInfo> callbackPtr {asyncCallbackInfo};
2023                 napi_value result[ARGS_SIZE_TWO] = {0};
2024                 napi_value callback = 0;
2025                 napi_value undefined = 0;
2026                 napi_value callResult = 0;
2027                 NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined));
2028                 NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result[PARAM1]));
2029                 ProcessFormsInfo(env, result[PARAM1], asyncCallbackInfo->formInfos);
2030                 result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->ret ? CODE_SUCCESS : CODE_FAILED);
2031                 NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callback, &callback));
2032                 NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_SIZE_TWO,
2033                     &result[PARAM0], &callResult));
2034             },
2035             reinterpret_cast<void*>(asyncCallbackInfo),
2036             &asyncCallbackInfo->asyncWork));
2037         NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
2038         callbackPtr.release();
2039         napi_value result;
2040         napi_create_int32(env, NAPI_RETURN_ONE, &result);
2041         return result;
2042     } else {
2043         APP_LOGI("GetFormInfos promise.");
2044         napi_deferred deferred;
2045         napi_value promise;
2046         NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
2047         asyncCallbackInfo->deferred = deferred;
2048 
2049         napi_value resourceName;
2050         NAPI_CALL(env, napi_create_string_latin1(env, "GetFormInfos", NAPI_AUTO_LENGTH, &resourceName));
2051         NAPI_CALL(env, napi_create_async_work(
2052             env,
2053             nullptr,
2054             resourceName,
2055             [](napi_env env, void *data) {
2056                 AsyncFormInfosCallbackInfo *asyncCallbackInfo =
2057                     reinterpret_cast<AsyncFormInfosCallbackInfo *>(data);
2058                 InnerGetAllFormsInfo(env, asyncCallbackInfo->formInfos);
2059             },
2060             [](napi_env env, napi_status status, void *data) {
2061                 APP_LOGI("=================load=================");
2062                 AsyncFormInfosCallbackInfo *asyncCallbackInfo =
2063                     reinterpret_cast<AsyncFormInfosCallbackInfo *>(data);
2064                 std::unique_ptr<AsyncFormInfosCallbackInfo> callbackPtr {asyncCallbackInfo};
2065                 napi_value result;
2066                 NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result));
2067                 ProcessFormsInfo(env, result, asyncCallbackInfo->formInfos);
2068                 NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred,
2069                     result));
2070             },
2071             reinterpret_cast<void*>(asyncCallbackInfo),
2072             &asyncCallbackInfo->asyncWork));
2073         NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
2074         callbackPtr.release();
2075         return promise;
2076     }
2077 }
2078 
InnerGetFormInfosByModule(napi_env env,const std::string & bundleName,const std::string & moduleName,std::vector<OHOS::AppExecFwk::FormInfo> & formInfos)2079 static bool InnerGetFormInfosByModule(napi_env env, const std::string &bundleName, const std::string &moduleName,
2080     std::vector<OHOS::AppExecFwk::FormInfo> &formInfos)
2081 {
2082     auto iBundleMgr = GetBundleMgr();
2083     if (iBundleMgr == nullptr) {
2084         APP_LOGE("can not get iBundleMgr");
2085         return false;
2086     }
2087     return iBundleMgr->GetFormsInfoByModule(bundleName, moduleName, formInfos);
2088 }
2089 /**
2090  * Promise and async callback
2091  */
GetFormsInfoByModule(napi_env env,napi_callback_info info)2092 napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info)
2093 {
2094     size_t argc = ARGS_SIZE_THREE;
2095     napi_value argv[ARGS_SIZE_THREE] = {nullptr};
2096     napi_value thisArg;
2097     void *data = nullptr;
2098     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data));
2099     APP_LOGI("ARGCSIZE is =%{public}zu.", argc);
2100     std::string bundleName;
2101     std::string moduleName;
2102     ParseString(env, bundleName, argv[PARAM0]);
2103     ParseString(env, moduleName, argv[PARAM1]);
2104 
2105     AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncFormInfosByModuleCallbackInfo(env);
2106     if (asyncCallbackInfo == nullptr) {
2107         return nullptr;
2108     }
2109     std::unique_ptr<AsyncFormInfosByModuleCallbackInfo> callbackPtr {asyncCallbackInfo};
2110     asyncCallbackInfo->bundleName = bundleName;
2111     asyncCallbackInfo->moduleName = moduleName;
2112 
2113     if (argc > (ARGS_SIZE_THREE - CALLBACK_SIZE)) {
2114         APP_LOGI("GetFormsInfoByModule asyncCallback.");
2115         napi_value resourceName;
2116         NAPI_CALL(env, napi_create_string_latin1(env, "GetFormsInfoByModule", NAPI_AUTO_LENGTH, &resourceName));
2117         napi_valuetype valuetype = napi_undefined;
2118         NAPI_CALL(env, napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype));
2119         NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
2120         NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
2121 
2122         NAPI_CALL(env, napi_create_async_work(
2123             env,
2124             nullptr,
2125             resourceName,
2126             [](napi_env env, void *data) {
2127                 AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo =
2128                     reinterpret_cast<AsyncFormInfosByModuleCallbackInfo *>(data);
2129                 asyncCallbackInfo->ret = InnerGetFormInfosByModule(
2130                     env, asyncCallbackInfo->bundleName, asyncCallbackInfo->moduleName, asyncCallbackInfo->formInfos);
2131             },
2132             [](napi_env env, napi_status status, void *data) {
2133                 AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo =
2134                     reinterpret_cast<AsyncFormInfosByModuleCallbackInfo *>(data);
2135                 std::unique_ptr<AsyncFormInfosByModuleCallbackInfo> callbackPtr {asyncCallbackInfo};
2136                 napi_value result[ARGS_SIZE_TWO] = {0};
2137                 napi_value callback = 0;
2138                 napi_value undefined = 0;
2139                 napi_value callResult = 0;
2140                 NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined));
2141                 NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result[PARAM1]));
2142                 ProcessFormsInfo(env, result[PARAM1], asyncCallbackInfo->formInfos);
2143                 result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->ret ? CODE_SUCCESS : CODE_FAILED);
2144                 NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callback, &callback));
2145                 NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_SIZE_TWO,
2146                     &result[PARAM0], &callResult));
2147             },
2148             reinterpret_cast<void*>(asyncCallbackInfo),
2149             &asyncCallbackInfo->asyncWork));
2150         NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
2151         callbackPtr.release();
2152         napi_value result;
2153         napi_create_int32(env, NAPI_RETURN_ONE, &result);
2154         return result;
2155     } else {
2156         APP_LOGI("GetFormsInfoByModule promise.");
2157         napi_deferred deferred;
2158         napi_value promise;
2159         NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
2160         asyncCallbackInfo->deferred = deferred;
2161 
2162         napi_value resourceName;
2163         NAPI_CALL(env, napi_create_string_latin1(env, "GetFormsInfoByModule", NAPI_AUTO_LENGTH, &resourceName));
2164         NAPI_CALL(env, napi_create_async_work(
2165             env,
2166             nullptr,
2167             resourceName,
2168             [](napi_env env, void *data) {
2169                 AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo =
2170                     reinterpret_cast<AsyncFormInfosByModuleCallbackInfo *>(data);
2171                 InnerGetFormInfosByModule(
2172                     env, asyncCallbackInfo->bundleName, asyncCallbackInfo->moduleName, asyncCallbackInfo->formInfos);
2173             },
2174             [](napi_env env, napi_status status, void *data) {
2175                 APP_LOGI("=================load=================");
2176                 AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo =
2177                     reinterpret_cast<AsyncFormInfosByModuleCallbackInfo *>(data);
2178                 std::unique_ptr<AsyncFormInfosByModuleCallbackInfo> callbackPtr {asyncCallbackInfo};
2179                 napi_value result;
2180                 NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result));
2181                 ProcessFormsInfo(env, result, asyncCallbackInfo->formInfos);
2182                 NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred,
2183                     result));
2184             },
2185             reinterpret_cast<void*>(asyncCallbackInfo),
2186             &asyncCallbackInfo->asyncWork));
2187         NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
2188         callbackPtr.release();
2189         return promise;
2190     }
2191 }
2192 
InnerGetFormInfosByApp(napi_env env,const std::string & bundleName,std::vector<OHOS::AppExecFwk::FormInfo> & formInfos)2193 static bool InnerGetFormInfosByApp(
2194     napi_env env, const std::string &bundleName, std::vector<OHOS::AppExecFwk::FormInfo> &formInfos)
2195 {
2196     auto iBundleMgr = GetBundleMgr();
2197     if (iBundleMgr == nullptr) {
2198         APP_LOGE("can not get iBundleMgr");
2199         return false;
2200     }
2201     return iBundleMgr->GetFormsInfoByApp(bundleName, formInfos);
2202 }
2203 /**
2204  * Promise and async callback
2205  */
GetFormsInfoByApp(napi_env env,napi_callback_info info)2206 napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info)
2207 {
2208     size_t argc = ARGS_SIZE_TWO;
2209     napi_value argv[ARGS_SIZE_TWO] = {nullptr};
2210     napi_value thisArg;
2211     void *data = nullptr;
2212     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data));
2213     APP_LOGI("ARGCSIZE is =%{public}zu.", argc);
2214     std::string bundleName;
2215     ParseString(env, bundleName, argv[PARAM0]);
2216 
2217     AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncFormInfosByAppCallbackInfo(env);
2218     if (asyncCallbackInfo == nullptr) {
2219         return nullptr;
2220     }
2221     std::unique_ptr<AsyncFormInfosByAppCallbackInfo> callbackPtr {asyncCallbackInfo};
2222     asyncCallbackInfo->bundleName = bundleName;
2223     if (argc > (ARGS_SIZE_TWO - CALLBACK_SIZE)) {
2224         APP_LOGI("GetFormsInfoByApp asyncCallback.");
2225         napi_value resourceName;
2226         NAPI_CALL(env, napi_create_string_latin1(env, "GetFormsInfoByApp", NAPI_AUTO_LENGTH, &resourceName));
2227         napi_valuetype valuetype = napi_undefined;
2228         napi_typeof(env, argv[ARGS_SIZE_ONE], &valuetype);
2229         NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
2230         NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
2231 
2232         NAPI_CALL(env, napi_create_async_work(
2233             env,
2234             nullptr,
2235             resourceName,
2236             [](napi_env env, void *data) {
2237                 AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo =
2238                     reinterpret_cast<AsyncFormInfosByAppCallbackInfo *>(data);
2239                 asyncCallbackInfo->ret =
2240                     InnerGetFormInfosByApp(env, asyncCallbackInfo->bundleName, asyncCallbackInfo->formInfos);
2241             },
2242             [](napi_env env, napi_status status, void *data) {
2243                 AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo =
2244                     reinterpret_cast<AsyncFormInfosByAppCallbackInfo *>(data);
2245                 std::unique_ptr<AsyncFormInfosByAppCallbackInfo> callbackPtr {asyncCallbackInfo};
2246                 napi_value result[ARGS_SIZE_TWO] = {0};
2247                 napi_value callback = 0;
2248                 napi_value undefined = 0;
2249                 napi_value callResult = 0;
2250                 NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined));
2251                 NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result[PARAM1]));
2252                 ProcessFormsInfo(env, result[PARAM1], asyncCallbackInfo->formInfos);
2253                 result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->ret ? CODE_SUCCESS : CODE_FAILED);
2254                 NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callback, &callback));
2255                 NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_SIZE_TWO,
2256                     &result[PARAM0], &callResult));
2257             },
2258             reinterpret_cast<void*>(asyncCallbackInfo),
2259             &asyncCallbackInfo->asyncWork));
2260         NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
2261         callbackPtr.release();
2262         napi_value result;
2263         napi_create_int32(env, NAPI_RETURN_ONE, &result);
2264         return result;
2265     } else {
2266         APP_LOGI("GetFormsInfoByApp promise.");
2267         napi_deferred deferred;
2268         napi_value promise;
2269         NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
2270         asyncCallbackInfo->deferred = deferred;
2271 
2272         napi_value resourceName;
2273         NAPI_CALL(env, napi_create_string_latin1(env, "GetFormsInfoByApp", NAPI_AUTO_LENGTH, &resourceName));
2274         NAPI_CALL(env, napi_create_async_work(
2275             env,
2276             nullptr,
2277             resourceName,
2278             [](napi_env env, void *data) {
2279                 AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo =
2280                     reinterpret_cast<AsyncFormInfosByAppCallbackInfo *>(data);
2281                 InnerGetFormInfosByApp(env, asyncCallbackInfo->bundleName, asyncCallbackInfo->formInfos);
2282             },
2283             [](napi_env env, napi_status status, void *data) {
2284                 APP_LOGI("=================load=================");
2285                 AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo =
2286                     reinterpret_cast<AsyncFormInfosByAppCallbackInfo *>(data);
2287                 std::unique_ptr<AsyncFormInfosByAppCallbackInfo> callbackPtr {asyncCallbackInfo};
2288                 napi_value result;
2289                 NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result));
2290                 ProcessFormsInfo(env, result, asyncCallbackInfo->formInfos);
2291                 NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred,
2292                     result));
2293             },
2294             reinterpret_cast<void*>(asyncCallbackInfo),
2295             &asyncCallbackInfo->asyncWork));
2296         NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
2297         callbackPtr.release();
2298         return promise;
2299     }
2300 }
2301 
InnerGetBundleGids(napi_env env,const std::string & bundleName,std::vector<int> & gids)2302 static bool InnerGetBundleGids(napi_env env, const std::string &bundleName, std::vector<int> &gids)
2303 {
2304     auto iBundleMgr = GetBundleMgr();
2305     if (iBundleMgr == nullptr) {
2306         APP_LOGE("can not get iBundleMgr");
2307         return false;
2308     };
2309     auto ret = iBundleMgr->GetBundleGids(bundleName, gids);
2310     return ret;
2311 }
2312 
ProcessGids(napi_env env,napi_value result,const std::vector<int32_t> & gids)2313 static void ProcessGids(napi_env env, napi_value result, const std::vector<int32_t> &gids)
2314 {
2315     if (gids.size() > 0) {
2316         APP_LOGI("-----gids is not null-----");
2317         size_t index = 0;
2318         for (const auto &item : gids) {
2319             napi_value value;
2320             napi_create_int32(env, item, &value);
2321             NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, value));
2322             index++;
2323         }
2324         APP_LOGI("-----gids is not null  end-----");
2325     } else {
2326         APP_LOGI("-----ShortcutInfos is null-----");
2327     }
2328 }
2329 
WrapVoidToJS(napi_env env)2330 napi_value WrapVoidToJS(napi_env env)
2331 {
2332     napi_value result = nullptr;
2333     NAPI_CALL(env, napi_get_null(env, &result));
2334     return result;
2335 }
2336 
WrapUndefinedToJS(napi_env env)2337 napi_value WrapUndefinedToJS(napi_env env)
2338 {
2339     napi_value result = nullptr;
2340     NAPI_CALL(env, napi_get_undefined(env, &result));
2341     return result;
2342 }
2343 
CreateAsyncGetBundleGidsCallbackInfo(napi_env env)2344 AsyncGetBundleGidsCallbackInfo *CreateAsyncGetBundleGidsCallbackInfo(napi_env env)
2345 {
2346     APP_LOGI("%{public}s called.", __func__);
2347     AsyncGetBundleGidsCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetBundleGidsCallbackInfo(env);
2348     if (asyncCallbackInfo == nullptr) {
2349         APP_LOGE("%{public}s, asyncCallbackInfo == nullptr.", __func__);
2350         return nullptr;
2351     }
2352 
2353     APP_LOGI("%{public}s end.", __func__);
2354     return asyncCallbackInfo;
2355 }
2356 
GetBundleGidsExecute(napi_env env,void * data)2357 void GetBundleGidsExecute(napi_env env, void *data)
2358 {
2359     APP_LOGI("NAPI_GetBundleGids, worker pool thread execute.");
2360     AsyncGetBundleGidsCallbackInfo *asyncCallbackInfo = static_cast<AsyncGetBundleGidsCallbackInfo *>(data);
2361     if (asyncCallbackInfo == nullptr) {
2362         APP_LOGE("NAPI_GetBundleGids, asyncCallbackInfo == nullptr");
2363         return;
2364     }
2365 
2366     bool ret = InnerGetBundleGids(env, asyncCallbackInfo->bundleName, asyncCallbackInfo->gids);
2367 
2368     if (!ret) {
2369         asyncCallbackInfo->err = NAPI_RETURN_FAILED;
2370     }
2371 }
2372 
GetBundleGidsAsyncComplete(napi_env env,napi_status status,void * data)2373 void GetBundleGidsAsyncComplete(napi_env env, napi_status status, void *data)
2374 {
2375     APP_LOGI("NAPI_GetBundleGids, main event thread complete.");
2376     AsyncGetBundleGidsCallbackInfo *asyncCallbackInfo = static_cast<AsyncGetBundleGidsCallbackInfo *>(data);
2377     std::unique_ptr<AsyncGetBundleGidsCallbackInfo> callbackPtr {asyncCallbackInfo};
2378     napi_value callback = nullptr;
2379     napi_value undefined = nullptr;
2380     napi_value result[ARGS_SIZE_TWO] = {nullptr};
2381     napi_value callResult = nullptr;
2382     NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined));
2383     result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->err);
2384 
2385     if (asyncCallbackInfo->err == NAPI_ERR_NO_ERROR) {
2386         NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result[PARAM1]));
2387         ProcessGids(env, result[PARAM1], asyncCallbackInfo->gids);
2388     } else {
2389         result[PARAM1] = WrapUndefinedToJS(env);
2390     }
2391 
2392     NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callback, &callback));
2393     NAPI_CALL_RETURN_VOID(env,
2394         napi_call_function(env, undefined, callback, sizeof(result) / sizeof(result[PARAM0]), result, &callResult));
2395     APP_LOGI("NAPI_GetApplicationInfo, main event thread complete end.");
2396 }
2397 
GetBundleGidsPromiseComplete(napi_env env,napi_status status,void * data)2398 void GetBundleGidsPromiseComplete(napi_env env, napi_status status, void *data)
2399 {
2400     APP_LOGI("NAPI_GetBundleGids, main event thread complete.");
2401     AsyncGetBundleGidsCallbackInfo *asyncCallbackInfo = static_cast<AsyncGetBundleGidsCallbackInfo *>(data);
2402     std::unique_ptr<AsyncGetBundleGidsCallbackInfo> callbackPtr {asyncCallbackInfo};
2403     napi_value result = nullptr;
2404     if (asyncCallbackInfo->err == NAPI_ERR_NO_ERROR) {
2405         NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result));
2406         ProcessGids(env, result, asyncCallbackInfo->gids);
2407         NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncCallbackInfo->deferred, result));
2408     } else {
2409         result = GetCallbackErrorValue(env, asyncCallbackInfo->err);
2410         NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, asyncCallbackInfo->deferred, result));
2411     }
2412     APP_LOGI("NAPI_GetApplicationInfo, main event thread complete end.");
2413 }
2414 
GetBundleGidsAsync(napi_env env,napi_value * args,const size_t argCallback,AsyncGetBundleGidsCallbackInfo * asyncCallbackInfo)2415 napi_value GetBundleGidsAsync(
2416     napi_env env, napi_value *args, const size_t argCallback, AsyncGetBundleGidsCallbackInfo *asyncCallbackInfo)
2417 {
2418     APP_LOGI("%{public}s, asyncCallback.", __func__);
2419     if (args == nullptr || asyncCallbackInfo == nullptr) {
2420         APP_LOGE("%{public}s, param == nullptr.", __func__);
2421         return nullptr;
2422     }
2423 
2424     napi_value resourceName = nullptr;
2425     NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName));
2426 
2427     napi_valuetype valuetype = napi_undefined;
2428     NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype));
2429     if (valuetype == napi_function) {
2430         NAPI_CALL(env, napi_create_reference(env, args[argCallback], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
2431     } else {
2432         return nullptr;
2433     }
2434 
2435     NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, GetBundleGidsExecute, GetBundleGidsAsyncComplete,
2436                        reinterpret_cast<void*>(asyncCallbackInfo), &asyncCallbackInfo->asyncWork));
2437     NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
2438     napi_value result = nullptr;
2439     NAPI_CALL(env, napi_get_null(env, &result));
2440     APP_LOGI("%{public}s, asyncCallback end.", __func__);
2441     return result;
2442 }
2443 
GetBundleGidsPromise(napi_env env,AsyncGetBundleGidsCallbackInfo * asyncCallbackInfo)2444 napi_value GetBundleGidsPromise(napi_env env, AsyncGetBundleGidsCallbackInfo *asyncCallbackInfo)
2445 {
2446     APP_LOGI("%{public}s, promise.", __func__);
2447     if (asyncCallbackInfo == nullptr) {
2448         APP_LOGE("%{public}s, param == nullptr.", __func__);
2449         return nullptr;
2450     }
2451     napi_value resourceName = nullptr;
2452     NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName));
2453     napi_deferred deferred;
2454     napi_value promise = nullptr;
2455     NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
2456     asyncCallbackInfo->deferred = deferred;
2457 
2458     NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName,
2459                 GetBundleGidsExecute, GetBundleGidsPromiseComplete,
2460                 reinterpret_cast<void*>(asyncCallbackInfo), &asyncCallbackInfo->asyncWork));
2461     NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
2462     APP_LOGI("%{public}s, promise end.", __func__);
2463     return promise;
2464 }
2465 
GetBundleGidsWrap(napi_env env,napi_callback_info info,AsyncGetBundleGidsCallbackInfo * asyncCallbackInfo)2466 napi_value GetBundleGidsWrap(napi_env env, napi_callback_info info, AsyncGetBundleGidsCallbackInfo *asyncCallbackInfo)
2467 {
2468     APP_LOGI("%{public}s, asyncCallback.", __func__);
2469     if (asyncCallbackInfo == nullptr) {
2470         APP_LOGE("%{public}s, asyncCallbackInfo == nullptr.", __func__);
2471         return nullptr;
2472     }
2473 
2474     size_t argcAsync = ARGS_SIZE_TWO;
2475     const size_t argcPromise = ARGS_SIZE_ONE;
2476     const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT;
2477     napi_value args[ARGS_MAX_COUNT] = {nullptr};
2478     napi_value ret = nullptr;
2479 
2480     NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr));
2481     if (argcAsync > argCountWithAsync) {
2482         APP_LOGE("%{public}s, Wrong argument count.", __func__);
2483         return nullptr;
2484     }
2485 
2486     napi_valuetype valueType = napi_undefined;
2487     NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valueType));
2488     if (valueType == napi_string) {
2489         ParseString(env, asyncCallbackInfo->bundleName, args[PARAM0]);
2490     } else {
2491         asyncCallbackInfo->err = INVALID_PARAM;
2492     }
2493 
2494     if (argcAsync > argcPromise) {
2495         ret = GetBundleGidsAsync(env, args, argcAsync - 1, asyncCallbackInfo);
2496     } else {
2497         ret = GetBundleGidsPromise(env, asyncCallbackInfo);
2498     }
2499     APP_LOGI("%{public}s, asyncCallback end.", __func__);
2500     return ret;
2501 }
2502 
GetBundleGids(napi_env env,napi_callback_info info)2503 napi_value GetBundleGids(napi_env env, napi_callback_info info)
2504 {
2505     APP_LOGI("NAPI_GetBundleGids start");
2506     AsyncGetBundleGidsCallbackInfo *asyncCallbackInfo = CreateAsyncGetBundleGidsCallbackInfo(env);
2507     if (asyncCallbackInfo == nullptr) {
2508         return WrapVoidToJS(env);
2509     }
2510     std::unique_ptr<AsyncGetBundleGidsCallbackInfo> callbackPtr {asyncCallbackInfo};
2511     napi_value ret = GetBundleGidsWrap(env, info, asyncCallbackInfo);
2512     if (ret == nullptr) {
2513         APP_LOGE("%{public}s ret == nullptr", __func__);
2514         ret = WrapVoidToJS(env);
2515     } else {
2516         callbackPtr.release();
2517     }
2518     APP_LOGI("%{public}s end.", __func__);
2519     return ret;
2520 }
2521 
InnerSetApplicationEnabled(const std::string & bundleName,bool isEnable)2522 static bool InnerSetApplicationEnabled(const std::string &bundleName, bool isEnable)
2523 {
2524     auto iBundleMgr = GetBundleMgr();
2525     if (iBundleMgr == nullptr) {
2526         APP_LOGE("can not get iBundleMgr");
2527         return false;
2528     }
2529     ErrCode result = iBundleMgr->SetApplicationEnabled(bundleName, isEnable);
2530     if (result != ERR_OK) {
2531         APP_LOGE("InnerSetApplicationEnabled::SetApplicationEnabled");
2532         return false;
2533     }
2534     return true;
2535 }
2536 
InnerSetAbilityEnabled(const OHOS::AppExecFwk::AbilityInfo & abilityInfo,bool isEnable)2537 static bool InnerSetAbilityEnabled(const OHOS::AppExecFwk::AbilityInfo &abilityInfo, bool isEnable)
2538 {
2539     auto iBundleMgr = GetBundleMgr();
2540     if (iBundleMgr == nullptr) {
2541         APP_LOGE("can not get iBundleMgr");
2542         return false;
2543     }
2544     ErrCode result = iBundleMgr->SetAbilityEnabled(abilityInfo, isEnable);
2545     if (result != ERR_OK) {
2546         APP_LOGE("InnerSetAbilityEnabled::SetAbilityEnabled");
2547         return false;
2548     }
2549     return true;
2550 }
2551 
InnerCleanBundleCacheCallback(const std::string & bundleName,const OHOS::sptr<CleanCacheCallback> & cleanCacheCallback)2552 static bool InnerCleanBundleCacheCallback(
2553     const std::string& bundleName, const OHOS::sptr<CleanCacheCallback>& cleanCacheCallback)
2554 {
2555     auto iBundleMgr = GetBundleMgr();
2556     if (iBundleMgr == nullptr) {
2557         APP_LOGE("can not get iBundleMgr");
2558         return false;
2559     }
2560     if (cleanCacheCallback == nullptr) {
2561         APP_LOGE("callback nullptr");
2562         return false;
2563     }
2564     int32_t userId = IPCSkeleton::GetCallingUid() / Constants::BASE_USER_RANGE;
2565     ErrCode result = iBundleMgr->CleanBundleCacheFiles(bundleName, cleanCacheCallback, userId);
2566     if (result != ERR_OK) {
2567         APP_LOGE("CleanBundleDataFiles call error");
2568         return false;
2569     }
2570 
2571     return true;
2572 }
2573 
ParseModuleName(napi_env env,napi_value param,std::string & moduleName)2574 bool ParseModuleName(napi_env env, napi_value param, std::string &moduleName)
2575 {
2576     bool hasKey = false;
2577     napi_has_named_property(env, param, "moduleName", &hasKey);
2578     if (hasKey) {
2579         napi_valuetype valueType;
2580         napi_value prop = nullptr;
2581         napi_get_named_property(env, param, "moduleName", &prop);
2582         napi_typeof(env, prop, &valueType);
2583         if (valueType == napi_undefined) {
2584             APP_LOGE("begin to parse moduleName failed");
2585             return false;
2586         }
2587         moduleName = GetStringFromNAPI(env, prop);
2588     }
2589     return true;
2590 }
2591 
UnwrapAbilityInfo(napi_env env,napi_value param,OHOS::AppExecFwk::AbilityInfo & abilityInfo)2592 bool UnwrapAbilityInfo(napi_env env, napi_value param, OHOS::AppExecFwk::AbilityInfo& abilityInfo)
2593 {
2594     napi_valuetype valueType;
2595     NAPI_CALL_BASE(env, napi_typeof(env, param, &valueType), false);
2596     if (valueType != napi_object) {
2597         APP_LOGE("param type mismatch!");
2598         return false;
2599     }
2600 
2601     napi_value prop = nullptr;
2602     // parse bundleName
2603     napi_get_named_property(env, param, "bundleName", &prop);
2604     napi_typeof(env, prop, &valueType);
2605     if (valueType == napi_undefined) {
2606         return false;
2607     }
2608     std::string bundleName = GetStringFromNAPI(env, prop);
2609     abilityInfo.bundleName = bundleName;
2610 
2611     // parse moduleName
2612     std::string moduleName;
2613     if (!ParseModuleName(env, param, moduleName)) {
2614         return false;
2615     }
2616     abilityInfo.moduleName = moduleName;
2617 
2618     // parse abilityName
2619     napi_get_named_property(env, param, "name", &prop);
2620     napi_typeof(env, prop, &valueType);
2621     if (valueType == napi_undefined) {
2622         return false;
2623     }
2624     std::string name = GetStringFromNAPI(env, prop);
2625     abilityInfo.name = name;
2626     return true;
2627 }
2628 
InnerGetNameForUid(int32_t uid,std::string & bundleName)2629 static bool InnerGetNameForUid(int32_t uid, std::string &bundleName)
2630 {
2631     auto iBundleMgr = GetBundleMgr();
2632     if (iBundleMgr == nullptr) {
2633         APP_LOGE("can not get iBundleMgr");
2634         return false;
2635     }
2636     if (iBundleMgr->GetNameForUid(uid, bundleName) != ERR_OK) {
2637         APP_LOGE("GetNameForUid failed");
2638         return false;
2639     }
2640     return true;
2641 }
2642 
ClearBundleCache(napi_env env,napi_callback_info info)2643 napi_value ClearBundleCache(napi_env env, napi_callback_info info)
2644 {
2645     size_t requireArgc = ARGS_SIZE_ONE;
2646     size_t argc = ARGS_SIZE_TWO;
2647     napi_value argv[ARGS_SIZE_TWO] = { 0 };
2648     napi_value thisArg = nullptr;
2649     void *data = nullptr;
2650 
2651     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data));
2652     NAPI_ASSERT(env, argc >= requireArgc, "requires 1 parameter");
2653 
2654     AsyncHandleBundleContext *asyncCallbackInfo = new (std::nothrow) AsyncHandleBundleContext(env);
2655     if (asyncCallbackInfo == nullptr) {
2656         return nullptr;
2657     }
2658     std::unique_ptr<AsyncHandleBundleContext> callbackPtr {asyncCallbackInfo};
2659     for (size_t i = 0; i < argc; ++i) {
2660         napi_valuetype valueType = napi_undefined;
2661         napi_typeof(env, argv[i], &valueType);
2662         if ((i == 0) && (valueType == napi_string)) {
2663             ParseString(env, asyncCallbackInfo->bundleName, argv[i]);
2664         } else if ((i == 1) && (valueType == napi_function)) {
2665             NAPI_CALL(env, napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callback));
2666         } else {
2667             asyncCallbackInfo->err = INVALID_PARAM;
2668         }
2669     }
2670     napi_value promise = nullptr;
2671 
2672     if (asyncCallbackInfo->callback == nullptr) {
2673         NAPI_CALL(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise));
2674     } else {
2675         NAPI_CALL(env, napi_get_undefined(env, &promise));
2676     }
2677 
2678     napi_value resource = nullptr;
2679     NAPI_CALL(env, napi_create_string_utf8(env, "JSCleanBundleCache", NAPI_AUTO_LENGTH, &resource));
2680     NAPI_CALL(env, napi_create_async_work(
2681         env, nullptr, resource,
2682         [](napi_env env, void* data) {
2683             AsyncHandleBundleContext* asyncCallbackInfo =
2684                 reinterpret_cast<AsyncHandleBundleContext*>(data);
2685             if (asyncCallbackInfo->cleanCacheCallback == nullptr) {
2686                 asyncCallbackInfo->cleanCacheCallback = new (std::nothrow) CleanCacheCallback(UNDEFINED_ERROR);
2687             }
2688             if (!asyncCallbackInfo->err) {
2689                 asyncCallbackInfo->ret =
2690                     InnerCleanBundleCacheCallback(asyncCallbackInfo->bundleName, asyncCallbackInfo->cleanCacheCallback);
2691             }
2692         },
2693         [](napi_env env, napi_status status, void* data) {
2694             AsyncHandleBundleContext* asyncCallbackInfo =
2695                 reinterpret_cast<AsyncHandleBundleContext*>(data);
2696             std::unique_ptr<AsyncHandleBundleContext> callbackPtr {asyncCallbackInfo};
2697             napi_value result[1] = { 0 };
2698             // set error code
2699             if (asyncCallbackInfo->err) {
2700                 NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, asyncCallbackInfo->err, &result[0]));
2701             } else {
2702                 if (!asyncCallbackInfo->ret) {
2703                     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, OPERATION_FAILED, &result[0]));
2704                 } else {
2705                     if (asyncCallbackInfo->cleanCacheCallback) {
2706                         // wait for OnCleanCacheFinished
2707                         uv_sem_wait(&(asyncCallbackInfo->cleanCacheCallback->uvSem_));
2708                         asyncCallbackInfo->ret = asyncCallbackInfo->cleanCacheCallback->GetErr() ? false : true;
2709                         if (!asyncCallbackInfo->cleanCacheCallback->GetErr()) {
2710                             NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &result[0]));
2711                         } else {
2712                             NAPI_CALL_RETURN_VOID(env, napi_create_int32(env,
2713                                 asyncCallbackInfo->cleanCacheCallback->GetErr(), &result[0]));
2714                         }
2715                     }
2716                 }
2717             }
2718             // implement callback or promise
2719             if (asyncCallbackInfo->deferred) {
2720                 if (!asyncCallbackInfo->ret) {
2721                     NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]));
2722                 } else {
2723                     NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[0]));
2724                 }
2725             } else {
2726                 napi_value callback = nullptr;
2727                 napi_value placeHolder = nullptr;
2728                 NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callback, &callback));
2729                 NAPI_CALL_RETURN_VOID(env, napi_call_function(env, nullptr, callback,
2730                     sizeof(result) / sizeof(result[0]), result, &placeHolder));
2731             }
2732         },
2733         reinterpret_cast<void*>(asyncCallbackInfo), &asyncCallbackInfo->asyncWork));
2734     NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
2735     callbackPtr.release();
2736     return promise;
2737 }
2738 
CreateAbilityTypeObject(NativeEngine * engine)2739 NativeValue *CreateAbilityTypeObject(NativeEngine *engine)
2740 {
2741     APP_LOGD("enter");
2742 
2743     if (engine == nullptr) {
2744         APP_LOGE("Invalid input parameters");
2745         return nullptr;
2746     }
2747 
2748     NativeValue *objValue = engine->CreateObject();
2749     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
2750 
2751     if (object == nullptr) {
2752         APP_LOGE("Failed to get object");
2753         return nullptr;
2754     }
2755 
2756     object->SetProperty("UNKNOWN", CreateJsValue(*engine, static_cast<int32_t>(AbilityType::UNKNOWN)));
2757     object->SetProperty("PAGE", CreateJsValue(*engine, static_cast<int32_t>(AbilityType::PAGE)));
2758     object->SetProperty("SERVICE", CreateJsValue(*engine, static_cast<int32_t>(AbilityType::SERVICE)));
2759     object->SetProperty("DATA", CreateJsValue(*engine, static_cast<int32_t>(AbilityType::DATA)));
2760 
2761     return objValue;
2762 }
2763 
CreateAbilitySubTypeObject(NativeEngine * engine)2764 NativeValue *CreateAbilitySubTypeObject(NativeEngine *engine)
2765 {
2766     APP_LOGD("enter");
2767 
2768     if (engine == nullptr) {
2769         APP_LOGE("Invalid input parameters");
2770         return nullptr;
2771     }
2772 
2773     NativeValue *objValue = engine->CreateObject();
2774     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
2775 
2776     if (object == nullptr) {
2777         APP_LOGE("Failed to get object");
2778         return nullptr;
2779     }
2780 
2781     object->SetProperty("UNSPECIFIED", CreateJsValue(*engine, NAPI_RETURN_ZERO));
2782     object->SetProperty("CA", CreateJsValue(*engine, NAPI_RETURN_ONE));
2783 
2784     return objValue;
2785 }
2786 
CreateDisplayOrientationObject(NativeEngine * engine)2787 NativeValue *CreateDisplayOrientationObject(NativeEngine *engine)
2788 {
2789     APP_LOGD("enter");
2790 
2791     if (engine == nullptr) {
2792         APP_LOGE("Invalid input parameters");
2793         return nullptr;
2794     }
2795 
2796     NativeValue *objValue = engine->CreateObject();
2797     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
2798 
2799     if (object == nullptr) {
2800         APP_LOGE("Failed to get object");
2801         return nullptr;
2802     }
2803 
2804     object->SetProperty("UNSPECIFIED", CreateJsValue(*engine, static_cast<int32_t>(DisplayOrientation::UNSPECIFIED)));
2805     object->SetProperty("LANDSCAPE", CreateJsValue(*engine, static_cast<int32_t>(DisplayOrientation::LANDSCAPE)));
2806     object->SetProperty("PORTRAIT", CreateJsValue(*engine, static_cast<int32_t>(DisplayOrientation::PORTRAIT)));
2807     object->SetProperty(
2808         "FOLLOW_RECENT", CreateJsValue(*engine, static_cast<int32_t>(DisplayOrientation::FOLLOWRECENT)));
2809     object->SetProperty(
2810         "LANDSCAPE_INVERTED", CreateJsValue(*engine, static_cast<int32_t>(DisplayOrientation::LANDSCAPE_INVERTED)));
2811     object->SetProperty(
2812         "PORTRAIT_INVERTED", CreateJsValue(*engine, static_cast<int32_t>(DisplayOrientation::PORTRAIT_INVERTED)));
2813     object->SetProperty(
2814         "AUTO_ROTATION", CreateJsValue(*engine, static_cast<int32_t>(DisplayOrientation::AUTO_ROTATION)));
2815     object->SetProperty(
2816         "AUTO_ROTATION_LANDSCAPE", CreateJsValue(*engine,
2817             static_cast<int32_t>(DisplayOrientation::AUTO_ROTATION_LANDSCAPE)));
2818     object->SetProperty(
2819         "AUTO_ROTATION_PORTRAIT", CreateJsValue(*engine,
2820             static_cast<int32_t>(DisplayOrientation::AUTO_ROTATION_PORTRAIT)));
2821     object->SetProperty(
2822         "AUTO_ROTATION_RESTRICTED", CreateJsValue(*engine,
2823             static_cast<int32_t>(DisplayOrientation::AUTO_ROTATION_RESTRICTED)));
2824     object->SetProperty(
2825         "AUTO_ROTATION_LANDSCAPE_RESTRICTED", CreateJsValue(*engine,
2826             static_cast<int32_t>(DisplayOrientation::AUTO_ROTATION_LANDSCAPE_RESTRICTED)));
2827     object->SetProperty(
2828         "AUTO_ROTATION_PORTRAIT_RESTRICTED", CreateJsValue(*engine,
2829             static_cast<int32_t>(DisplayOrientation::AUTO_ROTATION_PORTRAIT_RESTRICTED)));
2830     object->SetProperty("LOCKED", CreateJsValue(*engine, static_cast<int32_t>(DisplayOrientation::LOCKED)));
2831     return objValue;
2832 }
2833 
CreateLaunchModeObject(NativeEngine * engine)2834 NativeValue *CreateLaunchModeObject(NativeEngine *engine)
2835 {
2836     APP_LOGD("enter");
2837 
2838     if (engine == nullptr) {
2839         APP_LOGE("Invalid input parameters");
2840         return nullptr;
2841     }
2842 
2843     NativeValue *objValue = engine->CreateObject();
2844     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
2845 
2846     if (object == nullptr) {
2847         APP_LOGE("Failed to get object");
2848         return nullptr;
2849     }
2850 
2851     object->SetProperty("SINGLETON", CreateJsValue(*engine, static_cast<int32_t>(LaunchMode::SINGLETON)));
2852     object->SetProperty("STANDARD", CreateJsValue(*engine, static_cast<int32_t>(LaunchMode::STANDARD)));
2853 
2854     return objValue;
2855 }
2856 
CreateFormTypeObject(napi_env env,napi_value value)2857 void CreateFormTypeObject(napi_env env, napi_value value)
2858 {
2859     napi_value nJava;
2860     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nJava));
2861     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "JAVA", nJava));
2862     napi_value nJs;
2863     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &nJs));
2864     NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "JS", nJs));
2865 }
2866 
CreateColorModeObject(NativeEngine * engine)2867 NativeValue *CreateColorModeObject(NativeEngine *engine)
2868 {
2869     APP_LOGD("enter");
2870 
2871     if (engine == nullptr) {
2872         APP_LOGE("Invalid input parameters");
2873         return nullptr;
2874     }
2875 
2876     NativeValue *objValue = engine->CreateObject();
2877     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
2878 
2879     if (object == nullptr) {
2880         APP_LOGE("Failed to get object");
2881         return nullptr;
2882     }
2883 
2884     object->SetProperty("AUTO_MODE", CreateJsValue(*engine, NAPI_RETURN_FAILED));
2885     object->SetProperty("DARK_MODE", CreateJsValue(*engine, NAPI_RETURN_ZERO));
2886     object->SetProperty("LIGHT_MODE", CreateJsValue(*engine, NAPI_RETURN_ONE));
2887 
2888     return objValue;
2889 }
2890 
CreateGrantStatusObject(NativeEngine * engine)2891 NativeValue *CreateGrantStatusObject(NativeEngine *engine)
2892 {
2893     APP_LOGD("enter");
2894 
2895     if (engine == nullptr) {
2896         APP_LOGE("Invalid input parameters");
2897         return nullptr;
2898     }
2899 
2900     NativeValue *objValue = engine->CreateObject();
2901     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
2902 
2903     if (object == nullptr) {
2904         APP_LOGE("Failed to get object");
2905         return nullptr;
2906     }
2907 
2908     object->SetProperty("PERMISSION_DENIED", CreateJsValue(*engine, NAPI_RETURN_FAILED));
2909     object->SetProperty("PERMISSION_GRANTED", CreateJsValue(*engine, NAPI_RETURN_ZERO));
2910 
2911     return objValue;
2912 }
2913 
CreateModuleRemoveFlagObject(NativeEngine * engine)2914 NativeValue *CreateModuleRemoveFlagObject(NativeEngine *engine)
2915 {
2916     APP_LOGD("enter");
2917 
2918     if (engine == nullptr) {
2919         APP_LOGE("Invalid input parameters");
2920         return nullptr;
2921     }
2922 
2923     NativeValue *objValue = engine->CreateObject();
2924     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
2925 
2926     if (object == nullptr) {
2927         APP_LOGE("Failed to get object");
2928         return nullptr;
2929     }
2930 
2931     object->SetProperty("FLAG_MODULE_NOT_USED_BY_FORM", CreateJsValue(*engine, NAPI_RETURN_ZERO));
2932     object->SetProperty("FLAG_MODULE_USED_BY_FORM", CreateJsValue(*engine, NAPI_RETURN_ONE));
2933     object->SetProperty("FLAG_MODULE_NOT_USED_BY_SHORTCUT", CreateJsValue(*engine, NAPI_RETURN_TWO));
2934     object->SetProperty("FLAG_MODULE_USED_BY_SHORTCUT", CreateJsValue(*engine, NAPI_RETURN_THREE));
2935 
2936     return objValue;
2937 }
2938 
CreateSignatureCompareResultObject(NativeEngine * engine)2939 NativeValue *CreateSignatureCompareResultObject(NativeEngine *engine)
2940 {
2941     APP_LOGD("enter");
2942 
2943     if (engine == nullptr) {
2944         APP_LOGE("Invalid input parameters");
2945         return nullptr;
2946     }
2947 
2948     NativeValue *objValue = engine->CreateObject();
2949     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
2950 
2951     if (object == nullptr) {
2952         APP_LOGE("Failed to get object");
2953         return nullptr;
2954     }
2955 
2956     object->SetProperty("SIGNATURE_MATCHED", CreateJsValue(*engine, NAPI_RETURN_ZERO));
2957     object->SetProperty("SIGNATURE_NOT_MATCHED", CreateJsValue(*engine, NAPI_RETURN_ONE));
2958     object->SetProperty("SIGNATURE_UNKNOWN_BUNDLE", CreateJsValue(*engine, NAPI_RETURN_TWO));
2959 
2960     return objValue;
2961 }
2962 
CreateShortcutExistenceObject(NativeEngine * engine)2963 NativeValue *CreateShortcutExistenceObject(NativeEngine *engine)
2964 {
2965     APP_LOGD("enter");
2966 
2967     if (engine == nullptr) {
2968         APP_LOGE("Invalid input parameters");
2969         return nullptr;
2970     }
2971 
2972     NativeValue *objValue = engine->CreateObject();
2973     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
2974 
2975     if (object == nullptr) {
2976         APP_LOGE("Failed to get object");
2977         return nullptr;
2978     }
2979 
2980     object->SetProperty("SHORTCUT_EXISTENCE_EXISTS", CreateJsValue(*engine, NAPI_RETURN_ZERO));
2981     object->SetProperty("SHORTCUT_EXISTENCE_NOT_EXISTS", CreateJsValue(*engine, NAPI_RETURN_ONE));
2982     object->SetProperty("SHORTCUT_EXISTENCE_UNKNOW", CreateJsValue(*engine, NAPI_RETURN_TWO));
2983 
2984     return objValue;
2985 }
2986 
CreateQueryShortCutFlagObject(NativeEngine * engine)2987 NativeValue *CreateQueryShortCutFlagObject(NativeEngine *engine)
2988 {
2989     APP_LOGD("enter");
2990 
2991     if (engine == nullptr) {
2992         APP_LOGE("Invalid input parameters");
2993         return nullptr;
2994     }
2995 
2996     NativeValue *objValue = engine->CreateObject();
2997     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
2998 
2999     if (object == nullptr) {
3000         APP_LOGE("Failed to get object");
3001         return nullptr;
3002     }
3003 
3004     object->SetProperty("QUERY_SHORTCUT_HOME", CreateJsValue(*engine, NAPI_RETURN_ZERO));
3005 
3006     return objValue;
3007 }
3008 
CreateBundleFlagObject(NativeEngine * engine)3009 NativeValue *CreateBundleFlagObject(NativeEngine *engine)
3010 {
3011     APP_LOGD("enter");
3012 
3013     if (engine == nullptr) {
3014         APP_LOGE("Invalid input parameters");
3015         return nullptr;
3016     }
3017 
3018     NativeValue *objValue = engine->CreateObject();
3019     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
3020 
3021     if (object == nullptr) {
3022         APP_LOGE("Failed to get object");
3023         return nullptr;
3024     }
3025 
3026     object->SetProperty(
3027         "GET_ALL_APPLICATION_INFO", CreateJsValue(*engine,
3028             static_cast<int32_t>(ApplicationFlag::GET_ALL_APPLICATION_INFO)));
3029     object->SetProperty(
3030         "GET_BUNDLE_DEFAULT", CreateJsValue(*engine, static_cast<int32_t>(BundleFlag::GET_BUNDLE_DEFAULT)));
3031     object->SetProperty(
3032         "GET_BUNDLE_WITH_ABILITIES", CreateJsValue(*engine,
3033             static_cast<int32_t>(BundleFlag::GET_BUNDLE_WITH_ABILITIES)));
3034     object->SetProperty(
3035         "GET_BUNDLE_WITH_REQUESTED_PERMISSION", CreateJsValue(*engine,
3036             static_cast<int32_t>(BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION)));
3037     object->SetProperty(
3038         "GET_ABILITY_INFO_WITH_PERMISSION", CreateJsValue(*engine,
3039             static_cast<int32_t>(AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION)));
3040     object->SetProperty(
3041         "GET_ABILITY_INFO_WITH_APPLICATION", CreateJsValue(*engine,
3042             static_cast<int32_t>(AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION)));
3043     object->SetProperty(
3044         "GET_ABILITY_INFO_SYSTEMAPP_ONLY", CreateJsValue(*engine,
3045             static_cast<int32_t>(AbilityInfoFlag::GET_ABILITY_INFO_SYSTEMAPP_ONLY)));
3046     object->SetProperty(
3047         "GET_ABILITY_INFO_WITH_METADATA", CreateJsValue(*engine,
3048             static_cast<int32_t>(AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA)));
3049     object->SetProperty(
3050         "GET_BUNDLE_WITH_HASH_VALUE", CreateJsValue(*engine,
3051             static_cast<int32_t>(BundleFlag::GET_BUNDLE_WITH_HASH_VALUE)));
3052     object->SetProperty(
3053         "GET_ABILITY_INFO_WITH_DISABLE", CreateJsValue(*engine,
3054             static_cast<int32_t>(AbilityInfoFlag::GET_ABILITY_INFO_WITH_DISABLE)));
3055     object->SetProperty(
3056         "GET_APPLICATION_INFO_WITH_PERMISSION", CreateJsValue(*engine,
3057             static_cast<int32_t>(ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMISSION)));
3058     object->SetProperty(
3059         "GET_APPLICATION_INFO_WITH_METADATA", CreateJsValue(*engine,
3060             static_cast<int32_t>(ApplicationFlag::GET_APPLICATION_INFO_WITH_METADATA)));
3061     object->SetProperty(
3062         "GET_APPLICATION_INFO_WITH_DISABLE", CreateJsValue(*engine,
3063             static_cast<int32_t>(ApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE)));
3064     object->SetProperty(
3065         "GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT", CreateJsValue(*engine,
3066             static_cast<int32_t>(ApplicationFlag::GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT)));
3067 
3068     return objValue;
3069 }
3070 
CreateInstallErrorCodeObject(NativeEngine * engine)3071 NativeValue *CreateInstallErrorCodeObject(NativeEngine *engine)
3072 {
3073     APP_LOGD("enter");
3074 
3075     if (engine == nullptr) {
3076         APP_LOGE("Invalid input parameters");
3077         return nullptr;
3078     }
3079 
3080     NativeValue *objValue = engine->CreateObject();
3081     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
3082 
3083     if (object == nullptr) {
3084         APP_LOGE("Failed to get object");
3085         return nullptr;
3086     }
3087 
3088     object->SetProperty("SUCCESS", CreateJsValue(*engine, static_cast<int32_t>(InstallErrorCode::SUCCESS)));
3089     object->SetProperty(
3090         "STATUS_INSTALL_FAILURE", CreateJsValue(*engine,
3091             static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE)));
3092     object->SetProperty(
3093         "STATUS_INSTALL_FAILURE_ABORTED", CreateJsValue(*engine,
3094             static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_ABORTED)));
3095     object->SetProperty(
3096         "STATUS_INSTALL_FAILURE_INVALID", CreateJsValue(*engine,
3097             static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_INVALID)));
3098     object->SetProperty(
3099         "STATUS_INSTALL_FAILURE_CONFLICT", CreateJsValue(*engine,
3100             static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_CONFLICT)));
3101     object->SetProperty(
3102         "STATUS_INSTALL_FAILURE_STORAGE", CreateJsValue(*engine,
3103             static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_STORAGE)));
3104     object->SetProperty(
3105         "STATUS_INSTALL_FAILURE_INCOMPATIBLE", CreateJsValue(*engine,
3106             static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_INCOMPATIBLE)));
3107     object->SetProperty(
3108         "STATUS_UNINSTALL_FAILURE", CreateJsValue(*engine,
3109             static_cast<int32_t>(InstallErrorCode::STATUS_UNINSTALL_FAILURE)));
3110     object->SetProperty(
3111         "STATUS_UNINSTALL_FAILURE_BLOCKED", CreateJsValue(*engine,
3112             static_cast<int32_t>(InstallErrorCode::STATUS_UNINSTALL_FAILURE_BLOCKED)));
3113     object->SetProperty(
3114         "STATUS_UNINSTALL_FAILURE_ABORTED", CreateJsValue(*engine,
3115             static_cast<int32_t>(InstallErrorCode::STATUS_UNINSTALL_FAILURE_ABORTED)));
3116     object->SetProperty(
3117         "STATUS_UNINSTALL_FAILURE_CONFLICT", CreateJsValue(*engine,
3118             static_cast<int32_t>(InstallErrorCode::STATUS_UNINSTALL_FAILURE_CONFLICT)));
3119     object->SetProperty(
3120         "STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT", CreateJsValue(*engine,
3121             static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT)));
3122     object->SetProperty(
3123         "STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED", CreateJsValue(*engine,
3124             static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED)));
3125     object->SetProperty(
3126         "STATUS_ABILITY_NOT_FOUND", CreateJsValue(*engine,
3127             static_cast<int32_t>(InstallErrorCode::STATUS_ABILITY_NOT_FOUND)));
3128     object->SetProperty(
3129         "STATUS_BMS_SERVICE_ERROR", CreateJsValue(*engine,
3130             static_cast<int32_t>(InstallErrorCode::STATUS_BMS_SERVICE_ERROR)));
3131     object->SetProperty(
3132         "STATUS_GRANT_REQUEST_PERMISSIONS_FAILED", CreateJsValue(*engine,
3133             static_cast<int32_t>(InstallErrorCode::STATUS_GRANT_REQUEST_PERMISSIONS_FAILED)));
3134     object->SetProperty(
3135         "STATUS_INSTALL_PERMISSION_DENIED", CreateJsValue(*engine,
3136             static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_PERMISSION_DENIED)));
3137     object->SetProperty(
3138         "STATUS_UNINSTALL_PERMISSION_DENIED", CreateJsValue(*engine,
3139             static_cast<int32_t>(InstallErrorCode::STATUS_UNINSTALL_PERMISSION_DENIED)));
3140     object->SetProperty(
3141         "STATUS_FAILED_NO_SPACE_LEFT", CreateJsValue(*engine,
3142             static_cast<int32_t>(InstallErrorCode::STATUS_FAILED_NO_SPACE_LEFT)));
3143     object->SetProperty(
3144         "STATUS_RECOVER_FAILURE_INVALID", CreateJsValue(*engine,
3145             static_cast<int32_t>(InstallErrorCode::STATUS_RECOVER_FAILURE_INVALID)));
3146 
3147     return objValue;
3148 }
3149 
InnerGetApplicationInfo(const std::string & bundleName,int32_t flags,const int userId,ApplicationInfo & appInfo)3150 static bool InnerGetApplicationInfo(
3151     const std::string &bundleName, int32_t flags, const int userId, ApplicationInfo &appInfo)
3152 {
3153     auto iBundleMgr = GetBundleMgr();
3154     if (!iBundleMgr) {
3155         APP_LOGE("can not get iBundleMgr");
3156         return false;
3157     }
3158     return iBundleMgr->GetApplicationInfo(bundleName, flags, userId, appInfo);
3159 }
3160 
InnerGetApplicationInfos(int32_t flags,const int userId,std::vector<OHOS::AppExecFwk::ApplicationInfo> & appInfos)3161 static bool InnerGetApplicationInfos(
3162     int32_t flags, const int userId, std::vector<OHOS::AppExecFwk::ApplicationInfo> &appInfos)
3163 {
3164     auto iBundleMgr = GetBundleMgr();
3165     if (iBundleMgr == nullptr) {
3166         APP_LOGE("can not get iBundleMgr");
3167         return false;
3168     }
3169     return iBundleMgr->GetApplicationInfos(flags, userId, appInfos);
3170 }
3171 
InnerGetLaunchWantForBundle(const std::string & bundleName,Want & want)3172 static bool InnerGetLaunchWantForBundle(const std::string &bundleName, Want &want)
3173 {
3174     auto iBundleMgr = GetBundleMgr();
3175     if (iBundleMgr == nullptr) {
3176         APP_LOGE("can not get iBundleMgr");
3177         return false;
3178     }
3179 
3180     ErrCode ret = iBundleMgr->GetLaunchWantForBundle(bundleName, want);
3181     if (ret != ERR_OK) {
3182         APP_LOGE("launchWantForBundle is not find");
3183         return false;
3184     }
3185 
3186     return true;
3187 }
3188 
InnerGetArchiveInfo(const std::string & hapFilePath,const int32_t flags,BundleInfo & bundleInfo)3189 static bool InnerGetArchiveInfo(const std::string &hapFilePath, const int32_t flags, BundleInfo &bundleInfo)
3190 {
3191     auto iBundleMgr = GetBundleMgr();
3192     if (iBundleMgr == nullptr) {
3193         APP_LOGE("can not get iBundleMgr");
3194         return false;
3195     };
3196     bool ret = iBundleMgr->GetBundleArchiveInfo(hapFilePath, flags, bundleInfo);
3197     if (!ret) {
3198         APP_LOGE("ArchiveInfo not found");
3199     }
3200     return ret;
3201 }
3202 
CreateModuleInfos(NativeEngine & engine,const std::vector<ModuleInfo> & moduleInfos)3203 NativeValue* JsBundleMgr::CreateModuleInfos(NativeEngine &engine, const std::vector<ModuleInfo> &moduleInfos)
3204 {
3205     APP_LOGD("CreateModuleInfos is called.");
3206     NativeValue *arrayValue = engine.CreateArray(moduleInfos.size());
3207     NativeArray *array = ConvertNativeValueTo<NativeArray>(arrayValue);
3208     for (uint32_t i = 0; i < moduleInfos.size(); i++) {
3209         array->SetElement(i, CreateModuleInfo(engine, moduleInfos.at(i)));
3210     }
3211     return arrayValue;
3212 }
3213 
CreateCustomizeMetaDatas(NativeEngine & engine,const std::map<std::string,std::vector<CustomizeData>> & metaData)3214 NativeValue* JsBundleMgr::CreateCustomizeMetaDatas(
3215     NativeEngine &engine, const std::map<std::string, std::vector<CustomizeData>> &metaData)
3216 {
3217     APP_LOGD("CreateCustomizeMetaDatas is called.");
3218     NativeValue *objValue = engine.CreateObject();
3219     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
3220     for (const auto &item : metaData) {
3221         NativeValue *arrayValue = engine.CreateArray(item.second.size());
3222         NativeArray *array = ConvertNativeValueTo<NativeArray>(arrayValue);
3223         for (size_t i = 0; i < item.second.size(); i++) {
3224             array->SetElement(i, CreateCustomizeMetaData(engine, item.second[i]));
3225         }
3226         object->SetProperty(item.first.c_str(), arrayValue);
3227     }
3228     return objValue;
3229 }
3230 
CreateInnerMetaDatas(NativeEngine & engine,const std::map<std::string,std::vector<Metadata>> & metaData)3231 NativeValue* JsBundleMgr::CreateInnerMetaDatas(
3232     NativeEngine &engine, const std::map<std::string, std::vector<Metadata>> &metaData)
3233 {
3234     APP_LOGD("CreateInnerMetaDatas is called.");
3235     NativeValue *objValue = engine.CreateObject();
3236     NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
3237     for (const auto &item : metaData) {
3238         NativeValue *arrayValue = engine.CreateArray(item.second.size());
3239         NativeArray *array = ConvertNativeValueTo<NativeArray>(arrayValue);
3240         for (size_t i = 0; i < item.second.size(); i++) {
3241             array->SetElement(i, CreateInnerMetaData(engine, item.second[i]));
3242         }
3243         object->SetProperty(item.first.c_str(), arrayValue);
3244     }
3245     return objValue;
3246 }
3247 
CreateInnerMetaDatas(NativeEngine & engine,const std::vector<Metadata> & metaData)3248 NativeValue* JsBundleMgr::CreateInnerMetaDatas(NativeEngine &engine, const std::vector<Metadata> &metaData)
3249 {
3250     APP_LOGD("CreateInnerMetaDatas is called.");
3251     NativeValue *arrayValue = engine.CreateArray(metaData.size());
3252     NativeArray *array = ConvertNativeValueTo<NativeArray>(arrayValue);
3253     for (size_t i = 0; i < metaData.size(); i++) {
3254         array->SetElement(i, CreateInnerMetaData(engine, metaData[i]));
3255     }
3256     return arrayValue;
3257 }
3258 
CreateCustomizeMetaData(NativeEngine & engine,const CustomizeData & customizeData)3259 NativeValue* JsBundleMgr::CreateCustomizeMetaData(NativeEngine &engine, const CustomizeData &customizeData)
3260 {
3261     APP_LOGD("CreateCustomizeMetaData is called.");
3262     auto objContext = engine.CreateObject();
3263     if (objContext == nullptr) {
3264         APP_LOGE("CreateObject failed");
3265         return engine.CreateUndefined();
3266     }
3267 
3268     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3269     if (object == nullptr) {
3270         APP_LOGE("ConvertNativeValueTo object failed");
3271         return engine.CreateUndefined();
3272     }
3273 
3274     object->SetProperty("name", CreateJsValue(engine, customizeData.name));
3275     object->SetProperty("value", CreateJsValue(engine, customizeData.value));
3276     object->SetProperty("extra", CreateJsValue(engine, customizeData.extra));
3277     return objContext;
3278 }
3279 
CreateInnerMetaData(NativeEngine & engine,const Metadata & metadata)3280 NativeValue* JsBundleMgr::CreateInnerMetaData(NativeEngine &engine, const Metadata &metadata)
3281 {
3282     APP_LOGD("CreateInnerMetaData is called.");
3283     auto objContext = engine.CreateObject();
3284     if (objContext == nullptr) {
3285         APP_LOGE("CreateObject failed");
3286         return engine.CreateUndefined();
3287     }
3288 
3289     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3290     if (object == nullptr) {
3291         APP_LOGE("ConvertNativeValueTo object failed");
3292         return engine.CreateUndefined();
3293     }
3294 
3295     object->SetProperty("name", CreateJsValue(engine, metadata.name));
3296     object->SetProperty("value", CreateJsValue(engine, metadata.value));
3297     object->SetProperty("resource", CreateJsValue(engine, metadata.resource));
3298     return objContext;
3299 }
3300 
CreateModuleInfo(NativeEngine & engine,const ModuleInfo & modInfo)3301 NativeValue* JsBundleMgr::CreateModuleInfo(NativeEngine &engine, const ModuleInfo &modInfo)
3302 {
3303     APP_LOGD("CreateModuleInfo is called.");
3304     auto objContext = engine.CreateObject();
3305     if (objContext == nullptr) {
3306         APP_LOGE("CreateObject failed");
3307         return engine.CreateUndefined();
3308     }
3309 
3310     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3311     if (object == nullptr) {
3312         APP_LOGE("ConvertNativeValueTo object failed");
3313         return engine.CreateUndefined();
3314     }
3315 
3316     object->SetProperty("moduleName", CreateJsValue(engine, modInfo.moduleName));
3317     object->SetProperty("moduleSourceDir", CreateJsValue(engine, modInfo.moduleSourceDir));
3318 
3319     return objContext;
3320 }
3321 
CreateResource(NativeEngine & engine,const Resource & resource)3322 NativeValue* JsBundleMgr::CreateResource(NativeEngine &engine, const Resource &resource)
3323 {
3324     APP_LOGD("CreateResource is called.");
3325     auto objContext = engine.CreateObject();
3326     if (objContext == nullptr) {
3327         APP_LOGE("CreateObject failed");
3328         return engine.CreateUndefined();
3329     }
3330 
3331     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3332     if (object == nullptr) {
3333         APP_LOGE("ConvertNativeValueTo object failed");
3334         return engine.CreateUndefined();
3335     }
3336 
3337     object->SetProperty("bundleName", CreateJsValue(engine, resource.bundleName));
3338     object->SetProperty("moduleName", CreateJsValue(engine, resource.moduleName));
3339     object->SetProperty("id", CreateJsValue(engine, resource.id));
3340     return objContext;
3341 }
3342 
CreateAppInfo(NativeEngine & engine,const ApplicationInfo & appInfo)3343 NativeValue* JsBundleMgr::CreateAppInfo(NativeEngine &engine, const ApplicationInfo &appInfo)
3344 {
3345     APP_LOGD("CreateAppInfo is called.");
3346     auto objContext = engine.CreateObject();
3347     if (objContext == nullptr) {
3348         APP_LOGE("CreateObject failed");
3349         return engine.CreateUndefined();
3350     }
3351 
3352     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3353     if (object == nullptr) {
3354         APP_LOGE("ConvertNativeValueTo object failed");
3355         return engine.CreateUndefined();
3356     }
3357 
3358     object->SetProperty("name", CreateJsValue(engine, appInfo.name));
3359     object->SetProperty("codePath", CreateJsValue(engine, appInfo.codePath));
3360     object->SetProperty("accessTokenId", CreateJsValue(engine, appInfo.accessTokenId));
3361     object->SetProperty("description", CreateJsValue(engine, appInfo.description));
3362     object->SetProperty("descriptionId", CreateJsValue(engine, appInfo.descriptionId));
3363     object->SetProperty("icon", CreateJsValue(engine, appInfo.iconPath));
3364     object->SetProperty("iconId", CreateJsValue(engine, appInfo.iconId));
3365     object->SetProperty("label", CreateJsValue(engine, appInfo.label));
3366     object->SetProperty("labelId", CreateJsValue(engine, appInfo.labelId));
3367     object->SetProperty("systemApp", CreateJsValue(engine, appInfo.isSystemApp));
3368     object->SetProperty("supportedModes", CreateJsValue(engine, appInfo.supportedModes));
3369     object->SetProperty("process", CreateJsValue(engine, appInfo.process));
3370     object->SetProperty("iconIndex", CreateJsValue(engine, appInfo.iconId));
3371     object->SetProperty("labelIndex", CreateJsValue(engine, appInfo.labelId));
3372     object->SetProperty("entryDir", CreateJsValue(engine, appInfo.entryDir));
3373     object->SetProperty("permissions", CreateNativeArray(engine, appInfo.permissions));
3374     object->SetProperty("moduleSourceDirs", CreateNativeArray(engine, appInfo.moduleSourceDirs));
3375     object->SetProperty("moduleInfos", CreateModuleInfos(engine, appInfo.moduleInfos));
3376     object->SetProperty("metaData", CreateCustomizeMetaDatas(engine, appInfo.metaData));
3377     object->SetProperty("metadata", CreateInnerMetaDatas(engine, appInfo.metadata));
3378     object->SetProperty("enabled", CreateJsValue(engine, appInfo.enabled));
3379     object->SetProperty("uid", CreateJsValue(engine, appInfo.uid));
3380     object->SetProperty("entityType", CreateJsValue(engine, appInfo.entityType));
3381     object->SetProperty("removable", CreateJsValue(engine, appInfo.removable));
3382     object->SetProperty("fingerprint", CreateJsValue(engine, appInfo.fingerprint));
3383     object->SetProperty("iconResource", CreateResource(engine, appInfo.iconResource));
3384     object->SetProperty("labelResource", CreateResource(engine, appInfo.labelResource));
3385     object->SetProperty("descriptionResource", CreateResource(engine, appInfo.descriptionResource));
3386     object->SetProperty("appDistributionType", CreateJsValue(engine, appInfo.appDistributionType));
3387     object->SetProperty("appProvisionType", CreateJsValue(engine, appInfo.appProvisionType));
3388     return objContext;
3389 }
3390 
CreateAbilityInfo(NativeEngine & engine,const AbilityInfo & abilityInfo)3391 NativeValue* JsBundleMgr::CreateAbilityInfo(NativeEngine &engine, const AbilityInfo &abilityInfo)
3392 {
3393     APP_LOGD("CreateAbilityInfo is called.");
3394     auto objContext = engine.CreateObject();
3395     if (objContext == nullptr) {
3396         APP_LOGE("CreateObject failed");
3397         return engine.CreateUndefined();
3398     }
3399 
3400     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3401     if (object == nullptr) {
3402         APP_LOGE("ConvertNativeValueTo object failed");
3403         return engine.CreateUndefined();
3404     }
3405 
3406     object->SetProperty("name", CreateJsValue(engine, abilityInfo.name));
3407     object->SetProperty("label", CreateJsValue(engine, abilityInfo.label));
3408     object->SetProperty("description", CreateJsValue(engine, abilityInfo.description));
3409     object->SetProperty("icon", CreateJsValue(engine, abilityInfo.iconPath));
3410     object->SetProperty("isVisible", CreateJsValue(engine, abilityInfo.visible));
3411     object->SetProperty("permissions", CreateNativeArray(engine, abilityInfo.permissions));
3412     object->SetProperty("deviceCapabilities", CreateNativeArray(engine, abilityInfo.deviceCapabilities));
3413     object->SetProperty("deviceTypes", CreateNativeArray(engine, abilityInfo.deviceTypes));
3414     object->SetProperty("process", CreateJsValue(engine, abilityInfo.process));
3415     object->SetProperty("uri", CreateJsValue(engine, abilityInfo.uri));
3416     object->SetProperty("bundleName", CreateJsValue(engine, abilityInfo.bundleName));
3417     object->SetProperty("moduleName", CreateJsValue(engine, abilityInfo.moduleName));
3418     object->SetProperty("applicationInfo", CreateAppInfo(engine, abilityInfo.applicationInfo));
3419     object->SetProperty("type", CreateJsValue(engine, static_cast<int32_t>(abilityInfo.type)));
3420     object->SetProperty("orientation", CreateJsValue(engine, static_cast<int32_t>(abilityInfo.orientation)));
3421     object->SetProperty("launchMode", CreateJsValue(engine, static_cast<int32_t>(abilityInfo.launchMode)));
3422 
3423     if (!abilityInfo.isModuleJson) {
3424         object->SetProperty("backgroundModes", CreateJsValue(engine, abilityInfo.backgroundModes));
3425     } else {
3426         object->SetProperty("backgroundModes", CreateJsValue(engine, 0));
3427     }
3428 
3429     object->SetProperty("descriptionId", CreateJsValue(engine, abilityInfo.descriptionId));
3430     object->SetProperty("formEnabled", CreateJsValue(engine, abilityInfo.formEnabled));
3431     object->SetProperty("iconId", CreateJsValue(engine, abilityInfo.iconId));
3432     object->SetProperty("labelId", CreateJsValue(engine, abilityInfo.labelId));
3433     object->SetProperty("subType", CreateJsValue(engine, static_cast<int32_t>(abilityInfo.subType)));
3434     object->SetProperty("readPermission", CreateJsValue(engine, abilityInfo.readPermission));
3435     object->SetProperty("writePermission", CreateJsValue(engine, abilityInfo.writePermission));
3436     object->SetProperty("targetAbility", CreateJsValue(engine, abilityInfo.targetAbility));
3437     object->SetProperty("metaData", CreateMetaData(engine, abilityInfo.metaData));
3438     object->SetProperty("metadata", CreateInnerMetaDatas(engine, abilityInfo.metadata));
3439     object->SetProperty("enabled", CreateJsValue(engine, abilityInfo.enabled));
3440     object->SetProperty("maxWindowRatio", CreateJsValue(engine, abilityInfo.maxWindowRatio));
3441     object->SetProperty("minWindowRatio", CreateJsValue(engine, abilityInfo.minWindowRatio));
3442     object->SetProperty("maxWindowWidth", CreateJsValue(engine, abilityInfo.maxWindowWidth));
3443     object->SetProperty("minWindowWidth", CreateJsValue(engine, abilityInfo.minWindowWidth));
3444     object->SetProperty("maxWindowHeight", CreateJsValue(engine, abilityInfo.maxWindowHeight));
3445     object->SetProperty("minWindowHeight", CreateJsValue(engine, abilityInfo.minWindowHeight));
3446 
3447     return objContext;
3448 }
3449 
CreateMetaData(NativeEngine & engine,const MetaData & metaData)3450 NativeValue* JsBundleMgr::CreateMetaData(NativeEngine &engine, const MetaData &metaData)
3451 {
3452     APP_LOGD("CreateMetaData is called.");
3453     NativeValue *arrayValue = engine.CreateArray(metaData.customizeData.size());
3454     NativeArray *array = ConvertNativeValueTo<NativeArray>(arrayValue);
3455     for (size_t i = 0; i < metaData.customizeData.size(); i++) {
3456         array->SetElement(i, CreateCustomizeMetaData(engine, metaData.customizeData[i]));
3457     }
3458     return arrayValue;
3459 }
3460 
CreateAbilityInfos(NativeEngine & engine,const std::vector<AbilityInfo> & abilityInfos)3461 NativeValue* JsBundleMgr::CreateAbilityInfos(NativeEngine &engine,  const std::vector<AbilityInfo> &abilityInfos)
3462 {
3463     NativeValue* arrayValue = engine.CreateArray(abilityInfos.size());
3464     NativeArray* array = ConvertNativeValueTo<NativeArray>(arrayValue);
3465     uint32_t index = 0;
3466     for (const auto &abilityInfo : abilityInfos) {
3467         array->SetElement(index++, CreateAbilityInfo(engine, abilityInfo));
3468     }
3469     return arrayValue;
3470 }
3471 
CreateRequestPermissions(NativeEngine & engine,const std::vector<RequestPermission> & requestPermissions)3472 NativeValue *JsBundleMgr::CreateRequestPermissions(
3473     NativeEngine &engine, const std::vector<RequestPermission> &requestPermissions)
3474 {
3475     NativeValue* arrayValue = engine.CreateArray(requestPermissions.size());
3476     NativeArray* array = ConvertNativeValueTo<NativeArray>(arrayValue);
3477     uint32_t index = 0;
3478     for (const auto &requestPermission : requestPermissions) {
3479         array->SetElement(index++, CreateRequestPermission(engine, requestPermission));
3480     }
3481     return arrayValue;
3482 }
3483 
CreateRequestPermission(NativeEngine & engine,const RequestPermission & requestPermission)3484 NativeValue* JsBundleMgr::CreateRequestPermission(NativeEngine &engine, const RequestPermission &requestPermission)
3485 {
3486     APP_LOGD("CreateRequestPermission is called");
3487     auto objContext = engine.CreateObject();
3488     if (objContext == nullptr) {
3489         APP_LOGE("CreateObject failed");
3490         return engine.CreateUndefined();
3491     }
3492 
3493     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3494     if (object == nullptr) {
3495         APP_LOGE("ConvertNativeValueTo object failed");
3496         return engine.CreateUndefined();
3497     }
3498 
3499     object->SetProperty("name", CreateJsValue(engine, requestPermission.name));
3500     object->SetProperty("reason", CreateJsValue(engine, requestPermission.reason));
3501     object->SetProperty("reasonId", CreateJsValue(engine, requestPermission.reasonId));
3502     object->SetProperty("usedScene", CreateUsedScene(engine, requestPermission.usedScene));
3503 
3504     return objContext;
3505 }
3506 
CreateUsedScene(NativeEngine & engine,const RequestPermissionUsedScene & usedScene)3507 NativeValue* JsBundleMgr::CreateUsedScene(NativeEngine &engine, const RequestPermissionUsedScene &usedScene)
3508 {
3509     APP_LOGD("CreateUsedScene is called");
3510     auto objContext = engine.CreateObject();
3511     if (objContext == nullptr) {
3512         APP_LOGE("CreateObject failed");
3513         return engine.CreateUndefined();
3514     }
3515 
3516     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3517     if (object == nullptr) {
3518         APP_LOGE("ConvertNativeValueTo object failed");
3519         return engine.CreateUndefined();
3520     }
3521 
3522     object->SetProperty("abilities", CreateNativeArray(engine, usedScene.abilities));
3523     object->SetProperty("when", CreateJsValue(engine, usedScene.when));
3524 
3525     return objContext;
3526 }
3527 
CreateBundleInfo(NativeEngine & engine,const BundleInfo & bundleInfo)3528 NativeValue* JsBundleMgr::CreateBundleInfo(NativeEngine &engine, const BundleInfo &bundleInfo)
3529 {
3530     APP_LOGD("called");
3531     auto objContext = engine.CreateObject();
3532     if (objContext == nullptr) {
3533         APP_LOGE("CreateObject failed");
3534         return engine.CreateUndefined();
3535     }
3536 
3537     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3538     if (object == nullptr) {
3539         APP_LOGE("ConvertNativeValueTo object failed");
3540         return engine.CreateUndefined();
3541     }
3542 
3543     object->SetProperty("name", CreateJsValue(engine, bundleInfo.name));
3544     object->SetProperty("vendor", CreateJsValue(engine, bundleInfo.vendor));
3545     object->SetProperty("versionCode", CreateJsValue(engine, bundleInfo.versionCode));
3546     object->SetProperty("versionName", CreateJsValue(engine, bundleInfo.versionName));
3547     object->SetProperty("cpuAbi", CreateJsValue(engine, bundleInfo.cpuAbi));
3548     object->SetProperty("appId", CreateJsValue(engine, bundleInfo.appId));
3549     object->SetProperty("entryModuleName", CreateJsValue(engine, bundleInfo.entryModuleName));
3550     object->SetProperty("compatibleVersion", CreateJsValue(engine, bundleInfo.compatibleVersion));
3551     object->SetProperty("targetVersion", CreateJsValue(engine, bundleInfo.targetVersion));
3552     object->SetProperty("uid", CreateJsValue(engine, bundleInfo.uid));
3553     object->SetProperty("installTime", CreateJsValue(engine, bundleInfo.installTime));
3554     object->SetProperty("updateTime", CreateJsValue(engine, bundleInfo.updateTime));
3555     object->SetProperty("appInfo", CreateAppInfo(engine, bundleInfo.applicationInfo));
3556     object->SetProperty("abilityInfos", CreateAbilityInfos(engine, bundleInfo.abilityInfos));
3557     object->SetProperty("hapModuleInfos", CreateHapModuleInfos(engine, bundleInfo.hapModuleInfos));
3558     object->SetProperty("reqPermissions", CreateNativeArray(engine, bundleInfo.reqPermissions));
3559     object->SetProperty("reqPermissionStates", CreateNativeArray(engine, bundleInfo.reqPermissionStates));
3560     object->SetProperty("isCompressNativeLibs", CreateJsValue(engine, bundleInfo.applicationInfo.isCompressNativeLibs));
3561     object->SetProperty("isSilentInstallation", CreateJsValue(engine, std::string("")));
3562     auto typeValue = CreateJsValue(engine, "");
3563     if (typeValue->TypeOf() == NativeValueType::NATIVE_UNDEFINED) {
3564         APP_LOGE("ConvertNativeValueTo typeValue->TypeOf is UNDEFINE");
3565         auto jsValue =  CreateJsValue(engine, std::string(""));
3566         if (jsValue->TypeOf() == NativeValueType::NATIVE_UNDEFINED) {
3567             APP_LOGE("ConvertNativeValueTo typeValueStr->TypeOf is UNDEFINE");
3568         }
3569     }
3570     object->SetProperty("type", CreateJsValue(engine, std::string("")));
3571     object->SetProperty("reqPermissionDetails", CreateRequestPermissions(engine, bundleInfo.reqPermissionDetails));
3572     object->SetProperty("minCompatibleVersionCode", CreateJsValue(engine, bundleInfo.minCompatibleVersionCode));
3573     object->SetProperty("entryInstallationFree", CreateJsValue(engine, bundleInfo.entryInstallationFree));
3574 
3575     return objContext;
3576 }
3577 
CreateHapModuleInfos(NativeEngine & engine,const std::vector<HapModuleInfo> & hapModuleInfos)3578 NativeValue* JsBundleMgr::CreateHapModuleInfos(NativeEngine &engine, const std::vector<HapModuleInfo> &hapModuleInfos)
3579 {
3580     NativeValue* arrayValue = engine.CreateArray(hapModuleInfos.size());
3581     NativeArray* array = ConvertNativeValueTo<NativeArray>(arrayValue);
3582     uint32_t index = 0;
3583     for (const auto &hapModuleInfo : hapModuleInfos) {
3584         array->SetElement(index++, CreateHapModuleInfo(engine, hapModuleInfo));
3585     }
3586     return arrayValue;
3587 }
3588 
CreateHapModuleInfo(NativeEngine & engine,const HapModuleInfo & hapModuleInfo)3589 NativeValue* JsBundleMgr::CreateHapModuleInfo(NativeEngine &engine, const HapModuleInfo &hapModuleInfo)
3590 {
3591     APP_LOGD("CreateHapModuleInfo is called");
3592     auto objContext = engine.CreateObject();
3593     if (objContext == nullptr) {
3594         APP_LOGE("CreateObject failed");
3595         return engine.CreateUndefined();
3596     }
3597 
3598     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3599     if (object == nullptr) {
3600         APP_LOGE("ConvertNativeValueTo object failed");
3601         return engine.CreateUndefined();
3602     }
3603 
3604     object->SetProperty("name", CreateJsValue(engine, hapModuleInfo.name));
3605     object->SetProperty("moduleName", CreateJsValue(engine, hapModuleInfo.moduleName));
3606     object->SetProperty("description", CreateJsValue(engine, hapModuleInfo.description));
3607     object->SetProperty("descriptionId", CreateJsValue(engine, hapModuleInfo.descriptionId));
3608     object->SetProperty("icon", CreateJsValue(engine, hapModuleInfo.iconPath));
3609     object->SetProperty("label", CreateJsValue(engine, hapModuleInfo.label));
3610     object->SetProperty("hashValue", CreateJsValue(engine, hapModuleInfo.hashValue));
3611     object->SetProperty("labelId", CreateJsValue(engine, hapModuleInfo.labelId));
3612     object->SetProperty("iconId", CreateJsValue(engine, hapModuleInfo.iconId));
3613     object->SetProperty("backgroundImg", CreateJsValue(engine, hapModuleInfo.backgroundImg));
3614     object->SetProperty("supportedModes", CreateJsValue(engine, hapModuleInfo.supportedModes));
3615     object->SetProperty("reqCapabilities", CreateNativeArray(engine, hapModuleInfo.reqCapabilities));
3616     object->SetProperty("deviceTypes", CreateNativeArray(engine, hapModuleInfo.deviceTypes));
3617     object->SetProperty("abilityInfo", CreateAbilityInfos(engine, hapModuleInfo.abilityInfos));
3618     object->SetProperty("mainAbilityName", CreateJsValue(engine, hapModuleInfo.mainAbility));
3619     object->SetProperty("installationFree", CreateJsValue(engine, hapModuleInfo.installationFree));
3620     object->SetProperty("mainElementName", CreateJsValue(engine, hapModuleInfo.mainElementName));
3621     object->SetProperty("metadata", CreateInnerMetaDatas(engine, hapModuleInfo.metadata));
3622 
3623     return objContext;
3624 }
3625 
CreateWant(NativeEngine & engine,const OHOS::AAFwk::Want & want)3626 NativeValue* JsBundleMgr::CreateWant(NativeEngine &engine, const OHOS::AAFwk::Want &want)
3627 {
3628     APP_LOGD("CreateWant is called");
3629     auto objContext = engine.CreateObject();
3630     if (objContext == nullptr) {
3631         APP_LOGE("CreateObject failed");
3632         return engine.CreateUndefined();
3633     }
3634 
3635     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3636     if (object == nullptr) {
3637         APP_LOGE("ConvertNativeValueTo object failed");
3638         return engine.CreateUndefined();
3639     }
3640 
3641     ElementName elementName = want.GetElement();
3642     object->SetProperty("bundleName", CreateJsValue(engine, elementName.GetBundleName()));
3643     object->SetProperty("deviceId", CreateJsValue(engine, elementName.GetDeviceID()));
3644     object->SetProperty("abilityName", CreateJsValue(engine, elementName.GetAbilityName()));
3645     object->SetProperty("action", CreateJsValue(engine, want.GetAction()));
3646     object->SetProperty("entities", CreateNativeArray(engine, want.GetEntities()));
3647 
3648     return objContext;
3649 }
3650 
CreateAppInfos(NativeEngine & engine,const std::vector<ApplicationInfo> & appInfos)3651 NativeValue* JsBundleMgr::CreateAppInfos(NativeEngine &engine, const std::vector<ApplicationInfo> &appInfos)
3652 {
3653     NativeValue* arrayValue = engine.CreateArray(appInfos.size());
3654     NativeArray* array = ConvertNativeValueTo<NativeArray>(arrayValue);
3655     uint32_t index = 0;
3656     for (const auto &appInfo : appInfos) {
3657         array->SetElement(index++, CreateAppInfo(engine, appInfo));
3658     }
3659     return arrayValue;
3660 }
3661 
CreateBundleInfos(NativeEngine & engine,const std::vector<BundleInfo> & bundleInfos)3662 NativeValue* JsBundleMgr::CreateBundleInfos(NativeEngine &engine, const std::vector<BundleInfo> &bundleInfos)
3663 {
3664     NativeValue* arrayValue = engine.CreateArray(bundleInfos.size());
3665     NativeArray* array = ConvertNativeValueTo<NativeArray>(arrayValue);
3666     uint32_t index = 0;
3667     for (const auto &bundleInfo : bundleInfos) {
3668         array->SetElement(index++, CreateBundleInfo(engine, bundleInfo));
3669     }
3670     return arrayValue;
3671 }
3672 
UnwarpUserIdThreeParams(NativeEngine & engine,NativeCallbackInfo & info,int32_t & userId)3673 bool JsBundleMgr::UnwarpUserIdThreeParams(NativeEngine &engine, NativeCallbackInfo &info, int32_t &userId)
3674 {
3675     bool flagCall = true;
3676     if (info.argc == ARGS_SIZE_ONE) {
3677         userId = IPCSkeleton::GetCallingUid() / Constants::BASE_USER_RANGE;
3678         flagCall = false;
3679     } else if (info.argc == ARGS_SIZE_TWO && info.argv[PARAM1]->TypeOf() == NATIVE_NUMBER) {
3680         if (!ConvertFromJsValue(engine, info.argv[PARAM1], userId)) {
3681             APP_LOGE("input params string error");
3682         }
3683         flagCall = false;
3684     } else if (info.argc == ARGS_SIZE_TWO && info.argv[PARAM1]->TypeOf() == NATIVE_FUNCTION) {
3685         userId = IPCSkeleton::GetCallingUid() / Constants::BASE_USER_RANGE;
3686     } else if (info.argc == ARGS_SIZE_THREE) {
3687         if (!ConvertFromJsValue(engine, info.argv[PARAM1], userId)) {
3688             APP_LOGE("input params string error");
3689         }
3690     }
3691 
3692     return flagCall;
3693 }
3694 
UnwarpUserIdFourParams(NativeEngine & engine,NativeCallbackInfo & info,int32_t & userId)3695 bool JsBundleMgr::UnwarpUserIdFourParams(NativeEngine &engine, NativeCallbackInfo &info, int32_t &userId)
3696 {
3697     bool flagCall = true;
3698     if (info.argc == ARGS_SIZE_TWO) {
3699         userId = IPCSkeleton::GetCallingUid() / Constants::BASE_USER_RANGE;
3700         flagCall = false;
3701     } else if (info.argc == ARGS_SIZE_THREE && info.argv[PARAM2]->TypeOf() == NATIVE_NUMBER) {
3702         if (!ConvertFromJsValue(engine, info.argv[PARAM2], userId)) {
3703             APP_LOGE("input params string error");
3704         }
3705         flagCall = false;
3706     } else if (info.argc == ARGS_SIZE_THREE && info.argv[PARAM2]->TypeOf() == NATIVE_FUNCTION) {
3707         userId = IPCSkeleton::GetCallingUid() / Constants::BASE_USER_RANGE;
3708     } else if (info.argc == ARGS_SIZE_FOUR) {
3709         if (!ConvertFromJsValue(engine, info.argv[PARAM2], userId)) {
3710             APP_LOGE("input params string error");
3711         }
3712     }
3713 
3714     return flagCall;
3715 }
3716 
UnwarpBundleOptionsParams(NativeEngine & engine,NativeCallbackInfo & info,BundleOptions & options,bool & unwarpBundleOptionsParamsResult)3717 bool JsBundleMgr::UnwarpBundleOptionsParams(NativeEngine &engine, NativeCallbackInfo &info,
3718     BundleOptions &options, bool &unwarpBundleOptionsParamsResult)
3719 {
3720     bool flagCall = true;
3721     auto env = reinterpret_cast<napi_env>(&engine);
3722     if (info.argc == ARGS_SIZE_TWO) {
3723         unwarpBundleOptionsParamsResult = true;
3724         flagCall = false;
3725     } else if (info.argc == ARGS_SIZE_THREE && info.argv[PARAM2]->TypeOf() == NATIVE_OBJECT) {
3726         auto arg3 = reinterpret_cast<napi_value>(info.argv[PARAM2]);
3727         unwarpBundleOptionsParamsResult = ParseBundleOptions(env, options, arg3);
3728         flagCall = false;
3729     } else if (info.argc == ARGS_SIZE_FOUR) {
3730         auto arg3 = reinterpret_cast<napi_value>(info.argv[PARAM2]);
3731         unwarpBundleOptionsParamsResult = ParseBundleOptions(env, options, arg3);
3732     }
3733 
3734     return flagCall;
3735 }
3736 
UnwarpUserIdFiveParams(NativeEngine & engine,NativeCallbackInfo & info,int32_t & userId)3737 bool JsBundleMgr::UnwarpUserIdFiveParams(NativeEngine &engine, NativeCallbackInfo &info, int32_t &userId)
3738 {
3739     bool flagCall = true;
3740     if (info.argc == ARGS_SIZE_THREE && info.argv[PARAM2]->TypeOf() == NATIVE_NUMBER) {
3741         flagCall = false;
3742     } else if (info.argc == ARGS_SIZE_FOUR && info.argv[PARAM3]->TypeOf() == NATIVE_NUMBER) {
3743         if (!ConvertFromJsValue(engine, info.argv[PARAM3], userId)) {
3744             APP_LOGE("input params string error");
3745         }
3746         flagCall = false;
3747     } else if (info.argc == ARGS_SIZE_FIVE) {
3748         if (!ConvertFromJsValue(engine, info.argv[PARAM3], userId)) {
3749             APP_LOGE("input params string error");
3750         }
3751     }
3752 
3753     return flagCall;
3754 }
3755 
InnerGetBundleInfo(const std::string & bundleName,int32_t flags,BundleOptions bundleOptions,BundleInfo & bundleInfo)3756 static bool InnerGetBundleInfo(
3757     const std::string &bundleName, int32_t flags, BundleOptions bundleOptions, BundleInfo &bundleInfo)
3758 {
3759     auto iBundleMgr = GetBundleMgr();
3760     if (iBundleMgr == nullptr) {
3761         APP_LOGE("can not get iBundleMgr");
3762         return false;
3763     }
3764     bool ret = iBundleMgr->GetBundleInfo(bundleName, flags, bundleInfo, bundleOptions.userId);
3765     if (!ret) {
3766         APP_LOGE("bundleInfo is not find");
3767     }
3768     return ret;
3769 }
3770 
UnwarpQueryAbilityInfoParams(NativeEngine & engine,NativeCallbackInfo & info,int32_t & userId,int32_t & errCode)3771 NativeValue* JsBundleMgr::UnwarpQueryAbilityInfoParams(NativeEngine &engine,
3772     NativeCallbackInfo &info, int32_t &userId, int32_t &errCode)
3773 {
3774     if (info.argc == ARGS_SIZE_THREE) {
3775         if (info.argv[PARAM2]->TypeOf() == NATIVE_FUNCTION) {
3776             return info.argv[PARAM2];
3777         } else if (info.argv[PARAM2]->TypeOf() == NATIVE_NUMBER) {
3778             ConvertFromJsValue(engine, info.argv[PARAM2], userId);
3779             return nullptr;
3780         } else {
3781             APP_LOGW("Parse userId failed, set this parameter to the caller userId!");
3782             return nullptr;
3783         }
3784     }
3785 
3786     if (info.argc == ARGS_SIZE_FOUR && info.argv[PARAM3]->TypeOf() == NATIVE_FUNCTION) {
3787         if (info.argv[PARAM2]->TypeOf() == NATIVE_NUMBER) {
3788             ConvertFromJsValue(engine, info.argv[PARAM2], userId);
3789         } else {
3790             APP_LOGW("Parse userId failed, set this parameter to the caller userId!");
3791         }
3792         return info.argv[PARAM3];
3793     }
3794     return nullptr;
3795 }
3796 
OnHandleAbilityInfoCache(NativeEngine & engine,const Query & query,const AAFwk::Want & want,const std::vector<AbilityInfo> & abilityInfos,NativeValue * jsObject)3797 static void OnHandleAbilityInfoCache(NativeEngine &engine, const Query &query,
3798     const AAFwk::Want &want, const std::vector<AbilityInfo> &abilityInfos, NativeValue *jsObject)
3799 {
3800     APP_LOGD("%{public}s called.", __FUNCTION__);
3801     ElementName element = want.GetElement();
3802     if (element.GetBundleName().empty() || element.GetAbilityName().empty()) {
3803         APP_LOGE("get bundleName empty or get abiltityName empty.");
3804         return;
3805     }
3806     uint32_t explicitQueryResultLen = 1;
3807     if (abilityInfos.size() != explicitQueryResultLen || abilityInfos[0].uid != IPCSkeleton::GetCallingUid()) {
3808         APP_LOGE("abilityInfos not only or abilityInfos uid is wrong");
3809         return;
3810     }
3811 
3812     auto cacheAbilityInfo = engine.CreateReference(jsObject, NAPI_RETURN_ONE);
3813     nativeAbilityInfoCache.clear();
3814     nativeAbilityInfoCache[query] = cacheAbilityInfo;
3815 }
InnerGetBundleInfos(int32_t flags,int32_t userId,std::vector<OHOS::AppExecFwk::BundleInfo> & bundleInfos)3816 static bool InnerGetBundleInfos(int32_t flags, int32_t userId, std::vector<OHOS::AppExecFwk::BundleInfo> &bundleInfos)
3817 {
3818     auto iBundleMgr = GetBundleMgr();
3819     if (iBundleMgr == nullptr) {
3820         APP_LOGE("can not get iBundleMgr");
3821         return false;
3822     }
3823     return iBundleMgr->GetBundleInfos(flags, bundleInfos, userId);
3824 }
3825 
CreatePermissionDef(NativeEngine & engine,const PermissionDef & permissionDef)3826 NativeValue* JsBundleMgr::CreatePermissionDef(NativeEngine &engine, const PermissionDef &permissionDef)
3827 {
3828     APP_LOGD("called");
3829     auto objContext = engine.CreateObject();
3830     if (objContext == nullptr) {
3831         APP_LOGE("CreateObject failed");
3832         return engine.CreateUndefined();
3833     }
3834 
3835     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3836     if (object == nullptr) {
3837         APP_LOGE("ConvertNativeValueTo object failed");
3838         return engine.CreateUndefined();
3839     }
3840     object->SetProperty("permissionName", CreateJsValue(engine, permissionDef.permissionName));
3841     object->SetProperty("grantMode", CreateJsValue(engine, permissionDef.grantMode));
3842     object->SetProperty("labelId", CreateJsValue(engine, permissionDef.labelId));
3843     object->SetProperty("descriptionId", CreateJsValue(engine, permissionDef.descriptionId));
3844     return objContext;
3845 }
3846 
CreateBundlePackInfo(NativeEngine & engine,const int32_t & flags,const BundlePackInfo & bundlePackInfo)3847 NativeValue* JsBundleMgr::CreateBundlePackInfo(
3848     NativeEngine &engine, const int32_t &flags, const BundlePackInfo &bundlePackInfo)
3849 {
3850     APP_LOGD("called");
3851     auto objContext = engine.CreateObject();
3852     if (objContext == nullptr) {
3853         APP_LOGE("CreateObject failed");
3854         return engine.CreateUndefined();
3855     }
3856 
3857     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3858     if (object == nullptr) {
3859         APP_LOGE("ConvertNativeValueTo object failed");
3860         return engine.CreateUndefined();
3861     }
3862 
3863     if (static_cast<uint32_t>(flags) & BundlePackFlag::GET_PACKAGES) {
3864         object->SetProperty("packages", CreatePackages(engine, bundlePackInfo));
3865         return objContext;
3866     }
3867 
3868     if (static_cast<uint32_t>(flags) & BundlePackFlag::GET_BUNDLE_SUMMARY) {
3869         object->SetProperty("summary", CreateSummary(engine, bundlePackInfo));
3870         return objContext;
3871     }
3872     if (static_cast<uint32_t>(flags) & BundlePackFlag::GET_MODULE_SUMMARY) {
3873         NativeValue* objValue = engine.CreateObject();
3874         NativeObject* obj = ConvertNativeValueTo<NativeObject>(objValue);
3875         obj->SetProperty("modules", CreateSummaryModules(engine, bundlePackInfo));
3876         object->SetProperty("summary", objValue);
3877         return objContext;
3878     }
3879 
3880     object->SetProperty("summary", CreateSummary(engine, bundlePackInfo));
3881     object->SetProperty("packages", CreatePackages(engine, bundlePackInfo));
3882 
3883     return objContext;
3884 }
3885 
CreatePackages(NativeEngine & engine,const BundlePackInfo & bundlePackInfo)3886 NativeValue* JsBundleMgr::CreatePackages(NativeEngine &engine, const BundlePackInfo &bundlePackInfo)
3887 {
3888     APP_LOGD("called");
3889     auto objContext = engine.CreateObject();
3890     if (objContext == nullptr) {
3891         APP_LOGE("CreateObject failed");
3892         return engine.CreateUndefined();
3893     }
3894 
3895     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3896     if (object == nullptr) {
3897         APP_LOGE("ConvertNativeValueTo object failed");
3898         return engine.CreateUndefined();
3899     }
3900 
3901     for (const auto &package : bundlePackInfo.packages) {
3902         object->SetProperty("deviceType", CreateNativeArray(engine, package.deviceType));
3903         object->SetProperty("name", CreateJsValue(engine, package.name));
3904         object->SetProperty("moduleType", CreateJsValue(engine, package.moduleType));
3905         object->SetProperty("deliveryWithInstall", CreateJsValue(engine, package.deliveryWithInstall));
3906     }
3907 
3908     return objContext;
3909 }
3910 
CreateSummary(NativeEngine & engine,const BundlePackInfo & bundlePackInfo)3911 NativeValue* JsBundleMgr::CreateSummary(NativeEngine &engine, const BundlePackInfo &bundlePackInfo)
3912 {
3913     APP_LOGD("called");
3914     auto objContext = engine.CreateObject();
3915     if (objContext == nullptr) {
3916         APP_LOGE("CreateObject failed");
3917         return engine.CreateUndefined();
3918     }
3919 
3920     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3921     if (object == nullptr) {
3922         APP_LOGE("ConvertNativeValueTo object failed");
3923         return engine.CreateUndefined();
3924     }
3925 
3926     object->SetProperty("app", CreateSummaryApp(engine, bundlePackInfo));
3927     object->SetProperty("modules", CreateSummaryModules(engine, bundlePackInfo));
3928 
3929     return objContext;
3930 }
3931 
CreateSummaryApp(NativeEngine & engine,const BundlePackInfo & bundlePackInfo)3932 NativeValue* JsBundleMgr::CreateSummaryApp(NativeEngine &engine, const BundlePackInfo &bundlePackInfo)
3933 {
3934     APP_LOGD("called");
3935     auto objContext = engine.CreateObject();
3936     if (objContext == nullptr) {
3937         APP_LOGE("CreateObject failed");
3938         return engine.CreateUndefined();
3939     }
3940 
3941     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3942     if (object == nullptr) {
3943         APP_LOGE("ConvertNativeValueTo object failed");
3944         return engine.CreateUndefined();
3945     }
3946 
3947     object->SetProperty("bundleName", CreateJsValue(engine, bundlePackInfo.summary.app.bundleName));
3948     object->SetProperty("version", CreateSummaryAppVersion(engine, bundlePackInfo));
3949 
3950     return objContext;
3951 }
3952 
CreateSummaryAppVersion(NativeEngine & engine,const BundlePackInfo & bundlePackInfo)3953 NativeValue* JsBundleMgr::CreateSummaryAppVersion(NativeEngine &engine, const BundlePackInfo &bundlePackInfo)
3954 {
3955     APP_LOGD("called");
3956     auto objContext = engine.CreateObject();
3957     if (objContext == nullptr) {
3958         APP_LOGE("CreateObject failed");
3959         return engine.CreateUndefined();
3960     }
3961 
3962     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3963     if (object == nullptr) {
3964         APP_LOGE("ConvertNativeValueTo object failed");
3965         return engine.CreateUndefined();
3966     }
3967 
3968     object->SetProperty("name", CreateJsValue(engine, bundlePackInfo.summary.app.version.name));
3969     object->SetProperty("code", CreateJsValue(engine, bundlePackInfo.summary.app.version.code));
3970     object->SetProperty(
3971         "minCompatibleVersionCode", CreateJsValue(engine, bundlePackInfo.summary.app.version.minCompatibleVersionCode));
3972 
3973     return objContext;
3974 }
3975 
CreateSummaryModules(NativeEngine & engine,const BundlePackInfo & bundlePackInfo)3976 NativeValue* JsBundleMgr::CreateSummaryModules(NativeEngine &engine, const BundlePackInfo &bundlePackInfo)
3977 {
3978     APP_LOGD("called");
3979     auto *arrayValue = engine.CreateArray(bundlePackInfo.summary.modules.size());
3980     auto *array = ConvertNativeValueTo<NativeArray>(arrayValue);
3981     for (uint32_t i = 0; i < bundlePackInfo.summary.modules.size(); i++) {
3982         array->SetElement(i, CreateSummaryModule(engine, bundlePackInfo.summary.modules.at(i)));
3983     }
3984     return arrayValue;
3985 }
3986 
CreateSummaryModule(NativeEngine & engine,const PackageModule & moduleInfo)3987 NativeValue* JsBundleMgr::CreateSummaryModule(NativeEngine &engine, const PackageModule &moduleInfo)
3988 {
3989     APP_LOGD("called");
3990     auto objContext = engine.CreateObject();
3991     if (objContext == nullptr) {
3992         APP_LOGE("CreateObject failed");
3993         return engine.CreateUndefined();
3994     }
3995 
3996     auto object = ConvertNativeValueTo<NativeObject>(objContext);
3997     if (object == nullptr) {
3998         APP_LOGE("ConvertNativeValueTo object failed");
3999         return engine.CreateUndefined();
4000     }
4001 
4002     object->SetProperty("mainAbility", CreateJsValue(engine, moduleInfo.mainAbility));
4003     object->SetProperty("apiVersion", CreateModulesApiVersion(engine, moduleInfo));
4004     object->SetProperty("deviceType", CreateNativeArray(engine, moduleInfo.deviceType));
4005     object->SetProperty("distro", CreateDistro(engine, moduleInfo));
4006     object->SetProperty("abilities", CreateAbilities(engine, moduleInfo));
4007 
4008     return objContext;
4009 }
4010 
CreateModulesApiVersion(NativeEngine & engine,const OHOS::AppExecFwk::PackageModule & module)4011 NativeValue* JsBundleMgr::CreateModulesApiVersion(NativeEngine &engine, const OHOS::AppExecFwk::PackageModule &module)
4012 {
4013     APP_LOGD("called");
4014     auto objContext = engine.CreateObject();
4015     if (objContext == nullptr) {
4016         APP_LOGE("CreateObject failed");
4017         return engine.CreateUndefined();
4018     }
4019 
4020     auto object = ConvertNativeValueTo<NativeObject>(objContext);
4021     if (object == nullptr) {
4022         APP_LOGE("ConvertNativeValueTo object failed");
4023         return engine.CreateUndefined();
4024     }
4025 
4026     object->SetProperty("releaseType", CreateJsValue(engine, module.apiVersion.releaseType));
4027     object->SetProperty("compatible", CreateJsValue(engine, module.apiVersion.compatible));
4028     object->SetProperty("target", CreateJsValue(engine, module.apiVersion.target));
4029 
4030     return objContext;
4031 }
4032 
CreateDistro(NativeEngine & engine,const OHOS::AppExecFwk::PackageModule & module)4033 NativeValue* JsBundleMgr::CreateDistro(NativeEngine &engine, const OHOS::AppExecFwk::PackageModule &module)
4034 {
4035     APP_LOGD("called");
4036     auto objContext = engine.CreateObject();
4037     if (objContext == nullptr) {
4038         APP_LOGE("CreateObject failed");
4039         return engine.CreateUndefined();
4040     }
4041 
4042     auto object = ConvertNativeValueTo<NativeObject>(objContext);
4043     if (object == nullptr) {
4044         APP_LOGE("ConvertNativeValueTo object failed");
4045         return engine.CreateUndefined();
4046     }
4047 
4048     object->SetProperty("deliveryWithInstall", CreateJsValue(engine, module.distro.deliveryWithInstall));
4049     object->SetProperty("installationFree", CreateJsValue(engine, module.distro.installationFree));
4050     object->SetProperty("moduleName", CreateJsValue(engine, module.distro.moduleName));
4051     object->SetProperty("moduleType", CreateJsValue(engine, module.distro.moduleType));
4052 
4053     return objContext;
4054 }
4055 
CreateAbilities(NativeEngine & engine,const OHOS::AppExecFwk::PackageModule & module)4056 NativeValue* JsBundleMgr::CreateAbilities(NativeEngine &engine, const OHOS::AppExecFwk::PackageModule &module)
4057 {
4058     APP_LOGD("called");
4059     auto *arrayValue = engine.CreateArray(module.abilities.size());
4060     auto *array = ConvertNativeValueTo<NativeArray>(arrayValue);
4061     for (uint32_t i = 0; i < module.abilities.size(); i++) {
4062         array->SetElement(i, CreateAbility(engine, module.abilities.at(i)));
4063     }
4064     return arrayValue;
4065 }
4066 
CreateAbility(NativeEngine & engine,const ModuleAbilityInfo & ability)4067 NativeValue* JsBundleMgr::CreateAbility(NativeEngine &engine, const ModuleAbilityInfo &ability)
4068 {
4069     APP_LOGD("called");
4070     auto objContext = engine.CreateObject();
4071     if (objContext == nullptr) {
4072         APP_LOGE("CreateObject failed");
4073         return engine.CreateUndefined();
4074     }
4075 
4076     auto object = ConvertNativeValueTo<NativeObject>(objContext);
4077     if (object == nullptr) {
4078         APP_LOGE("ConvertNativeValueTo object failed");
4079         return engine.CreateUndefined();
4080     }
4081 
4082     object->SetProperty("name", CreateJsValue(engine, ability.name));
4083     object->SetProperty("label", CreateJsValue(engine, ability.label));
4084     object->SetProperty("visible", CreateJsValue(engine, ability.visible));
4085     object->SetProperty("forms", CreateFormsInfos(engine, ability.forms));
4086 
4087     return objContext;
4088 }
4089 
CreateFormsInfos(NativeEngine & engine,const std::vector<OHOS::AppExecFwk::AbilityFormInfo> & forms)4090 NativeValue* JsBundleMgr::CreateFormsInfos(
4091     NativeEngine &engine, const std::vector<OHOS::AppExecFwk::AbilityFormInfo> &forms)
4092 {
4093     APP_LOGD("called");
4094     auto *arrayValue = engine.CreateArray(forms.size());
4095     auto *array = ConvertNativeValueTo<NativeArray>(arrayValue);
4096     for (uint32_t i = 0; i < forms.size(); i++) {
4097         array->SetElement(i, CreateFormsInfo(engine, forms.at(i)));
4098     }
4099     return arrayValue;
4100 }
4101 
CreateFormsInfo(NativeEngine & engine,const AbilityFormInfo & form)4102 NativeValue* JsBundleMgr::CreateFormsInfo(NativeEngine &engine, const AbilityFormInfo &form)
4103 {
4104     APP_LOGD("called");
4105     auto objContext = engine.CreateObject();
4106     if (objContext == nullptr) {
4107         APP_LOGE("CreateObject failed");
4108         return engine.CreateUndefined();
4109     }
4110 
4111     auto object = ConvertNativeValueTo<NativeObject>(objContext);
4112     if (object == nullptr) {
4113         APP_LOGE("ConvertNativeValueTo object failed");
4114         return engine.CreateUndefined();
4115     }
4116 
4117     object->SetProperty("name", CreateJsValue(engine, form.name));
4118     object->SetProperty("type", CreateJsValue(engine, form.type));
4119     object->SetProperty("updateEnabled", CreateJsValue(engine, form.updateEnabled));
4120     object->SetProperty("scheduledUpdateTime", CreateJsValue(engine, form.scheduledUpdateTime));
4121     object->SetProperty("updateDuration", CreateJsValue(engine, form.updateDuration));
4122     object->SetProperty("supportDimensions", CreateNativeArray(engine, form.supportDimensions));
4123     object->SetProperty("defaultDimension", CreateJsValue(engine, form.defaultDimension));
4124 
4125     return objContext;
4126 }
4127 
Finalizer(NativeEngine * engine,void * data,void * hint)4128 void JsBundleMgr::Finalizer(NativeEngine *engine, void *data, void *hint)
4129 {
4130     APP_LOGD("JsBundleMgr::Finalizer is called");
4131     std::unique_ptr<JsBundleMgr>(static_cast<JsBundleMgr*>(data));
4132 }
4133 
GetAllApplicationInfo(NativeEngine * engine,NativeCallbackInfo * info)4134 NativeValue* JsBundleMgr::GetAllApplicationInfo(NativeEngine *engine, NativeCallbackInfo *info)
4135 {
4136     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4137     return (me != nullptr) ? me->OnGetAllApplicationInfo(*engine, *info) : nullptr;
4138 }
4139 
GetApplicationInfo(NativeEngine * engine,NativeCallbackInfo * info)4140 NativeValue* JsBundleMgr::GetApplicationInfo(NativeEngine *engine, NativeCallbackInfo *info)
4141 {
4142     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4143     return (me != nullptr) ? me->OnGetApplicationInfo(*engine, *info) : nullptr;
4144 }
4145 
4146 
GetBundleArchiveInfo(NativeEngine * engine,NativeCallbackInfo * info)4147 NativeValue* JsBundleMgr::GetBundleArchiveInfo(NativeEngine *engine, NativeCallbackInfo *info)
4148 {
4149     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4150     return (me != nullptr) ? me->OnGetBundleArchiveInfo(*engine, *info) : nullptr;
4151 }
4152 
GetLaunchWantForBundle(NativeEngine * engine,NativeCallbackInfo * info)4153 NativeValue* JsBundleMgr::GetLaunchWantForBundle(NativeEngine *engine, NativeCallbackInfo *info)
4154 {
4155     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4156     return (me != nullptr) ? me->OnGetLaunchWantForBundle(*engine, *info) : nullptr;
4157 }
4158 
IsAbilityEnabled(NativeEngine * engine,NativeCallbackInfo * info)4159 NativeValue* JsBundleMgr::IsAbilityEnabled(NativeEngine *engine, NativeCallbackInfo *info)
4160 {
4161     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4162     return (me != nullptr) ? me->OnIsAbilityEnabled(*engine, *info) : nullptr;
4163 }
4164 
IsApplicationEnabled(NativeEngine * engine,NativeCallbackInfo * info)4165 NativeValue* JsBundleMgr::IsApplicationEnabled(NativeEngine *engine, NativeCallbackInfo *info)
4166 {
4167     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4168     return (me != nullptr) ? me->OnIsApplicationEnabled(*engine, *info) : nullptr;
4169 }
4170 
GetBundleInfo(NativeEngine * engine,NativeCallbackInfo * info)4171 NativeValue* JsBundleMgr::GetBundleInfo(NativeEngine *engine, NativeCallbackInfo *info)
4172 {
4173     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4174     return (me != nullptr) ? me->OnGetBundleInfo(*engine, *info) : nullptr;
4175 }
4176 
GetAbilityIcon(NativeEngine * engine,NativeCallbackInfo * info)4177 NativeValue* JsBundleMgr::GetAbilityIcon(NativeEngine *engine, NativeCallbackInfo *info)
4178 {
4179     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4180     return (me != nullptr) ? me->OnGetAbilityIcon(*engine, *info) : nullptr;
4181 }
4182 
GetNameForUid(NativeEngine * engine,NativeCallbackInfo * info)4183 NativeValue* JsBundleMgr::GetNameForUid(NativeEngine *engine, NativeCallbackInfo *info)
4184 {
4185     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4186     return (me != nullptr) ? me->OnGetNameForUid(*engine, *info) : nullptr;
4187 }
4188 
GetAbilityInfo(NativeEngine * engine,NativeCallbackInfo * info)4189 NativeValue* JsBundleMgr::GetAbilityInfo(NativeEngine *engine, NativeCallbackInfo *info)
4190 {
4191     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4192     return (me != nullptr) ? me->OnGetAbilityInfo(*engine, *info) : nullptr;
4193 }
4194 
GetAbilityLabel(NativeEngine * engine,NativeCallbackInfo * info)4195 NativeValue* JsBundleMgr::GetAbilityLabel(NativeEngine *engine, NativeCallbackInfo *info)
4196 {
4197     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4198     return (me != nullptr) ? me->OnGetAbilityLabel(*engine, *info) : nullptr;
4199 }
4200 
SetAbilityEnabled(NativeEngine * engine,NativeCallbackInfo * info)4201 NativeValue* JsBundleMgr::SetAbilityEnabled(NativeEngine *engine, NativeCallbackInfo *info)
4202 {
4203     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4204     return (me != nullptr) ? me->OnSetAbilityEnabled(*engine, *info) : nullptr;
4205 }
4206 
SetApplicationEnabled(NativeEngine * engine,NativeCallbackInfo * info)4207 NativeValue* JsBundleMgr::SetApplicationEnabled(NativeEngine *engine, NativeCallbackInfo *info)
4208 {
4209     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4210     return (me != nullptr) ? me->OnSetApplicationEnabled(*engine, *info) : nullptr;
4211 }
4212 
QueryAbilityInfos(NativeEngine * engine,NativeCallbackInfo * info)4213 NativeValue* JsBundleMgr::QueryAbilityInfos(NativeEngine *engine, NativeCallbackInfo *info)
4214 {
4215     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4216     return (me != nullptr) ? me->OnQueryAbilityInfos(*engine, *info) : nullptr;
4217 }
4218 
GetAllBundleInfo(NativeEngine * engine,NativeCallbackInfo * info)4219 NativeValue* JsBundleMgr::GetAllBundleInfo(NativeEngine *engine, NativeCallbackInfo *info)
4220 {
4221     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4222     return (me != nullptr) ? me->OnGetAllBundleInfo(*engine, *info) : nullptr;
4223 }
4224 
GetBundleInstaller(NativeEngine * engine,NativeCallbackInfo * info)4225 NativeValue* JsBundleMgr::GetBundleInstaller(NativeEngine *engine, NativeCallbackInfo *info)
4226 {
4227     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4228     return (me != nullptr) ? me->OnGetBundleInstaller(*engine, *info) : nullptr;
4229 }
GetPermissionDef(NativeEngine * engine,NativeCallbackInfo * info)4230 NativeValue* JsBundleMgr::GetPermissionDef(NativeEngine *engine, NativeCallbackInfo *info)
4231 {
4232     JsBundleMgr* me = CheckParamsAndGetThis<JsBundleMgr>(engine, info);
4233     return (me != nullptr) ? me->OnGetPermissionDef(*engine, *info) : nullptr;
4234 }
4235 
OnGetAllApplicationInfo(NativeEngine & engine,NativeCallbackInfo & info)4236 NativeValue* JsBundleMgr::OnGetAllApplicationInfo(NativeEngine &engine, NativeCallbackInfo &info)
4237 {
4238     APP_LOGD("%{public}s is called", __FUNCTION__);
4239     int32_t errCode = ERR_OK;
4240     if (info.argc > ARGS_SIZE_THREE || info.argc < ARGS_SIZE_ONE) {
4241         APP_LOGE("wrong number of arguments!");
4242         errCode = PARAM_TYPE_ERROR;
4243     }
4244 
4245     int32_t bundleFlags = 0;
4246     if (!ConvertFromJsValue(engine, info.argv[PARAM0], bundleFlags)) {
4247         APP_LOGE("conversion failed!");
4248         errCode = PARAM_TYPE_ERROR;
4249     }
4250 
4251     int32_t userId = Constants::UNSPECIFIED_USERID;
4252     bool flagCall = JsBundleMgr::UnwarpUserIdThreeParams(engine, info, userId);
4253     auto complete = [obj = this, bundleFlags, userId, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) {
4254         if (errCode != ERR_OK) {
4255             task.Reject(engine, CreateJsError(engine, errCode, "type mismatch"));
4256             return;
4257         }
4258         std::vector<ApplicationInfo> appInfos;
4259         auto ret = InnerGetApplicationInfos(bundleFlags, userId, appInfos);
4260         if (!ret) {
4261             task.Reject(engine, CreateJsError(engine, 1, "GetAllApplicationInfo falied"));
4262             return;
4263         }
4264         task.Resolve(engine, obj->CreateAppInfos(engine, appInfos));
4265     };
4266 
4267     NativeValue *result = nullptr;
4268     auto callback = flagCall ? ((info.argc == ARGS_SIZE_TWO) ? info.argv[PARAM1] : info.argv[PARAM2]) : nullptr;
4269     AsyncTask::Schedule("JsBundleMgr::OnGetAllApplicationInfo",
4270         engine, CreateAsyncTaskWithLastParam(engine, callback, nullptr, std::move(complete), &result));
4271     return result;
4272 }
4273 
OnGetApplicationInfo(NativeEngine & engine,NativeCallbackInfo & info)4274 NativeValue* JsBundleMgr::OnGetApplicationInfo(NativeEngine &engine, NativeCallbackInfo &info)
4275 {
4276     APP_LOGD("%{public}s is called", __FUNCTION__);
4277     int32_t errCode = ERR_OK;
4278     if (info.argc > ARGS_SIZE_FOUR || info.argc < ARGS_SIZE_TWO) {
4279         APP_LOGE("wrong number of arguments!");
4280         errCode = PARAM_TYPE_ERROR;
4281     }
4282 
4283     if (info.argv[PARAM0]->TypeOf() != NATIVE_STRING) {
4284         APP_LOGE("input params is not string!");
4285         errCode = PARAM_TYPE_ERROR;
4286     }
4287     std::string bundleName("");
4288     if (!ConvertFromJsValue(engine, info.argv[PARAM0], bundleName)) {
4289         APP_LOGE("conversion failed!");
4290         errCode = PARAM_TYPE_ERROR;
4291     }
4292 
4293     if (info.argv[PARAM1]->TypeOf() != NATIVE_NUMBER) {
4294         APP_LOGE("input params is not number!");
4295         errCode = PARAM_TYPE_ERROR;
4296     }
4297     int32_t bundleFlags = 0;
4298     if (!ConvertFromJsValue(engine, info.argv[PARAM1], bundleFlags)) {
4299         APP_LOGE("conversion failed!");
4300         errCode = PARAM_TYPE_ERROR;
4301     }
4302 
4303     int32_t userId = Constants::UNSPECIFIED_USERID;
4304     bool flagCall = JsBundleMgr::UnwarpUserIdFourParams(engine, info, userId);
4305     auto complete = [obj = this, bundleName, bundleFlags, userId, errCode](
4306                         NativeEngine &engine, AsyncTask &task, int32_t status) {
4307         if (errCode != ERR_OK) {
4308             task.Reject(engine, CreateJsError(engine, errCode, "type mismatch"));
4309             return;
4310         }
4311         ApplicationInfo appInfo;
4312         std::string name(bundleName);
4313         auto ret = InnerGetApplicationInfo(name, bundleFlags, userId, appInfo);
4314         if (!ret) {
4315             task.Reject(engine, CreateJsError(engine, 1, "GetApplicationInfo falied"));
4316             return;
4317         }
4318         task.Resolve(engine, obj->CreateAppInfo(engine, appInfo));
4319     };
4320 
4321     NativeValue *result = nullptr;
4322     auto callback = flagCall ? ((info.argc == ARGS_SIZE_THREE) ? info.argv[PARAM2] : info.argv[PARAM3]) : nullptr;
4323     AsyncTask::Schedule("JsBundleMgr::OnGetApplicationInfo",
4324         engine, CreateAsyncTaskWithLastParam(engine, callback, nullptr, std::move(complete), &result));
4325     return result;
4326 }
4327 
OnGetBundleArchiveInfo(NativeEngine & engine,NativeCallbackInfo & info)4328 NativeValue* JsBundleMgr::OnGetBundleArchiveInfo(NativeEngine &engine, NativeCallbackInfo &info)
4329 {
4330     APP_LOGD("%{public}s is called", __FUNCTION__);
4331     int32_t errCode = ERR_OK;
4332     if (info.argc > ARGS_SIZE_THREE || info.argc < ARGS_SIZE_TWO) {
4333         APP_LOGE("wrong number of arguments!");
4334         errCode = PARAM_TYPE_ERROR;
4335     }
4336 
4337     std::string hapFilePath("");
4338     if (!ConvertFromJsValue(engine, info.argv[PARAM0], hapFilePath)) {
4339         APP_LOGE("conversion failed!");
4340         errCode = PARAM_TYPE_ERROR;
4341     }
4342 
4343     int32_t bundlePackFlag = 0;
4344     if (!ConvertFromJsValue(engine, info.argv[PARAM1], bundlePackFlag)) {
4345         APP_LOGE("conversion failed!");
4346         errCode = PARAM_TYPE_ERROR;
4347     }
4348 
4349     auto complete = [obj = this, hapFilePath, bundlePackFlag, errCode](
4350                         NativeEngine &engine, AsyncTask &task, int32_t status) {
4351         if (errCode != ERR_OK) {
4352             task.Reject(engine, CreateJsError(engine, errCode, "type mismatch"));
4353             return;
4354         }
4355         BundleInfo bundleInfo;
4356         std::string path(hapFilePath);
4357         auto ret = InnerGetArchiveInfo(path, bundlePackFlag, bundleInfo);
4358         if (!ret) {
4359             task.Reject(engine, CreateJsError(engine, 1, "GetBundleArchiveInfo falied"));
4360             return;
4361         }
4362         task.Resolve(engine, obj->CreateBundleInfo(engine, bundleInfo));
4363     };
4364 
4365     NativeValue *result = nullptr;
4366     auto callback = (info.argc == ARGS_SIZE_TWO) ? nullptr : info.argv[PARAM2];
4367     AsyncTask::Schedule("JsBundleMgr::OnGetBundleArchiveInfo",
4368         engine, CreateAsyncTaskWithLastParam(engine, callback, nullptr, std::move(complete), &result));
4369     return result;
4370 }
4371 
OnGetLaunchWantForBundle(NativeEngine & engine,NativeCallbackInfo & info)4372 NativeValue* JsBundleMgr::OnGetLaunchWantForBundle(NativeEngine &engine, NativeCallbackInfo &info)
4373 {
4374     APP_LOGD("%{public}s is called", __FUNCTION__);
4375     int32_t errCode = ERR_OK;
4376     if (info.argc > ARGS_SIZE_TWO || info.argc < ARGS_SIZE_ONE) {
4377         APP_LOGE("wrong number of arguments!");
4378         errCode = PARAM_TYPE_ERROR;
4379     }
4380 
4381     std::string bundleName("");
4382     if (!ConvertFromJsValue(engine, info.argv[PARAM0], bundleName)) {
4383         APP_LOGE("conversion failed!");
4384         errCode = PARAM_TYPE_ERROR;
4385     }
4386 
4387     auto complete = [obj = this, bundleName, errCode](
4388                         NativeEngine &engine, AsyncTask &task, int32_t status) {
4389         if (errCode != ERR_OK) {
4390             task.Reject(engine, CreateJsError(engine, errCode, "type mismatch"));
4391             return;
4392         }
4393         Want want;
4394         std::string name(bundleName);
4395         auto ret = InnerGetLaunchWantForBundle(name, want);
4396         if (!ret) {
4397             task.Reject(engine, CreateJsError(engine, 1, "getLaunchWantForBundle failed"));
4398             return;
4399         }
4400         task.Resolve(engine, obj->CreateWant(engine, want));
4401     };
4402 
4403     NativeValue *result = nullptr;
4404     auto callback = (info.argc == ARGS_SIZE_ONE) ? nullptr : info.argv[PARAM1];
4405     AsyncTask::Schedule("JsBundleMgr::OnGetLaunchWantForBundle",
4406         engine, CreateAsyncTaskWithLastParam(engine, callback, nullptr, std::move(complete), &result));
4407     return result;
4408 }
4409 
OnIsAbilityEnabled(NativeEngine & engine,NativeCallbackInfo & info)4410 NativeValue* JsBundleMgr::OnIsAbilityEnabled(NativeEngine &engine, NativeCallbackInfo &info)
4411 {
4412     APP_LOGD("%{public}s is called", __FUNCTION__);
4413     int32_t errCode = ERR_OK;
4414     auto env = reinterpret_cast<napi_env>(&engine);
4415     auto inputAbilityInfo = reinterpret_cast<napi_value>(info.argv[PARAM0]);
4416     OHOS::AppExecFwk::AbilityInfo abilityInfo;
4417     if (info.argc > ARGS_SIZE_TWO || info.argc < ARGS_SIZE_ONE) {
4418         APP_LOGE("wrong number of arguments!");
4419         errCode = INVALID_PARAM;
4420     }
4421     if (info.argv[PARAM0]->TypeOf() != NATIVE_OBJECT) {
4422         APP_LOGE("input params is not object!");
4423         errCode = INVALID_PARAM;
4424     }
4425     if (!UnwrapAbilityInfo(env, inputAbilityInfo, abilityInfo)) {
4426         APP_LOGE("conversion failed!");
4427         errCode = INVALID_PARAM;
4428     }
4429 
4430     AsyncTask::CompleteCallback complete = [obj = this, abilityInfo, errCode, info]
4431         (NativeEngine &engine, AsyncTask &task, int32_t status) {
4432             if (errCode != ERR_OK) {
4433                 task.Reject(engine, CreateJsError(engine, errCode, "type mismatch"));
4434                 return;
4435             }
4436             bool isEnable = false;
4437             auto iBundleMgr = GetBundleMgr();
4438             iBundleMgr->IsAbilityEnabled(abilityInfo, isEnable);
4439             task.Resolve(engine, CreateJsValue(engine, isEnable));
4440     };
4441     NativeValue* lastParam = (info.argc == ARGS_SIZE_ONE) ? nullptr : info.argv[PARAM1];
4442     NativeValue* result = nullptr;
4443     AsyncTask::Schedule("JsBundleMgr::OnIsAbilityEnabled",
4444         engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
4445     return result;
4446 }
4447 
OnIsApplicationEnabled(NativeEngine & engine,NativeCallbackInfo & info)4448 NativeValue* JsBundleMgr::OnIsApplicationEnabled(NativeEngine &engine, NativeCallbackInfo &info)
4449 {
4450     APP_LOGD("%{public}s is called", __FUNCTION__);
4451     int32_t errCode = ERR_OK;
4452     std::string bundleName;
4453     if (info.argc > ARGS_SIZE_TWO || info.argc < ARGS_SIZE_ONE) {
4454         APP_LOGE("wrong number of arguments!");
4455         errCode = INVALID_PARAM;
4456     }
4457     if (info.argv[PARAM0]->TypeOf() != NATIVE_STRING) {
4458         APP_LOGE("input params is not string!");
4459         errCode = INVALID_PARAM;
4460     } else if (!ConvertFromJsValue(engine, info.argv[PARAM0], bundleName)) {
4461         APP_LOGE("conversion failed!");
4462         errCode = INVALID_PARAM;
4463     }
4464     AsyncTask::CompleteCallback complete = [bundleName, errCode, info]
4465         (NativeEngine &engine, AsyncTask &task, int32_t status) {
4466             if (errCode != ERR_OK) {
4467                 task.Reject(engine, CreateJsError(engine, errCode, "type mismatch"));
4468                 return;
4469             }
4470             bool isEnable = false;
4471             auto iBundleMgr = GetBundleMgr();
4472             iBundleMgr->IsApplicationEnabled(bundleName, isEnable);
4473             task.Resolve(engine, CreateJsValue(engine, isEnable));
4474     };
4475     NativeValue* lastParam = (info.argc == ARGS_SIZE_ONE) ? nullptr : info.argv[PARAM1];
4476     NativeValue* result = nullptr;
4477     AsyncTask::Schedule("JsBundleMgr::OnIsApplicationEnabled",
4478         engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
4479     return result;
4480 }
4481 
OnGetBundleInfo(NativeEngine & engine,NativeCallbackInfo & info)4482 NativeValue* JsBundleMgr::OnGetBundleInfo(NativeEngine &engine, NativeCallbackInfo &info)
4483 {
4484     APP_LOGD("%{public}s is called", __FUNCTION__);
4485     int32_t errCode = ERR_OK;
4486     if (info.argc > ARGS_SIZE_FOUR || info.argc < ARGS_SIZE_TWO) {
4487         APP_LOGE("wrong number of arguments!");
4488         errCode = PARAM_TYPE_ERROR;
4489     }
4490 
4491     if (info.argv[PARAM0]->TypeOf() != NATIVE_STRING) {
4492         APP_LOGE("input params is not string!");
4493         errCode = PARAM_TYPE_ERROR;
4494     }
4495     std::string bundleName("");
4496     if (!ConvertFromJsValue(engine, info.argv[PARAM0], bundleName)) {
4497         APP_LOGE("conversion failed!");
4498         errCode = PARAM_TYPE_ERROR;
4499     }
4500 
4501     if (info.argv[PARAM1]->TypeOf() != NATIVE_NUMBER) {
4502         APP_LOGE("input params is not number!");
4503         errCode = PARAM_TYPE_ERROR;
4504     }
4505     int32_t bundleFlags = 0;
4506     if (!ConvertFromJsValue(engine, info.argv[PARAM1], bundleFlags)) {
4507         APP_LOGE("conversion failed!");
4508         errCode = PARAM_TYPE_ERROR;
4509     }
4510 
4511     BundleOptions options;
4512     bool unwarpBundleOptionsParamsResult = true;
4513     bool flagCall = UnwarpBundleOptionsParams(engine, info, options, unwarpBundleOptionsParamsResult);
4514     if (!unwarpBundleOptionsParamsResult) {
4515         APP_LOGE("UnwarpBundleOptionsParams failed!");
4516         errCode = PARAM_TYPE_ERROR;
4517     }
4518     auto complete = [obj = this, bundleName, bundleFlags, options, errCode](
4519                         NativeEngine &engine, AsyncTask &task, int32_t status) {
4520         if (errCode != ERR_OK) {
4521             std::string getBundleInfoErrData = "type mismatch";
4522             task.RejectWithCustomize(engine, CreateJsValue(engine, errCode),
4523                 CreateJsValue(engine, getBundleInfoErrData));
4524             return;
4525         }
4526         BundleInfo bundleInfo;
4527         std::string name(bundleName);
4528         auto ret = InnerGetBundleInfo(name, bundleFlags, options, bundleInfo);
4529         if (!ret) {
4530             task.RejectWithCustomize(engine, CreateJsValue(engine, 1), engine.CreateUndefined());
4531             return;
4532         }
4533         task.ResolveWithCustomize(engine, CreateJsValue(engine, 0), obj->CreateBundleInfo(engine, bundleInfo));
4534     };
4535 
4536     NativeValue *result = nullptr;
4537     auto callback = flagCall ? ((info.argc == ARGS_SIZE_THREE) ? info.argv[PARAM2] : info.argv[PARAM3]) : nullptr;
4538     AsyncTask::Schedule("JsBundleMgr::OnGetBundleInfo",
4539         engine, CreateAsyncTaskWithLastParam(engine, callback, nullptr, std::move(complete), &result));
4540     return result;
4541 }
4542 
4543 #ifdef BUNDLE_FRAMEWORK_GRAPHICS
InitGetAbilityIcon(NativeEngine & engine,NativeCallbackInfo & info,NativeValue * & lastParam,std::string & errMessage,std::shared_ptr<JsAbilityIcon> abilityIcon)4544 int32_t JsBundleMgr::InitGetAbilityIcon(NativeEngine &engine, NativeCallbackInfo &info, NativeValue *&lastParam,
4545     std::string &errMessage, std::shared_ptr<JsAbilityIcon> abilityIcon)
4546 {
4547     int32_t errorCode = NAPI_ERR_NO_ERROR;
4548     if (abilityIcon == nullptr) {
4549         errMessage = "Get an empty pointer.";
4550         return INVALID_PARAM;
4551     }
4552     abilityIcon->hasModuleName = false;
4553     if (info.argv[info.argc-1]->TypeOf() == NATIVE_FUNCTION) {
4554         abilityIcon->hasModuleName = (info.argc == ARGS_SIZE_FOUR) ? true : false;
4555     } else {
4556         abilityIcon->hasModuleName = (info.argc == ARGS_SIZE_THREE) ? true : false;
4557     }
4558     for (size_t i = 0; i < info.argc; ++i) {
4559         if ((i == PARAM0) && (info.argv[i]->TypeOf() == NATIVE_STRING)) {
4560             ConvertFromJsValue(engine, info.argv[i], abilityIcon->bundleName);
4561         } else if ((i == PARAM1) && (info.argv[i]->TypeOf() == NATIVE_STRING)) {
4562             if (abilityIcon->hasModuleName) {
4563                 ConvertFromJsValue(engine, info.argv[i], abilityIcon->moduleName);
4564             } else {
4565                 ConvertFromJsValue(engine, info.argv[i], abilityIcon->abilityName);
4566             }
4567         } else if ((i == PARAM2) && (info.argv[i]->TypeOf() == NATIVE_STRING)) {
4568             ConvertFromJsValue(engine, info.argv[i], abilityIcon->abilityName);
4569         } else if (((i == PARAM2) || (i == PARAM3)) && (info.argv[i]->TypeOf() == NATIVE_FUNCTION)) {
4570             lastParam = info.argv[i];
4571         } else {
4572             errMessage = "type misMatch";
4573             errorCode = INVALID_PARAM;
4574         }
4575     }
4576     return errorCode;
4577 }
4578 
ExecuteGetAbilityIcon(NativeEngine & engine,const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,bool hasModuleName)4579 static std::shared_ptr<Media::PixelMap> ExecuteGetAbilityIcon(NativeEngine &engine, const std::string &bundleName,
4580     const std::string &moduleName, const std::string &abilityName, bool hasModuleName)
4581 {
4582     if (bundleName.empty() || abilityName.empty()) {
4583         APP_LOGE("bundleName or abilityName is invalid param");
4584         return nullptr;
4585     }
4586     BundleGraphicsClient client;
4587     if (hasModuleName && moduleName.empty()) {
4588         APP_LOGE("moduleName is invalid param");
4589         return nullptr;
4590     }
4591     std::shared_ptr<Media::PixelMap> pixelMap = nullptr;
4592     ErrCode ret = client.GetAbilityPixelMapIcon(bundleName, moduleName, abilityName, pixelMap);
4593     if (ret != ERR_OK) {
4594         return nullptr;
4595     }
4596     return pixelMap;
4597 }
4598 
OnGetAbilityIcon(NativeEngine & engine,NativeCallbackInfo & info)4599 NativeValue* JsBundleMgr::OnGetAbilityIcon(NativeEngine &engine, NativeCallbackInfo &info)
4600 {
4601     APP_LOGD("%{public}s is called", __FUNCTION__);
4602     auto errorVal = std::make_shared<int32_t>(NAPI_ERR_NO_ERROR);
4603     std::shared_ptr<JsAbilityIcon> abilityIcon = std::make_shared<JsAbilityIcon>();
4604     if (info.argc < ARGS_SIZE_TWO || info.argc > ARGS_SIZE_FOUR) {
4605         APP_LOGE("wrong number of arguments.");
4606         return engine.CreateUndefined();
4607     }
4608     NativeValue *lastParam = nullptr;
4609     *errorVal = InitGetAbilityIcon(engine, info, lastParam, errMessage_, abilityIcon);
4610     auto complete = [obj = this, value = errorVal, info = abilityIcon]
4611         (NativeEngine &engine, AsyncTask &task, int32_t status) {
4612         if (*value != NAPI_ERR_NO_ERROR || info == nullptr) {
4613             obj->errMessage_ = (info == nullptr) ? "Pointer is empty." : obj->errMessage_;
4614             *value = (info == nullptr) ? INVALID_PARAM : *value;
4615             task.RejectWithCustomize(engine, CreateJsValue(engine, *value), CreateJsValue(engine, obj->errMessage_));
4616             return;
4617         }
4618         std::shared_ptr<Media::PixelMap> pixelMap;
4619         pixelMap = ExecuteGetAbilityIcon(engine, info->bundleName,
4620             info->moduleName, info->abilityName, info->hasModuleName);
4621         if (!pixelMap) {
4622             obj->errMessage_ = "get pixelMap failed.";
4623             task.RejectWithCustomize(engine, CreateJsValue(engine, OPERATION_FAILED),
4624                 CreateJsValue(engine, obj->errMessage_));
4625             return;
4626         }
4627         auto env = reinterpret_cast<napi_env>(&engine);
4628         NativeValue *ret = reinterpret_cast<NativeValue*>(
4629             Media::PixelMapNapi::CreatePixelMap(env, pixelMap));
4630         task.ResolveWithCustomize(engine, CreateJsValue(engine, 0), ret);
4631     };
4632     NativeValue *result = nullptr;
4633     AsyncTask::Schedule("JsBundleMgr::OnGetAbilityIcon",
4634         engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
4635     return result;
4636 }
4637 #else
OnGetAbilityIcon(NativeEngine & engine,NativeCallbackInfo & info)4638 NativeValue* JsBundleMgr::OnGetAbilityIcon(NativeEngine &engine, NativeCallbackInfo &info)
4639 {
4640     APP_LOGD("%{public}s is called", __FUNCTION__);
4641     auto errorVal = std::make_shared<int32_t>(NAPI_ERR_NO_ERROR);
4642     NativeValue *lastParam = nullptr;
4643     if (info.argc >PARAM0) {
4644         if (info.argv[info.argc - PARAM1]->TypeOf() == NATIVE_FUNCTION) {
4645             lastParam = info.argv[info.argc - PARAM1];
4646         }
4647     }
4648     auto complete = []
4649         (NativeEngine &engine, AsyncTask &task, int32_t status) {
4650             task.RejectWithCustomize(engine, CreateJsValue(engine, UNSUPPORTED_FEATURE_ERRCODE),
4651                 CreateJsValue(engine, UNSUPPORTED_FEATURE_MESSAGE.c_str()));
4652         };
4653     NativeValue *result = nullptr;
4654     AsyncTask::Schedule("JsBundleMgr::OnGetAbilityIcon",
4655         engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
4656     return result;
4657 }
4658 #endif
4659 
OnGetNameForUid(NativeEngine & engine,NativeCallbackInfo & info)4660 NativeValue* JsBundleMgr::OnGetNameForUid(NativeEngine &engine, NativeCallbackInfo &info)
4661 {
4662     APP_LOGD("%{public}s is called", __FUNCTION__);
4663     int32_t errCode = ERR_OK;
4664     if (info.argc < ARGS_SIZE_ONE || info.argc > ARGS_SIZE_TWO) {
4665         APP_LOGE("wrong number of arguments.");
4666         return engine.CreateUndefined();
4667     }
4668 
4669     if (info.argv[PARAM0]->TypeOf() != NATIVE_NUMBER) {
4670         errCode = INVALID_PARAM;
4671     }
4672 
4673     int32_t uid = 0;
4674     ConvertFromJsValue(engine, info.argv[PARAM0], uid);
4675 
4676     auto complete = [obj = this, uid, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) {
4677         if (errCode != ERR_OK) {
4678             std::string errMessage = "type mismatch";
4679             task.RejectWithCustomize(engine, CreateJsValue(engine, errCode), CreateJsValue(engine, errMessage));
4680             return;
4681         }
4682         std::string bundleName("");
4683         auto ret = InnerGetNameForUid(uid, bundleName);
4684         if (!ret) {
4685             task.RejectWithCustomize(engine, CreateJsValue(engine, 1), engine.CreateUndefined());
4686             return;
4687         }
4688         task.ResolveWithCustomize(engine, CreateJsValue(engine, 0), CreateJsValue(engine, bundleName));
4689     };
4690     auto lastParam = (info.argc == ARGS_SIZE_TWO) ? info.argv[PARAM1] : nullptr;
4691     NativeValue *result = nullptr;
4692     AsyncTask::Schedule("JsBundleMgr::OnGetNameForUid",
4693         engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
4694     return result;
4695 }
4696 
InitGetAbilityInfo(NativeEngine & engine,NativeCallbackInfo & info,NativeValue * & lastParam,std::string & errMessage,std::shared_ptr<JsAbilityInfo> abilityInfo)4697 int32_t JsBundleMgr::InitGetAbilityInfo(NativeEngine &engine, NativeCallbackInfo &info, NativeValue *&lastParam,
4698     std::string &errMessage, std::shared_ptr<JsAbilityInfo> abilityInfo)
4699 {
4700     int32_t errorCode = NAPI_ERR_NO_ERROR;
4701     if (abilityInfo == nullptr) {
4702         errMessage = "Get an empty pointer.";
4703         return INVALID_PARAM;
4704     }
4705     abilityInfo->hasModuleName = false;
4706     if (info.argv[info.argc-1]->TypeOf() == NATIVE_FUNCTION) {
4707         abilityInfo->hasModuleName = (info.argc == ARGS_SIZE_FOUR) ? true : false;
4708     } else {
4709         abilityInfo->hasModuleName = (info.argc == ARGS_SIZE_THREE) ? true : false;
4710     }
4711     for (size_t i = 0; i < info.argc; ++i) {
4712         if ((i == PARAM0) && (info.argv[i]->TypeOf() == NATIVE_STRING)) {
4713             ConvertFromJsValue(engine, info.argv[i], abilityInfo->bundleName);
4714         } else if ((i == PARAM1) && (info.argv[i]->TypeOf() == NATIVE_STRING)) {
4715             if (abilityInfo->hasModuleName) {
4716                 ConvertFromJsValue(engine, info.argv[i], abilityInfo->moduleName);
4717             } else {
4718                 ConvertFromJsValue(engine, info.argv[i], abilityInfo->abilityName);
4719             }
4720         } else if ((i == PARAM2) && (info.argv[i]->TypeOf() == NATIVE_STRING)) {
4721             ConvertFromJsValue(engine, info.argv[i], abilityInfo->abilityName);
4722         } else if (((i == PARAM2) || (i == PARAM3)) && (info.argv[i]->TypeOf() == NATIVE_FUNCTION)) {
4723             lastParam = info.argv[i];
4724         } else {
4725             errMessage = "type misMatch";
4726             errorCode = INVALID_PARAM;
4727         }
4728     }
4729     return errorCode;
4730 }
4731 
OnGetAbilityInfo(NativeEngine & engine,NativeCallbackInfo & info)4732 NativeValue* JsBundleMgr::OnGetAbilityInfo(NativeEngine &engine, NativeCallbackInfo &info)
4733 {
4734     APP_LOGD("%{public}s is called", __FUNCTION__);
4735     auto errorVal = std::make_shared<int32_t>(NAPI_ERR_NO_ERROR);
4736     std::shared_ptr<JsAbilityInfo> abilityInfo = std::make_shared<JsAbilityInfo>();
4737     if (info.argc < ARGS_SIZE_TWO || info.argc > ARGS_SIZE_FOUR) {
4738         APP_LOGE("wrong number of arguments.");
4739         return engine.CreateUndefined();
4740     }
4741     NativeValue *lastParam = nullptr;
4742     *errorVal = InitGetAbilityInfo(engine, info, lastParam, errMessage_, abilityInfo);
4743     auto execute = [obj = this, info = abilityInfo, value = errorVal] () {
4744         if (*value != NAPI_ERR_NO_ERROR || info == nullptr) {
4745             obj->errMessage_ = (info == nullptr) ? "Pointer is empty." : obj->errMessage_;
4746             *value = (info == nullptr) ? INVALID_PARAM : *value;
4747             return;
4748         }
4749         auto iBundleMgr = GetBundleMgr();
4750         if (iBundleMgr == nullptr) {
4751             APP_LOGE("can not get iBundleMgr");
4752             info->ret = false;
4753             return;
4754         }
4755         if (info->hasModuleName) {
4756             info->ret = iBundleMgr->GetAbilityInfo(
4757                 info->bundleName, info->moduleName, info->abilityName, info->abilityInfo);
4758             return;
4759         }
4760         info->ret = iBundleMgr->GetAbilityInfo(info->bundleName, info->abilityName, info->abilityInfo);
4761     };
4762     auto complete = [obj = this, value = errorVal, info = abilityInfo]
4763         (NativeEngine &engine, AsyncTask &task, int32_t status) {
4764         if (*value != NAPI_ERR_NO_ERROR || info == nullptr) {
4765             obj->errMessage_ = (info == nullptr) ? "Pointer is empty." : obj->errMessage_;
4766             *value = (info == nullptr) ? INVALID_PARAM : *value;
4767             task.RejectWithCustomize(engine, CreateJsValue(engine, *value), CreateJsValue(engine, obj->errMessage_));
4768             return;
4769         }
4770         if (!info->ret) {
4771             task.RejectWithCustomize(engine, CreateJsValue(engine, OPERATION_FAILED),
4772                 CreateJsValue(engine, engine.CreateUndefined()));
4773             return;
4774         }
4775         task.ResolveWithCustomize(engine, CreateJsValue(engine, 0), obj->CreateAbilityInfo(engine, info->abilityInfo));
4776     };
4777     NativeValue *result = nullptr;
4778     AsyncTask::Schedule("JsBundleMgr::OnGetAbilityInfo",
4779         engine, CreateAsyncTaskWithLastParam(engine, lastParam, std::move(execute), std::move(complete), &result));
4780     return result;
4781 }
4782 
InitGetAbilityLabel(NativeEngine & engine,NativeCallbackInfo & info,NativeValue * & lastParam,std::string & errMessage,std::shared_ptr<JsAbilityLabel> abilityLabel)4783 int32_t JsBundleMgr::InitGetAbilityLabel(NativeEngine &engine, NativeCallbackInfo &info, NativeValue *&lastParam,
4784     std::string &errMessage, std::shared_ptr<JsAbilityLabel> abilityLabel)
4785 {
4786     int32_t errorCode = NAPI_ERR_NO_ERROR;
4787     if (abilityLabel == nullptr) {
4788         errMessage = "Get an empty pointer.";
4789         return INVALID_PARAM;
4790     }
4791     abilityLabel->hasModuleName = false;
4792     if (info.argc > 0) {
4793         if (info.argv[info.argc - 1]->TypeOf() == NATIVE_FUNCTION) {
4794             abilityLabel->hasModuleName = (info.argc == ARGS_SIZE_FOUR) ? true : false;
4795         } else {
4796             abilityLabel->hasModuleName = (info.argc == ARGS_SIZE_THREE) ? true : false;
4797         }
4798     }
4799     for (size_t i = 0; i < info.argc; ++i) {
4800         if ((i == PARAM0) && (info.argv[i]->TypeOf() == NATIVE_STRING)) {
4801             ConvertFromJsValue(engine, info.argv[i], abilityLabel->bundleName);
4802         } else if ((i == PARAM1) && (info.argv[i]->TypeOf() == NATIVE_STRING)) {
4803             if (abilityLabel->hasModuleName) {
4804                 ConvertFromJsValue(engine, info.argv[i], abilityLabel->moduleName);
4805             } else {
4806                 ConvertFromJsValue(engine, info.argv[i], abilityLabel->className);
4807             }
4808         } else if ((i == PARAM2) && (info.argv[i]->TypeOf() == NATIVE_STRING)) {
4809             ConvertFromJsValue(engine, info.argv[i], abilityLabel->className);
4810         } else if (((i == PARAM2) || (i == PARAM3)) && (info.argv[i]->TypeOf() == NATIVE_FUNCTION)) {
4811             lastParam = info.argv[i];
4812         } else {
4813             errMessage = "type misMatch";
4814             errorCode = INVALID_PARAM;
4815         }
4816     }
4817     return errorCode;
4818 }
4819 
OnGetAbilityLabel(NativeEngine & engine,NativeCallbackInfo & info)4820 NativeValue* JsBundleMgr::OnGetAbilityLabel(NativeEngine &engine, NativeCallbackInfo &info)
4821 {
4822     APP_LOGD("%{public}s is called", __FUNCTION__);
4823     auto errorVal = std::make_shared<int32_t>(NAPI_ERR_NO_ERROR);
4824     std::shared_ptr<JsAbilityLabel> abilityLabel = std::make_shared<JsAbilityLabel>();
4825     if (info.argc < ARGS_SIZE_TWO || info.argc > ARGS_SIZE_FOUR) {
4826         APP_LOGE("wrong number of arguments.");
4827         return engine.CreateUndefined();
4828     }
4829     NativeValue *lastParam = nullptr;
4830     *errorVal = InitGetAbilityLabel(engine, info, lastParam, errMessage_, abilityLabel);
4831     auto execute = [obj = this, info = abilityLabel, value = errorVal] () {
4832         if (*value != NAPI_ERR_NO_ERROR || info == nullptr) {
4833             obj->errMessage_ = (info == nullptr) ? "Pointer is empty." : obj->errMessage_;
4834             *value = (info == nullptr) ? INVALID_PARAM : *value;
4835             return;
4836         }
4837         auto iBundleMgr = GetBundleMgr();
4838         if (iBundleMgr == nullptr) {
4839             APP_LOGE("can not get iBundleMgr");
4840             info->abilityLabel = Constants::EMPTY_STRING;
4841             return;
4842         }
4843         std::string label;
4844         if (!info->hasModuleName) {
4845             info->abilityLabel = iBundleMgr->GetAbilityLabel(info->bundleName, info->className);
4846             return;
4847         }
4848         ErrCode ret = iBundleMgr->GetAbilityLabel(
4849             info->bundleName, info->moduleName, info->className, label);
4850         if (ret != ERR_OK) {
4851             info->abilityLabel = Constants::EMPTY_STRING;
4852             return;
4853         }
4854         info->abilityLabel = label;
4855     };
4856     auto complete = [obj = this, value = errorVal, info = abilityLabel]
4857         (NativeEngine &engine, AsyncTask &task, int32_t status) {
4858         if (*value != NAPI_ERR_NO_ERROR || info == nullptr) {
4859             obj->errMessage_ = (info == nullptr) ? "Pointer is empty." : obj->errMessage_;
4860             *value = (info == nullptr) ? INVALID_PARAM : *value;
4861             task.RejectWithCustomize(engine, CreateJsValue(engine, *value),
4862                 CreateJsValue(engine, engine.CreateUndefined()));
4863             return;
4864         }
4865         if (info->abilityLabel == "") {
4866             task.RejectWithCustomize(engine, CreateJsValue(engine, OPERATION_FAILED),
4867                 CreateJsValue(engine, engine.CreateUndefined()));
4868             return;
4869         }
4870         task.ResolveWithNoError(engine, CreateJsValue(engine, info->abilityLabel));
4871     };
4872     NativeValue *result = nullptr;
4873     AsyncTask::Schedule("JsBundleMgr::OnGetAbilityLabel",
4874         engine, CreateAsyncTaskWithLastParam(engine, lastParam, std::move(execute), std::move(complete), &result));
4875     return result;
4876 }
4877 
OnSetApplicationEnabled(NativeEngine & engine,const NativeCallbackInfo & info)4878 NativeValue* JsBundleMgr::OnSetApplicationEnabled(NativeEngine &engine, const NativeCallbackInfo &info)
4879 {
4880     {
4881         std::lock_guard<std::mutex> lock(abilityInfoCacheMutex_);
4882         abilityInfoCache.clear();
4883     }
4884     APP_LOGD("%{public}s is called", __FUNCTION__);
4885     int32_t errCode = ERR_OK;
4886     std::string bundleName;
4887     bool isEnable = false;
4888     if (info.argc > ARGS_SIZE_THREE || info.argc < ARGS_SIZE_TWO) {
4889         APP_LOGE("wrong number of arguments!");
4890         errCode = INVALID_PARAM;
4891     }
4892     for (size_t i = 0; i < info.argc; ++i) {
4893         if ((i == PARAM0) && (info.argv[PARAM0]->TypeOf() == NATIVE_STRING)) {
4894             if (!ConvertFromJsValue(engine, info.argv[PARAM0], bundleName)) {
4895                 APP_LOGE("conversion failed!");
4896                 errCode= INVALID_PARAM;
4897             }
4898         } else if ((i == PARAM1) && (info.argv[PARAM1]->TypeOf() == NATIVE_BOOLEAN)) {
4899             if (!ConvertFromJsValue(engine, info.argv[PARAM1], isEnable)) {
4900                 APP_LOGE("conversion failed!");
4901                 errCode= INVALID_PARAM;
4902             }
4903         } else if ((i == PARAM2) && (info.argv[PARAM2]->TypeOf() == NATIVE_FUNCTION)) {
4904             break;
4905         } else {
4906             errCode = INVALID_PARAM;
4907         }
4908     }
4909     auto ret = std::make_shared<bool>(false);
4910     auto execute = [result = ret, bundleName, isEnable, errCode] () {
4911         if (errCode == ERR_OK) {
4912             *result = InnerSetApplicationEnabled(bundleName, isEnable);
4913             return;
4914         }
4915     };
4916     auto complete = [result = ret, isEnable, errCode]
4917         (NativeEngine &engine, AsyncTask &task, int32_t status) {
4918             if (errCode != ERR_OK) {
4919                 task.Reject(engine, CreateJsValue(engine, errCode));
4920                 return;
4921             }
4922             if (!(*result)) {
4923                 task.Reject(engine, CreateJsValue(engine, OPERATION_FAILED));
4924                 return;
4925             }
4926             task.ResolveWithCustomize(engine, engine.CreateUndefined(), engine.CreateUndefined());
4927     };
4928     NativeValue *result = nullptr;
4929     NativeValue *lastParam = (info.argc == ARGS_SIZE_TWO) ? nullptr : info.argv[PARAM2];
4930     AsyncTask::Schedule("JsBundleMgr::OnSetApplicationEnabled",
4931         engine, CreateAsyncTaskWithLastParam(engine, lastParam, std::move(execute), std::move(complete), &result));
4932     return result;
4933 }
4934 
OnSetAbilityEnabled(NativeEngine & engine,const NativeCallbackInfo & info)4935 NativeValue* JsBundleMgr::OnSetAbilityEnabled(NativeEngine &engine, const NativeCallbackInfo &info)
4936 {
4937     {
4938         std::lock_guard<std::mutex> lock(abilityInfoCacheMutex_);
4939         abilityInfoCache.clear();
4940     }
4941     APP_LOGD("%{public}s is called", __FUNCTION__);
4942     int32_t errCode = ERR_OK;
4943     bool isEnable = false;
4944     OHOS::AppExecFwk::AbilityInfo abilityInfo;
4945     auto env = reinterpret_cast<napi_env>(&engine);
4946     auto inputAbilityInfo = reinterpret_cast<napi_value>(info.argv[PARAM0]);
4947     if (info.argc > ARGS_SIZE_THREE || info.argc < ARGS_SIZE_TWO) {
4948         APP_LOGE("wrong number of arguments!");
4949         errCode = INVALID_PARAM;
4950     }
4951     for (size_t i = 0; i < info.argc; ++i) {
4952         if ((i == PARAM0) && (info.argv[PARAM0]->TypeOf() == NATIVE_OBJECT)) {
4953             if (!UnwrapAbilityInfo(env, inputAbilityInfo, abilityInfo)) {
4954                 APP_LOGE("conversion failed!");
4955                 errCode= INVALID_PARAM;
4956             }
4957         } else if ((i == PARAM1) && (info.argv[PARAM1]->TypeOf() == NATIVE_BOOLEAN)) {
4958             if (!ConvertFromJsValue(engine, info.argv[PARAM1], isEnable)) {
4959                 APP_LOGE("conversion failed!");
4960                 errCode= INVALID_PARAM;
4961             }
4962         } else if ((i == PARAM2) && (info.argv[PARAM2]->TypeOf() == NATIVE_FUNCTION)) {
4963             break;
4964         } else {
4965             errCode = INVALID_PARAM;
4966         }
4967     }
4968     auto ret = std::make_shared<bool>(false);
4969     auto execute = [result = ret, abilityInfo, isEnable, errCode] () {
4970         if (errCode == ERR_OK) {
4971             *result = InnerSetAbilityEnabled(abilityInfo, isEnable);
4972             return;
4973         }
4974     };
4975     auto complete = [result = ret, errCode]
4976         (NativeEngine &engine, AsyncTask &task, int32_t status) {
4977             if (errCode != ERR_OK) {
4978                 task.Reject(engine, CreateJsValue(engine, errCode));
4979                 return;
4980             }
4981             if (!*result) {
4982                 task.Reject(engine, CreateJsValue(engine, OPERATION_FAILED));
4983                 return;
4984             }
4985             task.ResolveWithCustomize(engine, CreateJsValue(engine, errCode), CreateJsValue(engine, errCode));
4986     };
4987     NativeValue *result = nullptr;
4988     NativeValue *lastParam = (info.argc == ARGS_SIZE_TWO) ? nullptr : info.argv[PARAM2];
4989     AsyncTask::Schedule("JsBundleMgr::OnSetAbilityEnabled",
4990         engine, CreateAsyncTaskWithLastParam(engine, lastParam, std::move(execute), std::move(complete), &result));
4991     return result;
4992 }
4993 
OnQueryAbilityInfos(NativeEngine & engine,NativeCallbackInfo & info)4994 NativeValue* JsBundleMgr::OnQueryAbilityInfos(NativeEngine &engine, NativeCallbackInfo &info)
4995 {
4996     APP_LOGD("%{public}s is called", __FUNCTION__);
4997     int32_t errCode = ERR_OK;
4998     int32_t bundleFlags = -1;
4999     int32_t userId = IPCSkeleton::GetCallingUid() / Constants::BASE_USER_RANGE;
5000     AAFwk::Want want;
5001     auto env = reinterpret_cast<napi_env>(&engine);
5002     auto inputWant = reinterpret_cast<napi_value>(info.argv[PARAM0]);
5003     if (info.argc > ARGS_SIZE_FOUR || info.argc < ARGS_SIZE_TWO) {
5004         APP_LOGE("wrong number of arguments!");
5005         errCode = PARAM_TYPE_ERROR;
5006     }
5007     if (!ParseWant(env, want, inputWant)) {
5008         APP_LOGE("parse want faile.");
5009         errCode = PARAM_TYPE_ERROR;
5010     }
5011     if (info.argv[PARAM1]->TypeOf() != NATIVE_NUMBER) {
5012         APP_LOGE("input params is not number!");
5013         errCode = PARAM_TYPE_ERROR;
5014     }
5015     ConvertFromJsValue(engine, info.argv[PARAM1], bundleFlags);
5016     NativeValue* lastParam = UnwarpQueryAbilityInfoParams(engine, info, userId, errCode);
5017 
5018     std::shared_ptr<JsQueryAbilityInfo> queryAbilityInfo = std::make_shared<JsQueryAbilityInfo>();
5019     auto execute = [want, bundleFlags, userId, info = queryAbilityInfo, &engine] () {
5020         {
5021             std::lock_guard<std::mutex> lock(abilityInfoCacheMutex_);
5022             auto env = reinterpret_cast<napi_env>(&engine);
5023             auto item = nativeAbilityInfoCache.find(Query(want.ToString(),
5024                 QUERY_ABILITY_BY_WANT, bundleFlags, userId, env));
5025             if (item != nativeAbilityInfoCache.end()) {
5026                 APP_LOGD("has cache,no need to query from host");
5027                 info->getCache = true;
5028                 return;
5029             }
5030         }
5031         auto iBundleMgr = GetBundleMgr();
5032         if (iBundleMgr == nullptr) {
5033             APP_LOGE("can not get iBundleMgr");
5034             info->ret = false;
5035             return;
5036         }
5037         info->ret = iBundleMgr->QueryAbilityInfos(want, bundleFlags, userId, info->abilityInfos);
5038     };
5039 
5040     AsyncTask::CompleteCallback complete = [obj = this, want, bundleFlags, userId, errCode, info = queryAbilityInfo]
5041         (NativeEngine &engine, AsyncTask &task, int32_t status) {
5042             std::string queryAbilityInfosErrData;
5043             auto env = reinterpret_cast<napi_env>(&engine);
5044             if (info->getCache) {
5045                 NativeValue *cacheAbilityInfos;
5046                 auto item = nativeAbilityInfoCache.find(Query(want.ToString(),
5047                     QUERY_ABILITY_BY_WANT, bundleFlags, userId, env));
5048                 cacheAbilityInfos  = item->second->Get();
5049                 APP_LOGD("has cache,no need to query from host");
5050                 task.ResolveWithCustomize(engine, CreateJsValue(engine, 0), cacheAbilityInfos);
5051                 return;
5052             }
5053             if (errCode != ERR_OK) {
5054                 queryAbilityInfosErrData = "type mismatch";
5055                 task.RejectWithCustomize(engine, CreateJsValue(engine, errCode),
5056                     CreateJsValue(engine, queryAbilityInfosErrData));
5057                 return;
5058             }
5059             if (!info->ret) {
5060                 queryAbilityInfosErrData = "QueryAbilityInfos failed";
5061                 task.RejectWithCustomize(engine, CreateJsValue(engine, 1),
5062                     CreateJsValue(engine, queryAbilityInfosErrData));
5063                 return;
5064             }
5065             NativeValue *cacheAbilityInfoValue = nullptr;
5066             {
5067                 std::lock_guard<std::mutex> lock(abilityInfoCacheMutex_);
5068                 Query query(want.ToString(), QUERY_ABILITY_BY_WANT, bundleFlags, userId, env);
5069                 cacheAbilityInfoValue = obj->CreateAbilityInfos(engine, info->abilityInfos);
5070                 OnHandleAbilityInfoCache(engine, query, want, info->abilityInfos, cacheAbilityInfoValue);
5071             }
5072             task.ResolveWithCustomize(engine, CreateJsValue(engine, 0), cacheAbilityInfoValue);
5073     };
5074 
5075     NativeValue* result = nullptr;
5076     AsyncTask::Schedule("JsBundleMgr::OnQueryAbilityInfos",
5077         engine, CreateAsyncTaskWithLastParam(engine, lastParam, std::move(execute), std::move(complete), &result));
5078     return result;
5079 }
5080 
OnGetAllBundleInfo(NativeEngine & engine,NativeCallbackInfo & info)5081 NativeValue* JsBundleMgr::OnGetAllBundleInfo(NativeEngine &engine, NativeCallbackInfo &info)
5082 {
5083     APP_LOGD("%{public}s is called", __FUNCTION__);
5084     int32_t errCode = ERR_OK;
5085     int32_t bundleFlags = 0;
5086     std::shared_ptr<std::vector<BundleInfo>> bundleInfos = std::make_shared<std::vector<BundleInfo>>();
5087     if (info.argc > ARGS_SIZE_THREE || info.argc < ARGS_SIZE_ONE) {
5088         APP_LOGE("wrong number of arguments!");
5089         errCode = PARAM_TYPE_ERROR;
5090     } else {
5091         if (!ConvertFromJsValue(engine, info.argv[PARAM0], bundleFlags)) {
5092             APP_LOGE("conversion failed!");
5093             errCode = PARAM_TYPE_ERROR;
5094         }
5095     }
5096     int32_t userId = Constants::UNSPECIFIED_USERID;
5097     bool flagCall = UnwarpUserIdThreeParams(engine, info, userId);
5098     auto apiResult = std::make_shared<bool>();
5099     auto execute = [obj = this, bundleFlags, userId, infos = bundleInfos, ret = apiResult] () {
5100         *ret = InnerGetBundleInfos(bundleFlags, userId, *infos);
5101     };
5102     auto complete = [obj = this, errCode, ret = apiResult, infos = bundleInfos]
5103         (NativeEngine &engine, AsyncTask &task, int32_t status) {
5104         if (errCode != ERR_OK) {
5105             std::string getAllBundleInfoErrData = "type mismatch";
5106             task.RejectWithCustomize(engine, CreateJsValue(engine, errCode),
5107                 CreateJsValue(engine, getAllBundleInfoErrData));
5108             return;
5109         }
5110         if (!*ret) {
5111             task.RejectWithCustomize(engine, CreateJsValue(engine, 1), engine.CreateUndefined());
5112             return;
5113         }
5114         task.ResolveWithCustomize(engine, CreateJsValue(engine, 0), obj->CreateBundleInfos(engine, *infos));
5115     };
5116 
5117     NativeValue *result = nullptr;
5118     NativeValue *callback = nullptr;
5119     if (flagCall) {
5120         if (info.argc == ARGS_SIZE_TWO || info.argc == ARGS_SIZE_THREE) {
5121             callback = (info.argc == ARGS_SIZE_TWO) ? info.argv[PARAM1] : info.argv[PARAM2];
5122         }
5123     }
5124 
5125     AsyncTask::Schedule("JsBundleMgr::OnGetAllBundleInfo",
5126         engine, CreateAsyncTaskWithLastParam(engine, callback, std::move(execute), std::move(complete), &result));
5127     return result;
5128 }
5129 
OnGetPermissionDef(NativeEngine & engine,NativeCallbackInfo & info)5130 NativeValue* JsBundleMgr::OnGetPermissionDef(NativeEngine &engine, NativeCallbackInfo &info)
5131 {
5132     APP_LOGD("%{public}s is called", __FUNCTION__);
5133     int32_t errCode = ERR_OK;
5134     auto jsInfo = std::make_shared<JsGetPermissionDef>();
5135     if (info.argc > ARGS_SIZE_TWO || info.argc < ARGS_SIZE_ONE) {
5136         APP_LOGE("wrong number of arguments!");
5137         errCode = PARAM_TYPE_ERROR;
5138     }
5139 
5140     if (info.argv[PARAM0]->TypeOf() == NATIVE_STRING) {
5141         if (!ConvertFromJsValue(engine, info.argv[PARAM0], jsInfo->permissionName)) {
5142             APP_LOGE("conversion failed!");
5143             errCode = PARAM_TYPE_ERROR;
5144         }
5145     } else {
5146         APP_LOGE("input params is not string!");
5147         errCode = PARAM_TYPE_ERROR;
5148     }
5149     auto execute = [info = jsInfo, errCode] () {
5150         if (errCode == ERR_OK) {
5151             info->ret = InnerGetPermissionDef(info->permissionName, info->permissionDef);
5152             return;
5153         }
5154     };
5155     auto complete = [obj = this, info = jsInfo, errCode]
5156         (NativeEngine &engine, AsyncTask &task, int32_t status) {
5157             OHOS::AppExecFwk::PermissionDef permissionDef;
5158             if (errCode != ERR_OK) {
5159                 std::string errMessage = "type mismatch";
5160                 task.RejectWithCustomize(
5161                     engine, CreateJsValue(engine, errCode), CreateJsValue(engine, errMessage));
5162                 return;
5163             }
5164             if (info == nullptr) {
5165                 std::string errMessage = "Parameter is empty.";
5166                 task.RejectWithCustomize(
5167                     engine, CreateJsValue(engine, INVALID_PARAM), CreateJsValue(engine, errMessage));
5168                 return;
5169             }
5170             if (!info->ret) {
5171                 task.Reject(engine, CreateJsValue(engine, OPERATION_FAILED));
5172                 return;
5173             }
5174             task.ResolveWithCustomize(
5175                 engine, CreateJsValue(engine, CODE_SUCCESS), obj->CreatePermissionDef(engine, info->permissionDef));
5176     };
5177     NativeValue *lastParam = (info.argc == ARGS_SIZE_ONE) ? nullptr : info.argv[PARAM1];
5178     NativeValue *result = nullptr;
5179     AsyncTask::Schedule("JsBundleMgr::OnGetPermissionDef",
5180         engine, CreateAsyncTaskWithLastParam(engine, lastParam, std::move(execute), std::move(complete), &result));
5181     return result;
5182 }
5183 
OnGetBundleInstaller(NativeEngine & engine,const NativeCallbackInfo & info)5184 NativeValue* JsBundleMgr::OnGetBundleInstaller(NativeEngine &engine, const NativeCallbackInfo &info)
5185 {
5186     APP_LOGI("%{public}s is called", __FUNCTION__);
5187     if (info.argc > ARGS_SIZE_ONE) {
5188         APP_LOGE("wrong number of arguments!");
5189         return engine.CreateUndefined();
5190     }
5191 
5192     AsyncTask::CompleteCallback complete = [obj = this](NativeEngine &engine, AsyncTask &task, int32_t status) {
5193             if (!VerifySystemApi()) {
5194                 APP_LOGE("GetBundleInstaller caller is not system app");
5195                 task.Reject(engine, CreateJsValue(engine, 1));
5196                 return;
5197             }
5198             if (!VerifyCallingPermission(Constants::PERMISSION_INSTALL_BUNDLE)) {
5199                 APP_LOGE("GetBundleInstaller no permission!");
5200                 task.Reject(engine, CreateJsValue(engine, 1));
5201                 return;
5202             }
5203 
5204             auto ret = obj->JsBundleInstallInit(engine);
5205             if (ret == nullptr) {
5206                 APP_LOGE("bind func failed");
5207             }
5208             task.Resolve(engine, ret);
5209     };
5210 
5211     NativeValue* lastParam = (info.argc == ARGS_SIZE_ONE) ? info.argv[PARAM0] : nullptr;
5212     NativeValue* result = nullptr;
5213     AsyncTask::Schedule("JsBundleMgr::OnGetBundleInstaller",
5214         engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
5215     return result;
5216 }
5217 
JsBundleInstallInit(NativeEngine & engine)5218 NativeValue* JsBundleMgr::JsBundleInstallInit(NativeEngine &engine)
5219 {
5220     APP_LOGD("JsBundleMgrInit is called");
5221     auto objBundleInstall = engine.CreateObject();
5222     if (objBundleInstall == nullptr) {
5223         APP_LOGE("CreateObject failed");
5224         return nullptr;
5225     }
5226     auto object = ConvertNativeValueTo<NativeObject>(objBundleInstall);
5227     if (object == nullptr) {
5228         APP_LOGE("ConvertNativeValueTo object failed");
5229         return nullptr;
5230     }
5231 
5232     auto jsCalss = std::make_unique<JsBundleInstall>();
5233     object->SetNativePointer(jsCalss.release(), JsBundleInstall::Finalizer, nullptr);
5234     const char *moduleName = "JsBundleInstall";
5235     BindNativeFunction(engine, *object, "install", moduleName, JsBundleInstall::Install);
5236     BindNativeFunction(engine, *object, "recover", moduleName, JsBundleInstall::Recover);
5237     BindNativeFunction(engine, *object, "uninstall", moduleName, JsBundleInstall::Uninstall);
5238 
5239     return objBundleInstall;
5240 }
5241 
Finalizer(NativeEngine * engine,void * data,void * hint)5242 void JsBundleInstall::Finalizer(NativeEngine *engine, void *data, void *hint)
5243 {
5244     APP_LOGI("JsBundleInstall::Finalizer is called");
5245     std::unique_ptr<JsBundleInstall>(static_cast<JsBundleInstall*>(data));
5246 }
5247 
Install(NativeEngine * engine,NativeCallbackInfo * info)5248 NativeValue* JsBundleInstall::Install(NativeEngine *engine, NativeCallbackInfo *info)
5249 {
5250     JsBundleInstall* me = CheckParamsAndGetThis<JsBundleInstall>(engine, info);
5251     return (me != nullptr) ? me->OnInstall(*engine, *info) : nullptr;
5252 }
5253 
Recover(NativeEngine * engine,NativeCallbackInfo * info)5254 NativeValue* JsBundleInstall::Recover(NativeEngine *engine, NativeCallbackInfo *info)
5255 {
5256     JsBundleInstall* me = CheckParamsAndGetThis<JsBundleInstall>(engine, info);
5257     return (me != nullptr) ? me->OnRecover(*engine, *info) : nullptr;
5258 }
5259 
Uninstall(NativeEngine * engine,NativeCallbackInfo * info)5260 NativeValue* JsBundleInstall::Uninstall(NativeEngine *engine, NativeCallbackInfo *info)
5261 {
5262     JsBundleInstall* me = CheckParamsAndGetThis<JsBundleInstall>(engine, info);
5263     return (me != nullptr) ? me->OnUninstall(*engine, *info) : nullptr;
5264 }
5265 
CreateInstallStatus(NativeEngine & engine,const std::shared_ptr<BundleInstallResult> bundleInstallResult)5266 NativeValue* JsBundleInstall::CreateInstallStatus(NativeEngine &engine,
5267     const std::shared_ptr<BundleInstallResult> bundleInstallResult)
5268 {
5269     APP_LOGD("CreateInstallStatus is called");
5270     auto objContext = engine.CreateObject();
5271     if (objContext == nullptr) {
5272         APP_LOGE("CreateObject failed");
5273         return engine.CreateUndefined();
5274     }
5275 
5276     auto object = ConvertNativeValueTo<NativeObject>(objContext);
5277     if (object == nullptr) {
5278         APP_LOGE("ConvertNativeValueTo object failed");
5279         return engine.CreateUndefined();
5280     }
5281 
5282     object->SetProperty("status", CreateJsValue(engine, bundleInstallResult->resCode));
5283     object->SetProperty("statusMessage", CreateJsValue(engine, bundleInstallResult->resMessage));
5284 
5285     return objContext;
5286 }
OnInstall(NativeEngine & engine,NativeCallbackInfo & info)5287 NativeValue* JsBundleInstall::OnInstall(NativeEngine &engine, NativeCallbackInfo &info)
5288 {
5289     APP_LOGD("%{public}s is called", __FUNCTION__);
5290 
5291     std::vector<std::string> bundleFilePaths;
5292     std::shared_ptr<BundleInstallResult> installResult = std::make_shared<BundleInstallResult>();
5293     InstallParam installParam;
5294     if (info.argc != ARGS_SIZE_THREE) {
5295         APP_LOGE("wrong number of arguments!");
5296         installResult->resCode = PARAM_TYPE_ERROR;
5297     }
5298     if (!info.argv[PARAM0]->IsArray()) {
5299         APP_LOGE("input params is not array!");
5300         installResult->resCode = PARAM_TYPE_ERROR;
5301     } else if (!GetStringsValue(engine, info.argv[PARAM0], bundleFilePaths)) {
5302         APP_LOGE("conversion failed!");
5303         installResult->resCode= PARAM_TYPE_ERROR;
5304     }
5305     if (info.argv[PARAM1]->TypeOf() != NATIVE_OBJECT) {
5306         APP_LOGE("input params is not array!");
5307         installResult->resCode = PARAM_TYPE_ERROR;
5308     } else if (!GetInstallParamValue(engine, info.argv[PARAM1], installParam)) {
5309         APP_LOGE("conversion failed!");
5310         installResult->resCode= PARAM_TYPE_ERROR;
5311     }
5312     AsyncTask::CompleteCallback complete = [obj = this, bundleFilePaths, installParam, resInstall = installResult]
5313         (NativeEngine &engine, AsyncTask &task, int32_t status) {
5314             if (resInstall->resCode != 0) {
5315                 task.Reject(engine, CreateJsError(engine, resInstall->resCode));
5316                 return;
5317             }
5318             auto iBundleMgr = GetBundleMgr();
5319             if (iBundleMgr == nullptr) {
5320                 APP_LOGE("iBundleMgr is nullptr");
5321                 return;
5322             }
5323             auto iBundleInstaller = iBundleMgr->GetBundleInstaller();
5324             if ((iBundleInstaller == nullptr) || (iBundleInstaller->AsObject() == nullptr)) {
5325                 APP_LOGE("can not get iBundleInstaller");
5326                 task.Reject(engine, CreateJsError(engine, OPERATION_FAILED));
5327                 return;
5328             }
5329 
5330             OHOS::sptr<InstallerCallback> callback = new (std::nothrow) InstallerCallback();
5331             if (callback == nullptr) {
5332                 APP_LOGE("callback nullptr");
5333                 task.Reject(engine, CreateJsError(engine, OPERATION_FAILED));
5334                 return;
5335             }
5336             sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(callback));
5337             iBundleInstaller->AsObject()->AddDeathRecipient(recipient);
5338             ErrCode res = iBundleInstaller->StreamInstall(bundleFilePaths, installParam, callback);
5339             if (res == ERR_APPEXECFWK_INSTALL_PARAM_ERROR) {
5340                 APP_LOGE("install param error");
5341                 resInstall->resCode = IStatusReceiver::ERR_INSTALL_PARAM_ERROR;
5342                 resInstall->resMessage = "STATUS_INSTALL_FAILURE_INVALID";
5343             } else if (res == ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID) {
5344                 APP_LOGE("install invalid path");
5345                 resInstall->resCode = IStatusReceiver::ERR_INSTALL_FILE_PATH_INVALID;
5346                 resInstall->resMessage = "STATUS_INSTALL_FAILURE_INVALID";
5347             } else {
5348                 resInstall->resCode = callback->GetResultCode();
5349                 APP_LOGD("Install resultCode %{public}d", resInstall->resCode);
5350                 resInstall->resMessage = callback->GetResultMsg();
5351                 APP_LOGD("Install resultMsg %{public}s", resInstall->resMessage.c_str());
5352             }
5353             obj->ConvertInstallResult(resInstall);
5354             task.Resolve(engine, obj->CreateInstallStatus(engine, resInstall));
5355     };
5356     NativeValue* lastParam = info.argv[PARAM2];
5357     NativeValue* result = nullptr;
5358     AsyncTask::Schedule("JsBundleInstall::OnInstall",
5359         engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
5360     return result;
5361 }
5362 
OnRecover(NativeEngine & engine,NativeCallbackInfo & info)5363 NativeValue* JsBundleInstall::OnRecover(NativeEngine &engine, NativeCallbackInfo &info)
5364 {
5365     APP_LOGD("%{public}s is called", __FUNCTION__);
5366     std::string bundleName;
5367     std::shared_ptr<BundleInstallResult> installResult = std::make_shared<BundleInstallResult>();
5368     InstallParam installParam;
5369 
5370     if (info.argc != ARGS_SIZE_THREE) {
5371         APP_LOGE("wrong number of arguments!");
5372         installResult->resCode = PARAM_TYPE_ERROR;
5373     }
5374     if (info.argv[PARAM0]->TypeOf() != NATIVE_STRING) {
5375         APP_LOGE("input params is not string!");
5376         installResult->resCode = PARAM_TYPE_ERROR;
5377     } else if (!ConvertFromJsValue(engine, info.argv[PARAM0], bundleName)) {
5378         APP_LOGE("conversion failed!");
5379         installResult->resCode= PARAM_TYPE_ERROR;
5380     }
5381     if (info.argv[PARAM1]->TypeOf() != NATIVE_OBJECT) {
5382         APP_LOGE("input params is not array!");
5383         installResult->resCode = PARAM_TYPE_ERROR;
5384     } else if (!GetInstallParamValue(engine, info.argv[PARAM1], installParam)) {
5385         APP_LOGE("conversion failed!");
5386         installResult->resCode= PARAM_TYPE_ERROR;
5387     }
5388     AsyncTask::CompleteCallback complete = [obj = this, bundleName, installParam, resInstall = installResult]
5389         (NativeEngine &engine, AsyncTask &task, int32_t status) {
5390             if (resInstall->resCode != ERR_OK) {
5391                 task.Reject(engine, CreateJsError(engine, resInstall->resCode));
5392                 return;
5393             }
5394             auto iBundleMgr = GetBundleMgr();
5395             if (iBundleMgr == nullptr) {
5396                 APP_LOGE("iBundleMgr is nullptr");
5397                 return;
5398             }
5399             auto iBundleInstaller = iBundleMgr->GetBundleInstaller();
5400             if ((iBundleInstaller == nullptr) || (iBundleInstaller->AsObject() == nullptr)) {
5401                 APP_LOGE("can not get iBundleInstaller");
5402                 task.Reject(engine, CreateJsError(engine, OPERATION_FAILED));
5403                 return;
5404             }
5405             OHOS::sptr<InstallerCallback> callback = new (std::nothrow) InstallerCallback();
5406             if (callback == nullptr) {
5407                 APP_LOGE("callback nullptr");
5408                 task.Reject(engine, CreateJsError(engine, OPERATION_FAILED));
5409                 return;
5410             }
5411 
5412             sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(callback));
5413             iBundleInstaller->AsObject()->AddDeathRecipient(recipient);
5414             iBundleInstaller->Recover(bundleName, installParam, callback);
5415             resInstall->resCode = callback->GetResultCode();
5416             APP_LOGD("Recover resultCode %{public}d", resInstall->resCode);
5417             resInstall->resMessage = callback->GetResultMsg();
5418             APP_LOGD("Recover resultMsg %{public}s", resInstall->resMessage.c_str());
5419             obj->ConvertInstallResult(resInstall);
5420             task.Resolve(engine, obj->CreateInstallStatus(engine, resInstall));
5421     };
5422     NativeValue* lastParam = info.argv[PARAM2];
5423     NativeValue* result = nullptr;
5424     AsyncTask::Schedule("JsBundleInstall::OnRecover",
5425         engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
5426     return result;
5427 }
5428 
OnUninstall(NativeEngine & engine,NativeCallbackInfo & info)5429 NativeValue* JsBundleInstall::OnUninstall(NativeEngine &engine, NativeCallbackInfo &info)
5430 {
5431     APP_LOGD("%{public}s is called", __FUNCTION__);
5432     std::string bundleName;
5433     std::shared_ptr<BundleInstallResult> installResult = std::make_shared<BundleInstallResult>();
5434     InstallParam installParam;
5435 
5436     if (info.argc != ARGS_SIZE_THREE) {
5437         APP_LOGE("wrong number of arguments!");
5438         installResult->resCode = PARAM_TYPE_ERROR;
5439     }
5440     if (info.argv[PARAM0]->TypeOf() != NATIVE_STRING) {
5441         APP_LOGE("input params is not string!");
5442         installResult->resCode = PARAM_TYPE_ERROR;
5443     } else if (!ConvertFromJsValue(engine, info.argv[PARAM0], bundleName)) {
5444         APP_LOGE("conversion failed!");
5445         installResult->resCode= PARAM_TYPE_ERROR;
5446     }
5447     if (info.argv[PARAM1]->TypeOf() != NATIVE_OBJECT) {
5448         APP_LOGE("input params is not array!");
5449         installResult->resCode = PARAM_TYPE_ERROR;
5450     } else if (!GetInstallParamValue(engine, info.argv[PARAM1], installParam)) {
5451         APP_LOGE("conversion failed!");
5452         installResult->resCode= PARAM_TYPE_ERROR;
5453     }
5454     installParam.installFlag = InstallFlag::NORMAL;
5455     AsyncTask::CompleteCallback complete = [obj = this, bundleName, installParam, resInstall = installResult]
5456         (NativeEngine &engine, AsyncTask &task, int32_t status) {
5457             if (resInstall->resCode != ERR_OK) {
5458                 task.Reject(engine, CreateJsError(engine, resInstall->resCode));
5459                 return;
5460             }
5461             auto iBundleMgr = GetBundleMgr();
5462             if (iBundleMgr == nullptr) {
5463                 APP_LOGE("iBundleMgr is nullptr");
5464                 return;
5465             }
5466             auto iBundleInstaller = iBundleMgr->GetBundleInstaller();
5467             if ((iBundleInstaller == nullptr) || (iBundleInstaller->AsObject() == nullptr)) {
5468                 APP_LOGE("can not get iBundleInstaller");
5469                 task.Reject(engine, CreateJsError(engine, OPERATION_FAILED));
5470                 return;
5471             }
5472 
5473             OHOS::sptr<InstallerCallback> callback = new (std::nothrow) InstallerCallback();
5474             if (callback == nullptr) {
5475                 APP_LOGE("callback nullptr");
5476                 task.Reject(engine, CreateJsError(engine, OPERATION_FAILED));
5477                 return;
5478             }
5479             sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(callback));
5480             iBundleInstaller->AsObject()->AddDeathRecipient(recipient);
5481             iBundleInstaller->Uninstall(bundleName, installParam, callback);
5482             resInstall->resCode = callback->GetResultCode();
5483             APP_LOGD("Uninstall resultCode %{public}d", resInstall->resCode);
5484             resInstall->resMessage = callback->GetResultMsg();
5485             APP_LOGD("Uninstall resultMsg %{public}s", resInstall->resMessage.c_str());
5486             obj->ConvertInstallResult(resInstall);
5487             task.Resolve(engine, obj->CreateInstallStatus(engine, resInstall));
5488     };
5489     NativeValue* lastParam = info.argv[PARAM2];
5490     NativeValue* result = nullptr;
5491     AsyncTask::Schedule("JsBundleInstall::OnUninstall",
5492         engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
5493     return result;
5494 }
GetStringsValue(NativeEngine & engine,NativeValue * object,std::vector<std::string> & strList)5495 bool JsBundleInstall::GetStringsValue(NativeEngine &engine, NativeValue *object, std::vector<std::string> &strList)
5496 {
5497     auto array = ConvertNativeValueTo<NativeArray>(object);
5498     if (array == nullptr) {
5499         APP_LOGE("input params error");
5500         return false;
5501     }
5502 
5503     for (uint32_t i = 0; i < array->GetLength(); i++) {
5504         std::string itemStr("");
5505         if ((array->GetElement(i))->TypeOf() != NATIVE_STRING) {
5506             APP_LOGE("GetElement is not string");
5507             return false;
5508         }
5509         if (!ConvertFromJsValue(engine, array->GetElement(i), itemStr)) {
5510             APP_LOGE("GetElement from to array [%{public}u] error", i);
5511             return false;
5512         }
5513         strList.push_back(itemStr);
5514     }
5515 
5516     return true;
5517 }
5518 
GetInstallParamValue(NativeEngine & engine,NativeValue * object,InstallParam & installParam)5519 bool JsBundleInstall::GetInstallParamValue(NativeEngine &engine, NativeValue *object, InstallParam &installParam)
5520 {
5521     auto env = reinterpret_cast<napi_env>(&engine);
5522     auto param = reinterpret_cast<napi_value>(object);
5523     if (!ParseInstallParam(env, installParam, param)) {
5524         APP_LOGE("ParseInstallParam fail");
5525         return false;
5526     }
5527     return true;
5528 }
5529 
ConvertInstallResult(std::shared_ptr<BundleInstallResult> installResult)5530 void JsBundleInstall::ConvertInstallResult(std::shared_ptr<BundleInstallResult> installResult)
5531 {
5532     APP_LOGD("ConvertInstallResult = %{public}s.", installResult->resMessage.c_str());
5533     switch (installResult->resCode) {
5534         case static_cast<int32_t>(IStatusReceiver::SUCCESS):
5535             installResult->resCode = static_cast<int32_t>(InstallErrorCode::SUCCESS);
5536             installResult->resMessage = "SUCCESS";
5537             break;
5538         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_INTERNAL_ERROR):
5539         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_HOST_INSTALLER_FAILED):
5540         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_DISALLOWED):
5541             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE);
5542             installResult->resMessage = "STATUS_INSTALL_FAILURE";
5543             break;
5544         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_FAILED):
5545         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_VERIFICATION_FAILED):
5546         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_INCOMPATIBLE_SIGNATURE):
5547         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARAM_ERROR):
5548         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FILE_PATH_INVALID):
5549         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_INVALID_HAP_SIZE):
5550         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_INVALID_HAP_NAME):
5551         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_INVALID_BUNDLE_FILE):
5552         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_INVALID_NUMBER_OF_ENTRY_HAP):
5553         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_UNEXPECTED):
5554         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_MISSING_BUNDLE):
5555         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_NO_PROFILE):
5556         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_BAD_PROFILE):
5557         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_PROFILE_PROP_TYPE_ERROR):
5558         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_PROFILE_MISSING_PROP):
5559         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_PERMISSION_ERROR):
5560         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_RPCID_FAILED):
5561         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_NATIVE_SO_FAILED):
5562         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_INVALID_SIGNATURE_FILE_PATH):
5563         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_BAD_BUNDLE_SIGNATURE_FILE):
5564         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_NO_BUNDLE_SIGNATURE):
5565         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_VERIFY_APP_PKCS7_FAIL):
5566         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_PROFILE_PARSE_FAIL):
5567         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_APP_SOURCE_NOT_TRUESTED):
5568         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_BAD_DIGEST):
5569         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_BUNDLE_INTEGRITY_VERIFICATION_FAILURE):
5570         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_FILE_SIZE_TOO_LARGE):
5571         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_BAD_PUBLICKEY):
5572         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_BAD_BUNDLE_SIGNATURE):
5573         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_NO_PROFILE_BLOCK_FAIL):
5574         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_BUNDLE_SIGNATURE_VERIFICATION_FAILURE):
5575         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_MODULE_NAME_EMPTY):
5576         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_MODULE_NAME_DUPLICATE):
5577         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_CHECK_HAP_HASH_PARAM):
5578         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_VERIFY_SOURCE_INIT_FAIL):
5579         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_DEPENDENT_MODULE_NOT_EXIST):
5580         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_DEBUG_NOT_SAME):
5581             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_INVALID);
5582             installResult->resMessage = "STATUS_INSTALL_FAILURE_INVALID";
5583             break;
5584         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PARSE_MISSING_ABILITY):
5585             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_ABILITY_NOT_FOUND);
5586             installResult->resMessage = "STATUS_ABILITY_NOT_FOUND";
5587             break;
5588         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_VERSION_DOWNGRADE):
5589         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_FAILED_INCONSISTENT_SIGNATURE):
5590             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_INCOMPATIBLE);
5591             installResult->resMessage = "STATUS_INSTALL_FAILURE_INCOMPATIBLE";
5592             break;
5593         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_PERMISSION_DENIED):
5594             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_PERMISSION_DENIED);
5595             installResult->resMessage = "STATUS_INSTALL_PERMISSION_DENIED";
5596             break;
5597         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_ENTRY_ALREADY_EXIST):
5598         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_ALREADY_EXIST):
5599         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_BUNDLENAME_NOT_SAME):
5600         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_VERSIONCODE_NOT_SAME):
5601         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_VERSIONNAME_NOT_SAME):
5602         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_MINCOMPATIBLE_VERSIONCODE_NOT_SAME):
5603         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_VENDOR_NOT_SAME):
5604         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_RELEASETYPE_TARGET_NOT_SAME):
5605         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_RELEASETYPE_COMPATIBLE_NOT_SAME):
5606         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_SINGLETON_NOT_SAME):
5607         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_ZERO_USER_WITH_NO_SINGLETON):
5608         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_CHECK_SYSCAP_FAILED):
5609         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_APPTYPE_NOT_SAME):
5610         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_URI_DUPLICATE):
5611         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_VERSION_NOT_COMPATIBLE):
5612         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_APP_DISTRIBUTION_TYPE_NOT_SAME):
5613         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_APP_PROVISION_TYPE_NOT_SAME):
5614         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_SO_INCOMPATIBLE):
5615         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_TYPE_ERROR):
5616         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_NOT_UNIQUE_DISTRO_MODULE_NAME):
5617         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_SINGLETON_INCOMPATIBLE):
5618         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_INCONSISTENT_MODULE_NAME):
5619             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_CONFLICT);
5620             installResult->resMessage = "STATUS_INSTALL_FAILURE_CONFLICT";
5621             break;
5622         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALLD_PARAM_ERROR):
5623         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALLD_GET_PROXY_ERROR):
5624         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALLD_CREATE_DIR_FAILED):
5625         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALLD_SET_SELINUX_LABEL_FAILED):
5626         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALLD_CREATE_DIR_EXIST):
5627         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALLD_CHOWN_FAILED):
5628         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALLD_REMOVE_DIR_FAILED):
5629         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALLD_EXTRACT_FILES_FAILED):
5630         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALLD_RNAME_DIR_FAILED):
5631         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALLD_CLEAN_DIR_FAILED):
5632         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_STATE_ERROR):
5633         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_GENERATE_UID_ERROR):
5634         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_INSTALLD_SERVICE_ERROR):
5635             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_INSTALL_FAILURE_STORAGE);
5636             installResult->resMessage = "STATUS_INSTALL_FAILURE_STORAGE";
5637             break;
5638         case static_cast<int32_t>(IStatusReceiver::ERR_UNINSTALL_PERMISSION_DENIED):
5639             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_UNINSTALL_PERMISSION_DENIED);
5640             installResult->resMessage = "STATUS_UNINSTALL_PERMISSION_DENIED";
5641             break;
5642         case static_cast<int32_t>(IStatusReceiver::ERR_UNINSTALL_INVALID_NAME):
5643         case static_cast<int32_t>(IStatusReceiver::ERR_UNINSTALL_PARAM_ERROR):
5644             if (CheckIsSystemApp()) {
5645                 installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_UNINSTALL_FAILURE_ABORTED);
5646                 installResult->resMessage = "STATUS_UNINSTALL_FAILURE_ABORTED";
5647                 break;
5648             }
5649             [[fallthrough]];
5650         case static_cast<int32_t>(IStatusReceiver::ERR_UNINSTALL_SYSTEM_APP_ERROR):
5651         case static_cast<int32_t>(IStatusReceiver::ERR_UNINSTALL_KILLING_APP_ERROR):
5652             if (CheckIsSystemApp()) {
5653                 installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_UNINSTALL_FAILURE_CONFLICT);
5654                 installResult->resMessage = "STATUS_UNINSTALL_FAILURE_CONFLICT";
5655                 break;
5656             }
5657             [[fallthrough]];
5658         case static_cast<int32_t>(IStatusReceiver::ERR_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR):
5659         case static_cast<int32_t>(IStatusReceiver::ERR_UNINSTALL_MISSING_INSTALLED_BUNDLE):
5660         case static_cast<int32_t>(IStatusReceiver::ERR_UNINSTALL_MISSING_INSTALLED_MODULE):
5661         case static_cast<int32_t>(IStatusReceiver::ERR_USER_NOT_INSTALL_HAP):
5662         case static_cast<int32_t>(IStatusReceiver::ERR_UNINSTALL_DISALLOWED):
5663             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_UNINSTALL_FAILURE);
5664             installResult->resMessage = "STATUS_UNINSTALL_FAILURE";
5665             break;
5666         case static_cast<int32_t>(IStatusReceiver::ERR_RECOVER_GET_BUNDLEPATH_ERROR):
5667         case static_cast<int32_t>(IStatusReceiver::ERR_RECOVER_INVALID_BUNDLE_NAME):
5668         case static_cast<int32_t>(IStatusReceiver::ERR_RECOVER_NOT_ALLOWED):
5669             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_RECOVER_FAILURE_INVALID);
5670             installResult->resMessage = "STATUS_RECOVER_FAILURE_INVALID";
5671             break;
5672         case static_cast<int32_t>(IStatusReceiver::ERR_FAILED_SERVICE_DIED):
5673         case static_cast<int32_t>(IStatusReceiver::ERR_FAILED_GET_INSTALLER_PROXY):
5674             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_BMS_SERVICE_ERROR);
5675             installResult->resMessage = "STATUS_BMS_SERVICE_ERROR";
5676             break;
5677         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_DISK_MEM_INSUFFICIENT):
5678             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_FAILED_NO_SPACE_LEFT);
5679             installResult->resMessage = "STATUS_FAILED_NO_SPACE_LEFT";
5680             break;
5681         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED):
5682         case static_cast<int32_t>(IStatusReceiver::ERR_INSTALL_UPDATE_HAP_TOKEN_FAILED):
5683             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_GRANT_REQUEST_PERMISSIONS_FAILED);
5684             installResult->resMessage = "STATUS_GRANT_REQUEST_PERMISSIONS_FAILED";
5685             break;
5686         case static_cast<int32_t>(IStatusReceiver::ERR_USER_NOT_EXIST):
5687             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_USER_NOT_EXIST);
5688             installResult->resMessage = "STATUS_USER_NOT_EXIST";
5689             break;
5690         case static_cast<int32_t>(IStatusReceiver::ERR_USER_CREATE_FAILED):
5691             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_USER_CREATE_FAILED);
5692             installResult->resMessage = "STATUS_USER_CREATE_FAILED";
5693             break;
5694         case static_cast<int32_t>(IStatusReceiver::ERR_USER_REMOVE_FAILED):
5695             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_USER_REMOVE_FAILED);
5696             installResult->resMessage = "STATUS_USER_REMOVE_FAILED";
5697             break;
5698         default:
5699             installResult->resCode = static_cast<int32_t>(InstallErrorCode::STATUS_BMS_SERVICE_ERROR);
5700             installResult->resMessage = "STATUS_BMS_SERVICE_ERROR";
5701             break;
5702     }
5703 }
5704 }  // namespace AppExecFwk
5705 }  // namespace OHOS