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