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;
AsyncWorkData(napi_env napiEnv)24 AsyncWorkData::AsyncWorkData(napi_env napiEnv)
25 {
26     env = napiEnv;
27 }
28 
~AsyncWorkData()29 AsyncWorkData::~AsyncWorkData()
30 {
31     if (callback) {
32         BUNDLE_ACTIVE_LOGI("delete callback");
33         napi_delete_reference(env, callback);
34         callback = nullptr;
35     }
36     if (asyncWork) {
37         BUNDLE_ACTIVE_LOGI("delete asyncwork");
38         napi_delete_async_work(env, asyncWork);
39         asyncWork = nullptr;
40     }
41 }
42 
HandleParamErr(const napi_env & env,int32_t errCode,const std::string & operation)43 napi_value BundleStateCommon::HandleParamErr(const napi_env &env, int32_t errCode, const std::string& operation)
44 {
45     if (errCode == ERR_OK) {
46         return nullptr;
47     }
48     BUNDLE_ACTIVE_LOGE("HandleParamErr %{public}d", errCode);
49     auto iter = paramErrCodeMsgMap.find(errCode);
50     if (iter != paramErrCodeMsgMap.end()) {
51         std::string errMessage = "BussinessError 401: Parameter error. ";
52         errMessage.append(operation);
53         errMessage.append(iter->second);
54         napi_throw_error(env, std::to_string(ERR_PARAM_ERROR).c_str(), errMessage.c_str());
55     }
56     return nullptr;
57 }
58 
GetSaErrCodeMsg(int32_t errCode,int32_t reflectCode)59 std::string BundleStateCommon::GetSaErrCodeMsg(int32_t errCode, int32_t reflectCode)
60 {
61     BUNDLE_ACTIVE_LOGE("GetSaErrCodeMsg %{public}d", errCode);
62     auto iter = saErrCodeMsgMap.find(errCode);
63     std::string errMessage;
64     if (iter != saErrCodeMsgMap.end()) {
65         errMessage.append("BussinessError ");
66         errMessage.append(std::to_string(reflectCode)).append(":").append(iter->second);
67     }
68     return errMessage;
69 }
70 
NapiGetNull(napi_env env)71 napi_value BundleStateCommon::NapiGetNull(napi_env env)
72 {
73     napi_value result = nullptr;
74     napi_get_null(env, &result);
75     return result;
76 }
77 
GetCallbackPromiseResult(const napi_env & env,const AsyncWorkData & workData,const napi_value & result)78 void BundleStateCommon::GetCallbackPromiseResult(const napi_env &env,
79     const AsyncWorkData &workData, const napi_value &result)
80 {
81     if (workData.isCallback) {
82         SetCallbackInfo(env, workData.callback, workData.errorCode, result);
83     } else {
84         SetPromiseInfo(env, workData.deferred, result, workData.errorCode);
85     }
86 }
87 
SetCallbackInfo(const napi_env & env,const napi_ref & callbackIn,const int32_t & errorCode,const napi_value & result)88 void BundleStateCommon::SetCallbackInfo(
89     const napi_env &env, const napi_ref &callbackIn, const int32_t &errorCode, const napi_value &result)
90 {
91     napi_value undefined = nullptr;
92     napi_get_undefined(env, &undefined);
93 
94     napi_value callback = nullptr;
95     napi_value resultout = nullptr;
96     napi_get_reference_value(env, callbackIn, &callback);
97     napi_value results[ARGS_TWO] = {nullptr};
98     results[PARAM_FIRST] = GetErrorValue(env, errorCode);
99     results[PARAM_SECOND] = result;
100     NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &results[PARAM_FIRST],
101         &resultout));
102 }
103 
GetBundleActiveEventForResult(napi_env env,const std::vector<BundleActiveEvent> & bundleActiveStates,napi_value result,bool isNewVersion)104 void BundleStateCommon::GetBundleActiveEventForResult(
105     napi_env env, const std::vector<BundleActiveEvent> &bundleActiveStates, napi_value result, bool isNewVersion)
106 {
107     int32_t index = 0;
108     for (const auto &item : bundleActiveStates) {
109         napi_value bundleActiveState = nullptr;
110         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &bundleActiveState));
111 
112         napi_value bundleName = nullptr;
113         NAPI_CALL_RETURN_VOID(
114             env, napi_create_string_utf8(env, item.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName));
115         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "bundleName", bundleName));
116 
117         napi_value eventId = nullptr;
118         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId));
119 
120         napi_value eventOccurredTime = nullptr;
121         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.timeStamp_, &eventOccurredTime));
122 
123         if (isNewVersion) {
124             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "eventId", eventId));
125             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "eventOccurredTime",
126                 eventOccurredTime));
127         } else {
128             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "stateType", eventId));
129             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "stateOccurredTime",
130                 eventOccurredTime));
131         }
132 
133         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, bundleActiveState));
134         index++;
135     }
136 }
137 
GetBundleStateInfoByIntervalForResult(napi_env env,const std::vector<BundleActivePackageStats> & packageStats,napi_value result)138 void BundleStateCommon::GetBundleStateInfoByIntervalForResult(
139     napi_env env, const std::vector<BundleActivePackageStats> &packageStats, napi_value result)
140 {
141     int32_t index = 0;
142     for (const auto &item : packageStats) {
143         napi_value packageObject = nullptr;
144         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &packageObject));
145 
146         napi_value bundleName = nullptr;
147         NAPI_CALL_RETURN_VOID(
148             env, napi_create_string_utf8(env, item.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName));
149         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "bundleName", bundleName));
150 
151         napi_value abilityPrevAccessTime = nullptr;
152         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.lastTimeUsed_, &abilityPrevAccessTime));
153         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityPrevAccessTime",
154             abilityPrevAccessTime));
155 
156         napi_value abilityInFgTotalTime = nullptr;
157         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.totalInFrontTime_, &abilityInFgTotalTime));
158         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityInFgTotalTime",
159             abilityInFgTotalTime));
160 
161         napi_value id = nullptr;
162         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.userId_, &id));
163         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "id", id));
164 
165         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, packageObject));
166         index++;
167     }
168 }
169 
GetBundleActiveEventStatsForResult(napi_env env,const std::vector<BundleActiveEventStats> & eventStats,napi_value result)170 void BundleStateCommon::GetBundleActiveEventStatsForResult(napi_env env,
171     const std::vector<BundleActiveEventStats> &eventStats, napi_value result)
172 {
173     int32_t index = 0;
174     for (const auto &item : eventStats) {
175         napi_value eventStatsObject = nullptr;
176         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &eventStatsObject));
177 
178         napi_value name = nullptr;
179         NAPI_CALL_RETURN_VOID(
180             env, napi_create_string_utf8(env, item.name_.c_str(), NAPI_AUTO_LENGTH, &name));
181         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "name", name));
182 
183         napi_value eventId = nullptr;
184         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId));
185         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "eventId", eventId));
186 
187         napi_value count = nullptr;
188         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.count_, &count));
189         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "count", count));
190 
191         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, eventStatsObject));
192         index++;
193     }
194 }
195 
GetBundleActiveNotificationNumberForResult(napi_env env,const std::vector<BundleActiveEventStats> & eventStats,napi_value result)196 void BundleStateCommon::GetBundleActiveNotificationNumberForResult(napi_env env,
197     const std::vector<BundleActiveEventStats> &eventStats, napi_value result)
198 {
199     int32_t index = 0;
200     for (const auto &item : eventStats) {
201         napi_value eventStatsObject = nullptr;
202         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &eventStatsObject));
203 
204         napi_value name = nullptr;
205         NAPI_CALL_RETURN_VOID(
206             env, napi_create_string_utf8(env, item.name_.c_str(), NAPI_AUTO_LENGTH, &name));
207         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "name", name));
208 
209         napi_value eventId = nullptr;
210         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId));
211         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "eventId", eventId));
212 
213         napi_value count = nullptr;
214         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.count_, &count));
215         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "count", count));
216 
217         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, eventStatsObject));
218         index++;
219     }
220 }
221 
GetBundleStateInfoForResult(napi_env env,const std::shared_ptr<std::map<std::string,BundleActivePackageStats>> & packageStats,napi_value result)222 void BundleStateCommon::GetBundleStateInfoForResult(napi_env env,
223     const std::shared_ptr<std::map<std::string, BundleActivePackageStats>> &packageStats, napi_value result)
224 {
225     if (packageStats == nullptr) {
226         BUNDLE_ACTIVE_LOGE("PackageStats is invalid");
227         return;
228     }
229     for (const auto &item : *packageStats) {
230         napi_value packageObject = nullptr;
231         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &packageObject));
232         napi_value bundleName = nullptr;
233         NAPI_CALL_RETURN_VOID(
234             env, napi_create_string_utf8(env, item.second.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName));
235         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "bundleName", bundleName));
236 
237         napi_value abilityPrevAccessTime = nullptr;
238         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.second.lastTimeUsed_, &abilityPrevAccessTime));
239         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityPrevAccessTime",
240             abilityPrevAccessTime));
241 
242         napi_value abilityInFgTotalTime = nullptr;
243         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.second.totalInFrontTime_, &abilityInFgTotalTime));
244         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityInFgTotalTime",
245             abilityInFgTotalTime));
246 
247         napi_value id = nullptr;
248         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.second.userId_, &id));
249         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "id", id));
250 
251         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, item.first.c_str(), packageObject));
252     }
253 }
254 
GetModuleRecordBasicForResult(napi_env env,const BundleActiveModuleRecord & moduleRecords,napi_value moduleObject)255 void BundleStateCommon::GetModuleRecordBasicForResult(napi_env env,
256     const BundleActiveModuleRecord &moduleRecords, napi_value moduleObject)
257 {
258         napi_value bundleName = nullptr;
259         NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moduleRecords.bundleName_.c_str(),
260             NAPI_AUTO_LENGTH, &bundleName));
261         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "bundleName", bundleName));
262         napi_value appLabelId = nullptr;
263         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.appLabelId_, &appLabelId));
264         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "appLabelId", appLabelId));
265         napi_value moduleName = nullptr;
266         NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moduleRecords.moduleName_.c_str(), NAPI_AUTO_LENGTH,
267             &moduleName));
268         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "moduleName", moduleName));
269         napi_value labelId = nullptr;
270         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.labelId_, &labelId));
271         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "labelId", labelId));
272         napi_value descriptionId = nullptr;
273         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.descriptionId_, &descriptionId));
274         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "descriptionId", descriptionId));
275         napi_value abilityName = nullptr;
276         NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moduleRecords.abilityName_.c_str(), NAPI_AUTO_LENGTH,
277             &abilityName));
278         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityName", abilityName));
279         napi_value abilityLableId = nullptr;
280         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.abilityLableId_, &abilityLableId));
281         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityLableId", abilityLableId));
282         napi_value abilityDescriptionId = nullptr;
283         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.abilityDescriptionId_,
284             &abilityDescriptionId));
285         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityDescriptionId",
286             abilityDescriptionId));
287         napi_value abilityIconId = nullptr;
288         NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.abilityIconId_, &abilityIconId));
289         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityIconId", abilityIconId));
290         napi_value launchedCount = nullptr;
291         NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, moduleRecords.launchedCount_, &launchedCount));
292         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "launchedCount", launchedCount));
293         napi_value lastModuleUsedTime = nullptr;
294         NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, moduleRecords.lastModuleUsedTime_, &lastModuleUsedTime));
295         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject,
296             "lastModuleUsedTime", lastModuleUsedTime));
297 }
298 
GetModuleRecordForResult(napi_env env,const std::vector<BundleActiveModuleRecord> & moduleRecords,napi_value result)299 void BundleStateCommon::GetModuleRecordForResult(napi_env env,
300     const std::vector<BundleActiveModuleRecord> &moduleRecords, napi_value result)
301 {
302     int32_t index = 0;
303     for (const auto &item : moduleRecords) {
304         napi_value moduleObject = nullptr;
305         NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &moduleObject));
306         GetModuleRecordBasicForResult(env, item, moduleObject);
307 
308         napi_value formRecords = nullptr;
309         NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &formRecords));
310         int32_t formIdx = 0;
311         for (const auto& oneFormRecord : item.formRecords_) {
312             napi_value formObject = nullptr;
313             NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &formObject));
314             napi_value formName = nullptr;
315             NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, oneFormRecord.formName_.c_str(), NAPI_AUTO_LENGTH,
316                 &formName));
317             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, formObject, "formName", formName));
318 
319             napi_value formDimension = nullptr;
320             NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, oneFormRecord.formDimension_, &formDimension));
321             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, formObject, "formDimension", formDimension));
322 
323             napi_value formId = nullptr;
324             NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, oneFormRecord.formId_, &formId));
325             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, formObject, "formId", formId));
326 
327             napi_value formLastUsedTime = nullptr;
328             NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, oneFormRecord.formLastUsedTime_, &formLastUsedTime));
329             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, formObject, "formLastUsedTime", formLastUsedTime));
330 
331             napi_value count = nullptr;
332             NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, oneFormRecord.count_, &count));
333             NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, formObject, "count", count));
334             NAPI_CALL_RETURN_VOID(env, napi_set_element(env, formRecords, formIdx, formObject));
335             formIdx++;
336         }
337         NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "formRecords", formRecords));
338         NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, moduleObject));
339         index++;
340     }
341 }
342 
SetPromiseInfo(const napi_env & env,const napi_deferred & deferred,const napi_value & result,const int32_t & errorCode)343 void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred &deferred,
344     const napi_value &result, const int32_t &errorCode)
345 {
346     switch (errorCode) {
347         case ERR_OK:
348             napi_resolve_deferred(env, deferred, result);
349             break;
350         default:
351             napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode));
352             break;
353     }
354 }
355 
GetReflectErrCode(int32_t errCode)356 int32_t BundleStateCommon::GetReflectErrCode(int32_t errCode)
357 {
358     if (errCode < ERR_GET_SYSTEM_ABILITY_MANAGER_FAILED) {
359         return errCode;
360     }
361     return errCode / ERR_MULTIPLE;
362 }
363 
GetErrorValue(napi_env env,int32_t errCode)364 napi_value BundleStateCommon::GetErrorValue(napi_env env, int32_t errCode)
365 {
366     if (errCode == ERR_OK) {
367         return NapiGetNull(env);
368     }
369     napi_value result = nullptr;
370     napi_value eCode = nullptr;
371     napi_value eMsg = nullptr;
372     int32_t reflectCode = GetReflectErrCode(errCode);
373     std::string errMsg = GetSaErrCodeMsg(errCode, reflectCode);
374     NAPI_CALL(env, napi_create_int32(env, reflectCode, &eCode));
375     NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(), errMsg.length(), &eMsg));
376     NAPI_CALL(env, napi_create_object(env, &result));
377     NAPI_CALL(env, napi_set_named_property(env, result, "code", eCode));
378     NAPI_CALL(env, napi_set_named_property(env, result, "message", eMsg));
379     return result;
380 }
381 
JSParaError(const napi_env & env,const napi_ref & callback,const int32_t & errorCode)382 napi_value BundleStateCommon::JSParaError(const napi_env &env, const napi_ref &callback, const int32_t &errorCode)
383 {
384     if (callback) {
385         napi_value result = nullptr;
386         napi_create_array(env, &result);
387         SetCallbackInfo(env, callback, errorCode, result);
388         return result;
389     } else {
390         napi_value promise = nullptr;
391         napi_deferred deferred = nullptr;
392         napi_create_promise(env, &deferred, &promise);
393         napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode));
394         return promise;
395     }
396 }
397 
GetTypeStringValue(napi_env env,napi_value param,const std::string & result)398 std::string BundleStateCommon::GetTypeStringValue(napi_env env, napi_value param, const std::string &result)
399 {
400     size_t size = 0;
401     if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != BUNDLE_STATE_OK) {
402         return result;
403     }
404 
405     std::string value("");
406     if (size == 0) {
407         return result;
408     }
409 
410     char *buf = new (std::nothrow) char[size + 1];
411     if (buf == nullptr) {
412         return value;
413     }
414 
415     if (memset_s(buf, size + 1, 0, size + 1) != EOK) {
416         delete[] buf;
417         buf = nullptr;
418         return value;
419     }
420 
421     bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == BUNDLE_STATE_OK;
422     if (rev) {
423         value = buf;
424     } else {
425         value = result;
426     }
427 
428     delete[] buf;
429     buf = nullptr;
430     return value;
431 }
432 
GetInt64NumberValue(const napi_env & env,const napi_value & value,int64_t & result)433 napi_value BundleStateCommon::GetInt64NumberValue(const napi_env &env, const napi_value &value, int64_t &result)
434 {
435     napi_valuetype valuetype = napi_undefined;
436 
437     NAPI_CALL(env, napi_typeof(env, value, &valuetype));
438     if (valuetype != napi_number) {
439         BUNDLE_ACTIVE_LOGE("Wrong argument type, number expected.");
440         return nullptr;
441     }
442     napi_get_value_int64(env, value, &result);
443     return BundleStateCommon::NapiGetNull(env);
444 }
445 
GetInt32NumberValue(const napi_env & env,const napi_value & value,int32_t & result)446 napi_value BundleStateCommon::GetInt32NumberValue(const napi_env &env, const napi_value &value, int32_t &result)
447 {
448     napi_valuetype valuetype = napi_undefined;
449     NAPI_CALL(env, napi_typeof(env, value, &valuetype));
450     if (valuetype != napi_number) {
451         BUNDLE_ACTIVE_LOGE("Wrong argument type. Number expected.");
452         return nullptr;
453     }
454     napi_get_value_int32(env, value, &result);
455     return BundleStateCommon::NapiGetNull(env);
456 }
457 
SettingAsyncWorkData(const napi_env & env,const napi_ref & callback,AsyncWorkData & workData,napi_value & promise)458 void BundleStateCommon::SettingAsyncWorkData(
459     const napi_env &env, const napi_ref &callback, AsyncWorkData &workData, napi_value &promise)
460 {
461     if (callback) {
462         workData.callback = callback;
463         workData.isCallback = true;
464     } else {
465         napi_deferred deferred = nullptr;
466         NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise));
467         workData.deferred = deferred;
468         workData.isCallback = false;
469     }
470 }
471 
QueryBundleStatsInfos(int64_t & beginTime,int64_t & endTime,int32_t & errCode)472 std::shared_ptr<std::map<std::string, BundleActivePackageStats>> BundleStateCommon::QueryBundleStatsInfos(
473     int64_t &beginTime, int64_t &endTime, int32_t &errCode)
474 {
475     std::vector<BundleActivePackageStats> packageStats;
476     errCode = BundleActiveClient::GetInstance().QueryBundleStatsInfoByInterval(packageStats, INTERVAL_TYPE_DEFAULT,
477         beginTime, endTime);
478     std::shared_ptr<std::map<std::string, BundleActivePackageStats>> mergedPackageStats =
479         std::make_shared<std::map<std::string, BundleActivePackageStats>>();
480     if (packageStats.empty()) {
481         return nullptr;
482     }
483     for (auto packageStat : packageStats) {
484         std::map<std::string, BundleActivePackageStats>::iterator iter =
485             mergedPackageStats->find(packageStat.bundleName_);
486         if (iter != mergedPackageStats->end()) {
487             MergePackageStats(iter->second, packageStat);
488         } else {
489             mergedPackageStats->
490                 insert(std::pair<std::string, BundleActivePackageStats>(packageStat.bundleName_, packageStat));
491         }
492     }
493     return mergedPackageStats;
494 }
495 
MergePackageStats(BundleActivePackageStats & left,const BundleActivePackageStats & right)496 void BundleStateCommon::MergePackageStats(BundleActivePackageStats &left, const BundleActivePackageStats &right)
497 {
498     if (left.bundleName_ != right.bundleName_) {
499         BUNDLE_ACTIVE_LOGE("Merge package stats failed, existing packageName : %{public}s,"
500             " new packageName : %{public}s,", left.bundleName_.c_str(), right.bundleName_.c_str());
501         return;
502     }
503     left.lastTimeUsed_ = std::max(left.lastTimeUsed_, right.lastTimeUsed_);
504     left.lastContiniousTaskUsed_ = std::max(left.lastContiniousTaskUsed_, right.lastContiniousTaskUsed_);
505     left.totalInFrontTime_ += right.totalInFrontTime_;
506     left.totalContiniousTaskUsedTime_ += right.totalContiniousTaskUsedTime_;
507     left.bundleStartedCount_ += right.bundleStartedCount_;
508 }
509 
HandleEventStatsInfo(const napi_env & env,AsyncCallbackInfoEventStats * asyncCallbackInfo,EventStatesParamsInfo & params)510 std::unique_ptr<AsyncCallbackInfoEventStats> BundleStateCommon::HandleEventStatsInfo(const napi_env &env,
511     AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo &params)
512 {
513     if (!asyncCallbackInfo) {
514         params.errorCode = ERR_ASYNC_CALLBACK_NULLPTR;
515         BundleStateCommon::HandleParamErr(env, ERR_ASYNC_CALLBACK_NULLPTR, "");
516         return nullptr;
517     }
518     if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) {
519         params.errorCode = ERR_ASYNC_CALLBACK_INIT_FAILED;
520         BundleStateCommon::HandleParamErr(env, ERR_ASYNC_CALLBACK_INIT_FAILED, "");
521         delete asyncCallbackInfo;
522         asyncCallbackInfo = nullptr;
523         return nullptr;
524     }
525     std::unique_ptr<AsyncCallbackInfoEventStats> callbackPtr {asyncCallbackInfo};
526     callbackPtr->beginTime = params.beginTime;
527     callbackPtr->endTime = params.endTime;
528     BUNDLE_ACTIVE_LOGI("CallbackPtr->beginTime: %{public}lld, callbackPtr->endTime: %{public}lld",
529         (long long)callbackPtr->beginTime, (long long)callbackPtr->endTime);
530     return callbackPtr;
531 }
532 }  // namespace DeviceUsageStats
533 }  // namespace OHOS
534 
535