• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022  Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "securec.h"
17 
18 #include "bundle_active_log.h"
19 #include "bundle_state_common.h"
20 
21 namespace OHOS {
22 namespace DeviceUsageStats {
23 const int ERR_MULTIPLE = 100;
24 const int64_t YEAR_TYPE = 3;
25 const int64_t MAX_TIME = 20000000000000;
AsyncWorkData(napi_env napiEnv)26 AsyncWorkData::AsyncWorkData(napi_env napiEnv)
27 {
28     env = napiEnv;
29 }
30 
~AsyncWorkData()31 AsyncWorkData::~AsyncWorkData()
32 {
33     if (callback) {
34         BUNDLE_ACTIVE_LOGI("delete callback");
35         napi_delete_reference(env, callback);
36         callback = nullptr;
37     }
38     if (asyncWork) {
39         BUNDLE_ACTIVE_LOGI("delete asyncwork");
40         napi_delete_async_work(env, asyncWork);
41         asyncWork = nullptr;
42     }
43 }
44 
HandleParamErr(const napi_env & env,int32_t errCode,const std::string & operation)45 napi_value BundleStateCommon::HandleParamErr(const napi_env &env, int32_t errCode, const std::string& operation)
46 {
47     if (errCode == ERR_OK) {
48         return nullptr;
49     }
50     BUNDLE_ACTIVE_LOGE("HandleParamErr %{public}d", errCode);
51     auto iter = paramErrCodeMsgMap.find(errCode);
52     if (iter != paramErrCodeMsgMap.end()) {
53         std::string errMessage = "BussinessError 401: Parameter error. ";
54         errMessage.append(operation);
55         errMessage.append(iter->second);
56         napi_throw_error(env, std::to_string(ERR_PARAM_ERROR).c_str(), errMessage.c_str());
57     }
58     return nullptr;
59 }
60 
GetSaErrCodeMsg(int32_t errCode,int32_t reflectCode)61 std::string BundleStateCommon::GetSaErrCodeMsg(int32_t errCode, int32_t reflectCode)
62 {
63     BUNDLE_ACTIVE_LOGE("GetSaErrCodeMsg %{public}d", errCode);
64     auto iter = saErrCodeMsgMap.find(errCode);
65     std::string errMessage;
66     if (iter != saErrCodeMsgMap.end()) {
67         errMessage.append("BussinessError ");
68         errMessage.append(std::to_string(reflectCode)).append(":").append(iter->second);
69     }
70     return errMessage;
71 }
72 
NapiGetNull(napi_env env)73 napi_value BundleStateCommon::NapiGetNull(napi_env env)
74 {
75     napi_value result = nullptr;
76     napi_get_null(env, &result);
77     return result;
78 }
79 
GetCallbackPromiseResult(const napi_env & env,const AsyncWorkData & workData,const napi_value & result)80 void BundleStateCommon::GetCallbackPromiseResult(const napi_env &env,
81     const AsyncWorkData &workData, const napi_value &result)
82 {
83     if (workData.isCallback) {
84         SetCallbackInfo(env, workData.callback, workData.errorCode, result);
85     } else {
86         SetPromiseInfo(env, workData.deferred, result, workData.errorCode);
87     }
88 }
89 
SetCallbackInfo(const napi_env & env,const napi_ref & callbackIn,const int32_t & errorCode,const napi_value & result)90 void BundleStateCommon::SetCallbackInfo(
91     const napi_env &env, const napi_ref &callbackIn, const int32_t &errorCode, const napi_value &result)
92 {
93     napi_value undefined = nullptr;
94     napi_get_undefined(env, &undefined);
95 
96     napi_value callback = nullptr;
97     napi_value resultout = nullptr;
98     napi_get_reference_value(env, callbackIn, &callback);
99     napi_value results[ARGS_TWO] = {nullptr};
100     results[PARAM_FIRST] = GetErrorValue(env, errorCode);
101     results[PARAM_SECOND] = result;
102     NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &results[PARAM_FIRST],
103         &resultout));
104 }
105 
GetBundleActiveEventForResult(napi_env env,const std::vector<BundleActiveEvent> & bundleActiveStates,napi_value result,bool isNewVersion)106 void BundleStateCommon::GetBundleActiveEventForResult(
107     napi_env env, const std::vector<BundleActiveEvent> &bundleActiveStates, napi_value result, bool isNewVersion)
108 {
109     int32_t index = 0;
110     for (const auto &item : bundleActiveStates) {
111         napi_value bundleActiveState = nullptr;
112         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &bundleActiveState));
113 
114         napi_value bundleName = nullptr;
115         NAPI_CALL_RETURN_VOID(
116             env, napi_create_string_utf8(env, item.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName));
117         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "bundleName", bundleName));
118 
119         napi_value eventId = nullptr;
120         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId));
121 
122         napi_value eventOccurredTime = nullptr;
123         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.timeStamp_, &eventOccurredTime));
124 
125         if (isNewVersion) {
126             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "eventId", eventId));
127             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "eventOccurredTime",
128                 eventOccurredTime));
129         } else {
130             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "stateType", eventId));
131             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "stateOccurredTime",
132                 eventOccurredTime));
133         }
134 
135         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, bundleActiveState));
136         index++;
137     }
138 }
139 
GetBundleStateInfoByIntervalForResult(napi_env env,const std::vector<BundleActivePackageStats> & packageStats,napi_value result)140 void BundleStateCommon::GetBundleStateInfoByIntervalForResult(
141     napi_env env, const std::vector<BundleActivePackageStats> &packageStats, napi_value result)
142 {
143     int32_t index = 0;
144     for (const auto &item : packageStats) {
145         napi_value packageObject = nullptr;
146         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &packageObject));
147 
148         napi_value bundleName = nullptr;
149         NAPI_CALL_RETURN_VOID(
150             env, napi_create_string_utf8(env, item.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName));
151         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "bundleName", bundleName));
152 
153         napi_value abilityPrevAccessTime = nullptr;
154         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.lastTimeUsed_, &abilityPrevAccessTime));
155         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityPrevAccessTime",
156             abilityPrevAccessTime));
157 
158         napi_value abilityInFgTotalTime = nullptr;
159         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.totalInFrontTime_, &abilityInFgTotalTime));
160         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityInFgTotalTime",
161             abilityInFgTotalTime));
162 
163         napi_value id = nullptr;
164         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.userId_, &id));
165         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "id", id));
166 
167         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, packageObject));
168         index++;
169     }
170 }
171 
GetBundleActiveEventStatsForResult(napi_env env,const std::vector<BundleActiveEventStats> & eventStats,napi_value result)172 void BundleStateCommon::GetBundleActiveEventStatsForResult(napi_env env,
173     const std::vector<BundleActiveEventStats> &eventStats, napi_value result)
174 {
175     int32_t index = 0;
176     for (const auto &item : eventStats) {
177         napi_value eventStatsObject = nullptr;
178         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &eventStatsObject));
179 
180         napi_value name = nullptr;
181         NAPI_CALL_RETURN_VOID(
182             env, napi_create_string_utf8(env, item.name_.c_str(), NAPI_AUTO_LENGTH, &name));
183         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "name", name));
184 
185         napi_value eventId = nullptr;
186         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId));
187         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "eventId", eventId));
188 
189         napi_value count = nullptr;
190         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.count_, &count));
191         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "count", count));
192 
193         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, eventStatsObject));
194         index++;
195     }
196 }
197 
GetBundleActiveNotificationNumberForResult(napi_env env,const std::vector<BundleActiveEventStats> & eventStats,napi_value result)198 void BundleStateCommon::GetBundleActiveNotificationNumberForResult(napi_env env,
199     const std::vector<BundleActiveEventStats> &eventStats, napi_value result)
200 {
201     int32_t index = 0;
202     for (const auto &item : eventStats) {
203         napi_value eventStatsObject = nullptr;
204         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &eventStatsObject));
205 
206         napi_value name = nullptr;
207         NAPI_CALL_RETURN_VOID(
208             env, napi_create_string_utf8(env, item.name_.c_str(), NAPI_AUTO_LENGTH, &name));
209         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "name", name));
210 
211         napi_value eventId = nullptr;
212         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId));
213         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "eventId", eventId));
214 
215         napi_value count = nullptr;
216         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.count_, &count));
217         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "count", count));
218 
219         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, eventStatsObject));
220         index++;
221     }
222 }
223 
GetBundleStateInfoForResult(napi_env env,const std::shared_ptr<std::map<std::string,BundleActivePackageStats>> & packageStats,napi_value result)224 void BundleStateCommon::GetBundleStateInfoForResult(napi_env env,
225     const std::shared_ptr<std::map<std::string, BundleActivePackageStats>> &packageStats, napi_value result)
226 {
227     if (packageStats == nullptr) {
228         BUNDLE_ACTIVE_LOGE("PackageStats is invalid");
229         return;
230     }
231     for (const auto &item : *packageStats) {
232         napi_value packageObject = nullptr;
233         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &packageObject));
234         napi_value bundleName = nullptr;
235         NAPI_CALL_RETURN_VOID(
236             env, napi_create_string_utf8(env, item.second.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName));
237         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "bundleName", bundleName));
238 
239         napi_value abilityPrevAccessTime = nullptr;
240         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.second.lastTimeUsed_, &abilityPrevAccessTime));
241         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityPrevAccessTime",
242             abilityPrevAccessTime));
243 
244         napi_value abilityInFgTotalTime = nullptr;
245         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.second.totalInFrontTime_, &abilityInFgTotalTime));
246         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityInFgTotalTime",
247             abilityInFgTotalTime));
248 
249         napi_value id = nullptr;
250         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.second.userId_, &id));
251         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "id", id));
252 
253         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, item.first.c_str(), packageObject));
254     }
255 }
256 
GetAppStatsInfosForResult(napi_env env,const std::shared_ptr<std::map<std::string,std::vector<BundleActivePackageStats>>> & packageStats,napi_value result)257 void BundleStateCommon::GetAppStatsInfosForResult(napi_env env,
258     const std::shared_ptr<std::map<std::string, std::vector<BundleActivePackageStats>>> &packageStats,
259     napi_value result)
260 {
261     if (packageStats == nullptr) {
262         BUNDLE_ACTIVE_LOGE("PackageStats is invalid");
263         return;
264     }
265     for (const auto &item : *packageStats) {
266         napi_value packageStatsArray = nullptr;
267         napi_create_array(env, &packageStatsArray);
268         int32_t index = 0;
269         for (auto iter : item.second) {
270             napi_value packageObject = nullptr;
271             NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &packageObject));
272             napi_value bundleName = nullptr;
273             NAPI_CALL_RETURN_VOID(
274                 env, napi_create_string_utf8(env, iter.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName));
275             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "bundleName", bundleName));
276             napi_value abilityPrevAccessTime = nullptr;
277             NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, iter.lastTimeUsed_, &abilityPrevAccessTime));
278             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityPrevAccessTime",
279                 abilityPrevAccessTime));
280             napi_value abilityInFgTotalTime = nullptr;
281             NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, iter.totalInFrontTime_, &abilityInFgTotalTime));
282             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityInFgTotalTime",
283                 abilityInFgTotalTime));
284             napi_value id = nullptr;
285             NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, iter.userId_, &id));
286             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "id", id));
287             napi_value appIndex = nullptr;
288             NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, iter.appIndex_, &appIndex));
289             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "appIndex", appIndex));
290             NAPI_CALL_RETURN_VOID(env, napi_set_element(env, packageStatsArray, index++, packageObject));
291         }
292         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, item.first.c_str(), packageStatsArray));
293     }
294 }
295 
GetModuleRecordBasicForResult(napi_env env,const BundleActiveModuleRecord & moduleRecords,napi_value moduleObject)296 void BundleStateCommon::GetModuleRecordBasicForResult(napi_env env,
297     const BundleActiveModuleRecord &moduleRecords, napi_value moduleObject)
298 {
299         napi_value bundleName = nullptr;
300         NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moduleRecords.bundleName_.c_str(),
301             NAPI_AUTO_LENGTH, &bundleName));
302         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "bundleName", bundleName));
303         napi_value appLabelId = nullptr;
304         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.appLabelId_, &appLabelId));
305         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "appLabelId", appLabelId));
306         napi_value moduleName = nullptr;
307         NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moduleRecords.moduleName_.c_str(), NAPI_AUTO_LENGTH,
308             &moduleName));
309         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "moduleName", moduleName));
310         napi_value labelId = nullptr;
311         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.labelId_, &labelId));
312         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "labelId", labelId));
313         napi_value descriptionId = nullptr;
314         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.descriptionId_, &descriptionId));
315         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "descriptionId", descriptionId));
316         napi_value abilityName = nullptr;
317         NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moduleRecords.abilityName_.c_str(), NAPI_AUTO_LENGTH,
318             &abilityName));
319         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityName", abilityName));
320         napi_value abilityLableId = nullptr;
321         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.abilityLableId_, &abilityLableId));
322         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityLableId", abilityLableId));
323         napi_value abilityDescriptionId = nullptr;
324         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.abilityDescriptionId_,
325             &abilityDescriptionId));
326         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityDescriptionId",
327             abilityDescriptionId));
328         napi_value abilityIconId = nullptr;
329         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.abilityIconId_, &abilityIconId));
330         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityIconId", abilityIconId));
331         napi_value launchedCount = nullptr;
332         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, moduleRecords.launchedCount_, &launchedCount));
333         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "launchedCount", launchedCount));
334         napi_value lastModuleUsedTime = nullptr;
335         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, moduleRecords.lastModuleUsedTime_, &lastModuleUsedTime));
336         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject,
337             "lastModuleUsedTime", lastModuleUsedTime));
338 }
339 
GetModuleRecordForResult(napi_env env,const std::vector<BundleActiveModuleRecord> & moduleRecords,napi_value result)340 void BundleStateCommon::GetModuleRecordForResult(napi_env env,
341     const std::vector<BundleActiveModuleRecord> &moduleRecords, napi_value result)
342 {
343     int32_t index = 0;
344     for (const auto &item : moduleRecords) {
345         napi_value moduleObject = nullptr;
346         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &moduleObject));
347         GetModuleRecordBasicForResult(env, item, moduleObject);
348 
349         napi_value formRecords = nullptr;
350         NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &formRecords));
351         int32_t formIdx = 0;
352         for (const auto& oneFormRecord : item.formRecords_) {
353             napi_value formObject = nullptr;
354             NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &formObject));
355             napi_value formName = nullptr;
356             NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, oneFormRecord.formName_.c_str(), NAPI_AUTO_LENGTH,
357                 &formName));
358             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, formObject, "formName", formName));
359 
360             napi_value formDimension = nullptr;
361             NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, oneFormRecord.formDimension_, &formDimension));
362             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, formObject, "formDimension", formDimension));
363 
364             napi_value formId = nullptr;
365             NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, oneFormRecord.formId_, &formId));
366             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, formObject, "formId", formId));
367 
368             napi_value formLastUsedTime = nullptr;
369             NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, oneFormRecord.formLastUsedTime_, &formLastUsedTime));
370             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, formObject, "formLastUsedTime", formLastUsedTime));
371 
372             napi_value count = nullptr;
373             NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, oneFormRecord.count_, &count));
374             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, formObject, "count", count));
375             NAPI_CALL_RETURN_VOID(env, napi_set_element(env, formRecords, formIdx, formObject));
376             formIdx++;
377         }
378         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "formRecords", formRecords));
379         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, moduleObject));
380         index++;
381     }
382 }
383 
SetPromiseInfo(const napi_env & env,const napi_deferred & deferred,const napi_value & result,const int32_t & errorCode)384 void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred &deferred,
385     const napi_value &result, const int32_t &errorCode)
386 {
387     switch (errorCode) {
388         case ERR_OK:
389             napi_resolve_deferred(env, deferred, result);
390             break;
391         default:
392             napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode));
393             break;
394     }
395 }
396 
GetReflectErrCode(int32_t errCode)397 int32_t BundleStateCommon::GetReflectErrCode(int32_t errCode)
398 {
399     if (errCode < ERR_GET_SYSTEM_ABILITY_MANAGER_FAILED) {
400         return errCode;
401     }
402     return errCode / ERR_MULTIPLE;
403 }
404 
GetErrorValue(napi_env env,int32_t errCode)405 napi_value BundleStateCommon::GetErrorValue(napi_env env, int32_t errCode)
406 {
407     if (errCode == ERR_OK) {
408         return NapiGetNull(env);
409     }
410     napi_value result = nullptr;
411     napi_value eCode = nullptr;
412     napi_value eMsg = nullptr;
413     int32_t reflectCode = GetReflectErrCode(errCode);
414     std::string errMsg = GetSaErrCodeMsg(errCode, reflectCode);
415     NAPI_CALL(env, napi_create_int32(env, reflectCode, &eCode));
416     NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(), errMsg.length(), &eMsg));
417     NAPI_CALL(env, napi_create_object(env, &result));
418     NAPI_CALL(env, napi_set_named_property(env, result, "code", eCode));
419     NAPI_CALL(env, napi_set_named_property(env, result, "message", eMsg));
420     return result;
421 }
422 
ConvertMapFromJs(napi_env env,napi_value value,std::map<std::string,std::vector<int64_t>> & result)423 napi_value BundleStateCommon::ConvertMapFromJs(napi_env env, napi_value value,
424     std::map<std::string, std::vector<int64_t>>& result)
425 {
426     napi_valuetype valuetype = napi_undefined;
427     NAPI_CALL(env, napi_typeof(env, value, &valuetype));
428     if (valuetype != napi_object) {
429         BUNDLE_ACTIVE_LOGE("Wrong argument type, number expected.");
430         return nullptr;
431     }
432 
433     std::vector<std::string> propNames;
434     napi_value array = nullptr;
435     napi_get_property_names(env, value, &array);
436     ParseArrayStringValue(env, array, propNames);
437     for (const auto &propName : propNames) {
438         napi_value prop = nullptr;
439         napi_get_named_property(env, value, propName.c_str(), &prop);
440         if (prop == nullptr) {
441             BUNDLE_ACTIVE_LOGW("prop is null: %{public}s", propName.c_str());
442             continue;
443         }
444         std::vector<int64_t> intList;
445         ConvertInt64ArrayFromJs(env, prop, intList);
446         result.emplace(propName, std::move(intList));
447     }
448     return BundleStateCommon::NapiGetNull(env);
449 }
450 
ParseArrayStringValue(napi_env env,napi_value array,std::vector<std::string> & vectorResult)451 napi_value BundleStateCommon::ParseArrayStringValue(napi_env env, napi_value array,
452     std::vector<std::string>& vectorResult)
453 {
454     uint32_t arrayLen = 0;
455     napi_get_array_length(env, array, &arrayLen);
456     if (arrayLen == 0) {
457         return BundleStateCommon::NapiGetNull(env);
458     }
459     vectorResult.reserve(arrayLen);
460     for (uint32_t i = 0; i < arrayLen; i++) {
461         std::string strItem;
462         napi_value jsValue = nullptr;
463         napi_get_element(env, array, i, &jsValue);
464         size_t len = 0;
465         if (napi_get_value_string_utf8(env, jsValue, nullptr, 0, &len) != napi_ok) {
466         }
467         auto buffer = std::make_unique<char[]>(len + 1);
468         size_t strLength = 0;
469         if (napi_get_value_string_utf8(env, jsValue, buffer.get(), len + 1, &strLength) == napi_ok) {
470             strItem = buffer.get();
471         }
472         vectorResult.emplace_back(std::move(strItem));
473     }
474     return BundleStateCommon::NapiGetNull(env);
475 }
476 
ConvertInt64ArrayFromJs(napi_env env,napi_value jsObject,std::vector<int64_t> & intList)477 napi_value BundleStateCommon::ConvertInt64ArrayFromJs(napi_env env, napi_value jsObject,
478     std::vector<int64_t>& intList)
479 {
480     uint32_t length = 0;
481     napi_get_array_length(env, jsObject, &length);
482     for (uint32_t i = 0; i < length; i++) {
483         int64_t persistentId;
484         napi_value elememtVal = nullptr;
485         napi_get_element(env, jsObject, i, &elememtVal);
486         napi_get_value_int64(env, elememtVal, &persistentId);
487         intList.push_back(std::move(persistentId));
488     }
489     return BundleStateCommon::NapiGetNull(env);
490 }
491 
492 
JSParaError(const napi_env & env,const napi_ref & callback,const int32_t & errorCode)493 napi_value BundleStateCommon::JSParaError(const napi_env &env, const napi_ref &callback, const int32_t &errorCode)
494 {
495     if (callback) {
496         napi_value result = nullptr;
497         napi_create_array(env, &result);
498         SetCallbackInfo(env, callback, errorCode, result);
499         return result;
500     } else {
501         napi_value promise = nullptr;
502         napi_deferred deferred = nullptr;
503         napi_create_promise(env, &deferred, &promise);
504         napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode));
505         return promise;
506     }
507 }
508 
GetTypeStringValue(napi_env env,napi_value param,const std::string & result)509 std::string BundleStateCommon::GetTypeStringValue(napi_env env, napi_value param, const std::string &result)
510 {
511     size_t size = 0;
512     if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != BUNDLE_STATE_OK) {
513         return result;
514     }
515 
516     std::string value("");
517     if (size == 0) {
518         return result;
519     }
520 
521     char *buf = new (std::nothrow) char[size + 1];
522     if (buf == nullptr) {
523         return value;
524     }
525 
526     if (memset_s(buf, size + 1, 0, size + 1) != EOK) {
527         delete[] buf;
528         buf = nullptr;
529         return value;
530     }
531 
532     bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == BUNDLE_STATE_OK;
533     if (rev) {
534         value = buf;
535     } else {
536         value = result;
537     }
538 
539     delete[] buf;
540     buf = nullptr;
541     return value;
542 }
543 
GetInt64NumberValue(const napi_env & env,const napi_value & value,int64_t & result)544 napi_value BundleStateCommon::GetInt64NumberValue(const napi_env &env, const napi_value &value, int64_t &result)
545 {
546     napi_valuetype valuetype = napi_undefined;
547 
548     NAPI_CALL(env, napi_typeof(env, value, &valuetype));
549     if (valuetype != napi_number) {
550         BUNDLE_ACTIVE_LOGE("Wrong argument type, number expected.");
551         return nullptr;
552     }
553     napi_get_value_int64(env, value, &result);
554     return BundleStateCommon::NapiGetNull(env);
555 }
556 
GetInt32NumberValue(const napi_env & env,const napi_value & value,int32_t & result)557 napi_value BundleStateCommon::GetInt32NumberValue(const napi_env &env, const napi_value &value, int32_t &result)
558 {
559     napi_valuetype valuetype = napi_undefined;
560     NAPI_CALL(env, napi_typeof(env, value, &valuetype));
561     if (valuetype != napi_number) {
562         BUNDLE_ACTIVE_LOGE("Wrong argument type. Number expected.");
563         return nullptr;
564     }
565     napi_get_value_int32(env, value, &result);
566     return BundleStateCommon::NapiGetNull(env);
567 }
568 
SettingAsyncWorkData(const napi_env & env,const napi_ref & callback,AsyncWorkData & workData,napi_value & promise)569 void BundleStateCommon::SettingAsyncWorkData(
570     const napi_env &env, const napi_ref &callback, AsyncWorkData &workData, napi_value &promise)
571 {
572     if (callback) {
573         workData.callback = callback;
574         workData.isCallback = true;
575     } else {
576         napi_deferred deferred = nullptr;
577         NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise));
578         workData.deferred = deferred;
579         workData.isCallback = false;
580     }
581 }
582 
QueryBundleStatsInfos(int64_t & beginTime,int64_t & endTime,int32_t & errCode)583 std::shared_ptr<std::map<std::string, BundleActivePackageStats>> BundleStateCommon::QueryBundleStatsInfos(
584     int64_t &beginTime, int64_t &endTime, int32_t &errCode)
585 {
586     std::vector<BundleActivePackageStats> packageStats;
587     errCode = BundleActiveClient::GetInstance().QueryBundleStatsInfoByInterval(packageStats, INTERVAL_TYPE_DEFAULT,
588         beginTime, endTime);
589     std::shared_ptr<std::map<std::string, BundleActivePackageStats>> mergedPackageStats =
590         std::make_shared<std::map<std::string, BundleActivePackageStats>>();
591     if (packageStats.empty()) {
592         return nullptr;
593     }
594     for (auto packageStat : packageStats) {
595         std::map<std::string, BundleActivePackageStats>::iterator iter =
596             mergedPackageStats->find(packageStat.bundleName_);
597         if (iter != mergedPackageStats->end()) {
598             MergePackageStats(iter->second, packageStat);
599         } else {
600             mergedPackageStats->
601                 insert(std::pair<std::string, BundleActivePackageStats>(packageStat.bundleName_, packageStat));
602         }
603     }
604     return mergedPackageStats;
605 }
606 
QueryAppStatsInfos(int64_t & beginTime,int64_t & endTime,int32_t & errCode)607 std::shared_ptr<std::map<std::string, std::vector<BundleActivePackageStats>>> BundleStateCommon::QueryAppStatsInfos(
608     int64_t &beginTime, int64_t &endTime, int32_t &errCode)
609 {
610     std::vector<BundleActivePackageStats> packageStats;
611     errCode = BundleActiveClient::GetInstance().QueryBundleStatsInfoByInterval(packageStats, 0,
612         beginTime, endTime);
613     std::shared_ptr<std::map<std::string, std::vector<BundleActivePackageStats>>> mergedPackageStats =
614         std::make_shared<std::map<std::string, std::vector<BundleActivePackageStats>>>();
615     if (packageStats.empty()) {
616         return nullptr;
617     }
618     for (auto packageStat : packageStats) {
619         std::map<std::string, std::vector<BundleActivePackageStats>>::iterator iter =
620             mergedPackageStats->find(packageStat.bundleName_);
621         if (iter != mergedPackageStats->end()) {
622             bool sign = false;
623             for (auto packageMerge : iter->second) {
624                 if (packageMerge.appIndex_ == packageStat.appIndex_) {
625                     MergePackageStats(packageMerge, packageStat);
626                     sign = true;
627                 }
628             }
629             if (sign == false) {
630                 iter->second.push_back(packageStat);
631             }
632         } else {
633             std::vector<BundleActivePackageStats> temp;
634             temp.push_back(packageStat);
635             mergedPackageStats->insert(std::pair<std::string, std::vector<BundleActivePackageStats>>(
636                 packageStat.bundleName_, temp));
637         }
638     }
639     return mergedPackageStats;
640 }
641 
QueryLastUseTime(const std::map<std::string,std::vector<int64_t>> & queryInfos,int32_t & errCode)642 std::shared_ptr<std::map<std::string, std::vector<BundleActivePackageStats>>> BundleStateCommon::QueryLastUseTime(
643     const std::map<std::string, std::vector<int64_t>>& queryInfos, int32_t &errCode)
644 {
645     std::vector<BundleActivePackageStats> packageStats;
646     errCode = BundleActiveClient::GetInstance().QueryBundleStatsInfoByInterval(packageStats, YEAR_TYPE, 0, MAX_TIME);
647     std::shared_ptr<std::map<std::string, std::vector<BundleActivePackageStats>>> mergedPackageStats =
648         std::make_shared<std::map<std::string, std::vector<BundleActivePackageStats>>>();
649     if (packageStats.empty()) {
650         return nullptr;
651     }
652 
653     std::vector<std::string> tempQueryInfos;
654     for (auto queryInfo : queryInfos) {
655         for (std::vector<int64_t>::iterator queryInfoIter = queryInfo.second.begin();
656             queryInfoIter != queryInfo.second.end(); queryInfoIter++) {
657             std::string tempQueryInfo = queryInfo.first + std::to_string(*queryInfoIter);
658             tempQueryInfos.push_back(tempQueryInfo);
659         }
660     }
661     std::vector<BundleActivePackageStats> tempPackageStats;
662     for (auto tempQueryInfoIter : tempQueryInfos) {
663         for (auto packageStat : packageStats) {
664             if (tempQueryInfoIter == packageStat.bundleName_ + std::to_string(packageStat.appIndex_)) {
665                 tempPackageStats.push_back(packageStat);
666             }
667         }
668     }
669     for (auto tempPackageStat : tempPackageStats) {
670         std::map<std::string, std::vector<BundleActivePackageStats>>::iterator iter =
671             mergedPackageStats->find(tempPackageStat.bundleName_);
672         if (iter != mergedPackageStats->end()) {
673             bool sign = false;
674             for (auto packageMerge : iter->second) {
675                 if (packageMerge.appIndex_ == tempPackageStat.appIndex_) {
676                     MergePackageStats(packageMerge, tempPackageStat);
677                     sign = true;
678                 }
679             }
680             if (sign == false) {
681                 iter->second.push_back(tempPackageStat);
682             }
683         } else {
684             std::vector<BundleActivePackageStats> temp;
685             temp.push_back(tempPackageStat);
686             mergedPackageStats->insert(std::pair<std::string, std::vector<BundleActivePackageStats>>(
687                 tempPackageStat.bundleName_, temp));
688         }
689     }
690     return mergedPackageStats;
691 }
692 
MergePackageStats(BundleActivePackageStats & left,const BundleActivePackageStats & right)693 void BundleStateCommon::MergePackageStats(BundleActivePackageStats &left, const BundleActivePackageStats &right)
694 {
695     if (left.bundleName_ != right.bundleName_) {
696         BUNDLE_ACTIVE_LOGE("Merge package stats failed, existing packageName : %{public}s,"
697             " new packageName : %{public}s,", left.bundleName_.c_str(), right.bundleName_.c_str());
698         return;
699     }
700     left.lastTimeUsed_ = std::max(left.lastTimeUsed_, right.lastTimeUsed_);
701     left.lastContiniousTaskUsed_ = std::max(left.lastContiniousTaskUsed_, right.lastContiniousTaskUsed_);
702     left.totalInFrontTime_ += right.totalInFrontTime_;
703     left.totalContiniousTaskUsedTime_ += right.totalContiniousTaskUsedTime_;
704     left.bundleStartedCount_ += right.bundleStartedCount_;
705 }
706 
HandleEventStatsInfo(const napi_env & env,AsyncCallbackInfoEventStats * asyncCallbackInfo,EventStatesParamsInfo & params)707 std::unique_ptr<AsyncCallbackInfoEventStats> BundleStateCommon::HandleEventStatsInfo(const napi_env &env,
708     AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo &params)
709 {
710     if (!asyncCallbackInfo) {
711         params.errorCode = ERR_ASYNC_CALLBACK_NULLPTR;
712         BundleStateCommon::HandleParamErr(env, ERR_ASYNC_CALLBACK_NULLPTR, "");
713         return nullptr;
714     }
715     if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) {
716         params.errorCode = ERR_ASYNC_CALLBACK_INIT_FAILED;
717         BundleStateCommon::HandleParamErr(env, ERR_ASYNC_CALLBACK_INIT_FAILED, "");
718         delete asyncCallbackInfo;
719         asyncCallbackInfo = nullptr;
720         return nullptr;
721     }
722     std::unique_ptr<AsyncCallbackInfoEventStats> callbackPtr {asyncCallbackInfo};
723     callbackPtr->beginTime = params.beginTime;
724     callbackPtr->endTime = params.endTime;
725     BUNDLE_ACTIVE_LOGI("CallbackPtr->beginTime: %{public}lld, callbackPtr->endTime: %{public}lld",
726         (long long)callbackPtr->beginTime, (long long)callbackPtr->endTime);
727     return callbackPtr;
728 }
729 }  // namespace DeviceUsageStats
730 }  // namespace OHOS
731 
732