diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index 1beaff661e6df951717a28869afabec891d74600..e1730a60df122719adc819213cdabd0f93f9f0cf 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -34,7 +34,7 @@ void BundleStateCommon::GetCallbackPromiseResult(const napi_env &env, if (info.isCallback) { SetCallbackInfo(env, info.callback, info.errorCode, result); } else { - SetPromiseInfo(env, info.deferred, result); + SetPromiseInfo(env, info.deferred, result, info.errorCode); } } @@ -48,7 +48,7 @@ void BundleStateCommon::SetCallbackInfo( napi_value resultout = nullptr; napi_get_reference_value(env, callbackIn, &callback); napi_value results[ARGS_TWO] = {nullptr}; - results[PARAM_FIRST] = GetCallbackErrorValue(env, errorCode); + results[PARAM_FIRST] = GetErrorValue(env, errorCode); results[PARAM_SECOND] = result; NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &results[PARAM_FIRST], &resultout)); @@ -138,37 +138,44 @@ void BundleStateCommon::GetBundleStateInfoForResult(napi_env env, } } -void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, const napi_value &result) +void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, + const napi_value &result, const int &errorCode) { - napi_resolve_deferred(env, deferred, result); + if (errorCode == ERR_OK) { + napi_resolve_deferred(env, deferred, result); + } else { + napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode)); + } } -napi_value BundleStateCommon::GetCallbackErrorValue(napi_env env, int errCode) +napi_value BundleStateCommon::GetErrorValue(napi_env env, int errCode) { napi_value result = nullptr; napi_value eCode = nullptr; NAPI_CALL(env, napi_create_int32(env, errCode, &eCode)); NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, napi_set_named_property(env, result, "data", eCode)); + NAPI_CALL(env, napi_set_named_property(env, result, "code", eCode)); return result; } -napi_value BundleStateCommon::JSParaError(const napi_env &env, const napi_ref &callback) +napi_value BundleStateCommon::JSParaError(const napi_env &env, const napi_ref &callback, const int &errorCode) { if (callback) { - return BundleStateCommon::NapiGetNull(env); + napi_value result = nullptr; + napi_create_array(env, &result); + SetCallbackInfo(env, callback, errorCode, result); + return result; } else { napi_value promise = nullptr; napi_deferred deferred = nullptr; napi_create_promise(env, &deferred, &promise); - napi_resolve_deferred(env, deferred, BundleStateCommon::NapiGetNull(env)); + napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode)); return promise; } } std::string BundleStateCommon::GetTypeStringValue(napi_env env, napi_value param, const std::string &result) { - BUNDLE_ACTIVE_LOGI("GetTypeStringValue start"); size_t size = 0; if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != BUNDLE_STATE_OK) { return result; @@ -197,33 +204,31 @@ std::string BundleStateCommon::GetTypeStringValue(napi_env env, napi_value param delete[] buf; buf = nullptr; - BUNDLE_ACTIVE_LOGI("string result: %{public}s", value.c_str()); return value; } napi_value BundleStateCommon::GetInt64NumberValue(const napi_env &env, const napi_value &value, int64_t &result) { - BUNDLE_ACTIVE_LOGI("GetInt64NumberValue start"); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, value, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number or function expected."); + if (valuetype != napi_number) { + BUNDLE_ACTIVE_LOGE("Wrong argument type, number expected."); + return nullptr; + } napi_get_value_int64(env, value, &result); - BUNDLE_ACTIVE_LOGI("number result: %{public}lld", result); - return BundleStateCommon::NapiGetNull(env); } napi_value BundleStateCommon::GetInt32NumberValue(const napi_env &env, const napi_value &value, int32_t &result) { - BUNDLE_ACTIVE_LOGI("GetInt32NumberValue start"); napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, value, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number or function expected."); + if (valuetype != napi_number) { + BUNDLE_ACTIVE_LOGE("Wrong argument type. Number expected."); + return nullptr; + } napi_get_value_int32(env, value, &result); - BUNDLE_ACTIVE_LOGI("number result: %{public}d", result); - return BundleStateCommon::NapiGetNull(env); } diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index 8d84091dfa25928e9616a1d61b1889ebf6f2198c..2a30443372af7b15e333e738fc31995da038efd0 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -15,9 +15,10 @@ #include -#include "bundle_state_common.h" #include "bundle_active_log.h" +#include "bundle_state_common.h" #include "bundle_state_data.h" +#include "bundle_state_inner_errors.h" namespace OHOS { namespace DeviceUsageStats { @@ -41,26 +42,28 @@ napi_value ParseIsIdleStateParameters(const napi_env &env, const napi_callback_i napi_value argv[Is_Idle_State_PARAMS] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_ASSERT(env, argc == Is_Idle_State_MIN_PARAMS || argc == Is_Idle_State_PARAMS, - "invalid number of parameters"); + "Invalid number of parameters"); // argv[0] : bundleName - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "ParseIsIdleStateParameters invalid parameter type. " - "String expected."); std::string result = ""; params.bundleName = BundleStateCommon::GetTypeStringValue(env, argv[0], result); if (params.bundleName.empty()) { - BUNDLE_ACTIVE_LOGI("ParseIsIdleStateParameters failed, bundleName is invalid."); - return nullptr; + BUNDLE_ACTIVE_LOGE("ParseIsIdleStateParameters failed, bundleName is empty."); + params.errorCode = ERR_USAGE_STATS_BUNDLENAME_EMPTY; + } + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + if ((valuetype != napi_string) && (params.errorCode == ERR_OK)) { + BUNDLE_ACTIVE_LOGE("Wrong argument type, string expected."); + params.errorCode = ERR_USAGE_STATS_BUNDLENAME_TYPE; } // argv[1]: callback if (argc == Is_Idle_State_PARAMS) { napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "ParseIsIdleStateParameters invalid parameter type. " - "Function expected."); + NAPI_ASSERT(env, valuetype == napi_function, + "ParseIsIdleStateParameters invalid parameter type, function expected."); napi_create_reference(env, argv[1], 1, ¶ms.callback); } return BundleStateCommon::NapiGetNull(env); @@ -69,36 +72,33 @@ napi_value ParseIsIdleStateParameters(const napi_env &env, const napi_callback_i napi_value IsIdleState(napi_env env, napi_callback_info info) { IsIdleStateParamsInfo params; - if (ParseIsIdleStateParameters(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); + ParseIsIdleStateParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; AsyncCallbackInfoIsIdleState *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoIsIdleState {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } asyncCallbackInfo->bundleName = params.bundleName; - BUNDLE_ACTIVE_LOGI("asyncCallbackInfo->bundleName: %{public}s", asyncCallbackInfo->bundleName.c_str()); BundleStateCommon::SettingCallbackPromiseInfo(env, params.callback, asyncCallbackInfo->info, promise); - napi_value resourceName = nullptr; napi_create_string_latin1(env, "IsIdleState", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("IsIdleState, worker pool thread execute."); AsyncCallbackInfoIsIdleState *asyncCallbackInfo = (AsyncCallbackInfoIsIdleState *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->state = BundleActiveClient::GetInstance().IsBundleIdle( asyncCallbackInfo->bundleName); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("IsIdleState, asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("IsIdleState, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoIsIdleState *asyncCallbackInfo = (AsyncCallbackInfoIsIdleState *)data; @@ -118,9 +118,7 @@ napi_value IsIdleState(napi_env env, napi_callback_info info) }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - if (asyncCallbackInfo->info.isCallback) { return BundleStateCommon::NapiGetNull(env); } else { @@ -135,7 +133,7 @@ napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback napi_value argv[Priority_Group_PARAMS] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_ASSERT(env, argc == Priority_Group_MIN_PARAMS || argc == Priority_Group_PARAMS, - "invalid number of parameters"); + "Invalid number of parameters"); // argv[0]: callback if (argc == Priority_Group_PARAMS) { @@ -151,33 +149,28 @@ napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) { PriorityGroupParamsInfo params; - if (ParsePriorityGroupParameters(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); - } - + ParsePriorityGroupParameters(env, info, params); napi_value promise = nullptr; AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoPriorityGroup {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } BundleStateCommon::SettingCallbackPromiseInfo(env, params.callback, asyncCallbackInfo->info, promise); - napi_value resourceName = nullptr; napi_create_string_latin1(env, "QueryAppUsagePriorityGroup", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("QueryAppUsagePriorityGroup, worker pool thread execute."); AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->priorityGroup = BundleActiveClient::GetInstance().QueryPackageGroup(); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("QueryAppUsagePriorityGroup, asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("QueryAppUsagePriorityGroup, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; @@ -185,11 +178,9 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) napi_value result = nullptr; napi_create_int32(env, asyncCallbackInfo->priorityGroup, &result); BundleStateCommon::GetCallbackPromiseResult(env, asyncCallbackInfo->info, result); - if (asyncCallbackInfo->info.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->info.callback); } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; asyncCallbackInfo = nullptr; @@ -197,9 +188,7 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - if (asyncCallbackInfo->info.isCallback) { return BundleStateCommon::NapiGetNull(env); } else { @@ -213,18 +202,34 @@ napi_value ParseStatesParameters(const napi_env &env, const napi_callback_info & napi_value argv[States_PARAMS] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_ASSERT(env, argc == States_MIN_PARAMS || argc == States_PARAMS, - "invalid number of parameters"); - + "Invalid number of parameters"); + // argv[0] : beginTime if (BundleStateCommon::GetInt64NumberValue(env, argv[0], params.beginTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, beginTime is invalid."); - return nullptr; + BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, beginTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.beginTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, beginTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; } // argv[1] : endTime - if (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, endTime is invalid."); - return nullptr; + if ((params.errorCode == ERR_OK) + && (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr)) { + BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, endTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.endTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, endTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) && (params.endTime <= params.beginTime)) { + BUNDLE_ACTIVE_LOGE("ParseStatesParameters endTime(%{public}lld) <= beginTime(%{public}lld)", + params.endTime, params.beginTime); + params.errorCode = ERR_USAGE_STATS_TIME_INTERVAL; } // argv[SECOND_ARG]: callback @@ -241,15 +246,16 @@ napi_value ParseStatesParameters(const napi_env &env, const napi_callback_info & napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) { StatesParamsInfo params; - if (ParseStatesParameters(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); + ParseStatesParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; AsyncCallbackInfoStates *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoStates {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } asyncCallbackInfo->beginTime = params.beginTime; BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates asyncCallbackInfo->beginTime: %{public}lld", @@ -266,16 +272,15 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates, worker pool thread execute."); AsyncCallbackInfoStates *asyncCallbackInfo = (AsyncCallbackInfoStates *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->BundleActiveState = BundleActiveClient::GetInstance().QueryCurrentEvents(asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("QueryCurrentBundleActiveStates, asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoStates *asyncCallbackInfo = (AsyncCallbackInfoStates *)data; @@ -288,7 +293,6 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) if (asyncCallbackInfo->info.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->info.callback); } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; asyncCallbackInfo = nullptr; @@ -309,15 +313,16 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) { StatesParamsInfo params; - if (ParseStatesParameters(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); + ParseStatesParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; AsyncCallbackInfoStates *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoStates {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } asyncCallbackInfo->beginTime = params.beginTime; BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates asyncCallbackInfo->beginTime: %{public}lld", @@ -334,16 +339,15 @@ napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates, worker pool thread execute."); AsyncCallbackInfoStates *asyncCallbackInfo = (AsyncCallbackInfoStates *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->BundleActiveState = BundleActiveClient::GetInstance().QueryEvents(asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("QueryBundleActiveStates, asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoStates *asyncCallbackInfo = (AsyncCallbackInfoStates *)data; @@ -352,11 +356,9 @@ napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) napi_create_array(env, &result); BundleStateCommon::GetBundleActiveEventForResult(env, asyncCallbackInfo->BundleActiveState, result); BundleStateCommon::GetCallbackPromiseResult(env, asyncCallbackInfo->info, result); - if (asyncCallbackInfo->info.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->info.callback); } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; asyncCallbackInfo = nullptr; @@ -364,9 +366,7 @@ napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - if (asyncCallbackInfo->info.isCallback) { return BundleStateCommon::NapiGetNull(env); } else { @@ -381,24 +381,46 @@ napi_value ParseAppUsageParametersByInterval(const napi_env &env, const napi_cal napi_value argv[App_Usage_PARAMS_BY_INTERVAL] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_ASSERT(env, argc == App_Usage_MIN_PARAMS_BY_INTERVAL || argc == App_Usage_PARAMS_BY_INTERVAL, - "invalid number of parameters"); + "Invalid number of parameters"); // argv[0] : intervalType if (BundleStateCommon::GetInt32NumberValue(env, argv[0], params.intervalType) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, beginTime is invalid."); - return nullptr; + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, intervalType is invalid."); + params.errorCode = ERR_USAGE_STATS_INTERVAL_TYPE; + } + if ((params.errorCode == ERR_OK) && ((params.intervalType < INTERVAL_NUMBER_MIN) + || (params.intervalType > INTERVAL_NUMBER_MAX))) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, intervalType number is invalid."); + params.errorCode = ERR_USAGE_STATS_INTERVAL_NUMBER; } // argv[1] : beginTime - if (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.beginTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, beginTime is invalid."); - return nullptr; + if ((params.errorCode == ERR_OK) + && (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.beginTime) == nullptr)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, beginTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.beginTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, beginTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; } // argv[SECOND_ARG] : endTime - if (BundleStateCommon::GetInt64NumberValue(env, argv[SECOND_ARG], params.endTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, endTime is invalid."); - return nullptr; + if ((params.errorCode == ERR_OK) + && (BundleStateCommon::GetInt64NumberValue(env, argv[SECOND_ARG], params.endTime) == nullptr)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, endTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.endTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, endTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) && (params.endTime <= params.beginTime)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval endTime(%{public}lld) <= beginTime(%{public}lld)", + params.endTime, params.beginTime); + params.errorCode = ERR_USAGE_STATS_TIME_INTERVAL; } // argv[THIRD_ARG]: callback @@ -415,15 +437,16 @@ napi_value ParseAppUsageParametersByInterval(const napi_env &env, const napi_cal napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info) { AppUsageParamsByIntervalInfo params; - if (ParseAppUsageParametersByInterval(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); + ParseAppUsageParametersByInterval(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; AsyncCallbackInfoAppUsageByInterval *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoAppUsageByInterval {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } asyncCallbackInfo->intervalType = params.intervalType; BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval asyncCallbackInfo->intervalType: %{public}d", @@ -435,24 +458,21 @@ napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info) BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval asyncCallbackInfo->endTime: %{public}lld", asyncCallbackInfo->endTime); BundleStateCommon::SettingCallbackPromiseInfo(env, params.callback, asyncCallbackInfo->info, promise); - napi_value resourceName = nullptr; napi_create_string_latin1(env, "QueryBundleStateInfoByInterval", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval, worker pool thread execute."); AsyncCallbackInfoAppUsageByInterval *asyncCallbackInfo = (AsyncCallbackInfoAppUsageByInterval *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->packageStats = BundleActiveClient::GetInstance().QueryPackageStats(asyncCallbackInfo->intervalType, asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("QueryBundleStateInfoByInterval, asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoAppUsageByInterval *asyncCallbackInfo = (AsyncCallbackInfoAppUsageByInterval *)data; @@ -473,9 +493,7 @@ napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info) }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - if (asyncCallbackInfo->info.isCallback) { return BundleStateCommon::NapiGetNull(env); } else { @@ -489,18 +507,34 @@ napi_value ParseAppUsageParameters(const napi_env &env, const napi_callback_info napi_value argv[App_Usage_PARAMS] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_ASSERT(env, argc == App_Usage_MIN_PARAMS || argc == App_Usage_PARAMS, - "invalid number of parameters"); - + "Invalid number of parameters"); + // argv[0] : beginTime if (BundleStateCommon::GetInt64NumberValue(env, argv[0], params.beginTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed, beginTime is invalid."); - return nullptr; + BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed, beginTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.beginTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed failed, beginTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; } // argv[1] : endTime - if (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed, endTime is invalid."); - return nullptr; + if ((params.errorCode == ERR_OK) + && (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed, endTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.endTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed failed, endTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) && (params.endTime <= params.beginTime)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters endTime(%{public}lld) <= beginTime(%{public}lld)", + params.endTime, params.beginTime); + params.errorCode = ERR_USAGE_STATS_TIME_INTERVAL; } // argv[SECOND_ARG]: callback @@ -517,14 +551,16 @@ napi_value ParseAppUsageParameters(const napi_env &env, const napi_callback_info napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) { AppUsageParamsInfo params; - if (ParseAppUsageParameters(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); + ParseAppUsageParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } napi_value promise = nullptr; AsyncCallbackInfoAppUsage *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoAppUsage {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } asyncCallbackInfo->beginTime = params.beginTime; BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos asyncCallbackInfo->beginTime: %{public}lld", @@ -539,15 +575,14 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos, worker pool thread execute."); AsyncCallbackInfoAppUsage *asyncCallbackInfo = (AsyncCallbackInfoAppUsage *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->packageStats = BundleStateCommon::GetPackageStats(asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("QueryBundleStateInfos asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoAppUsage *asyncCallbackInfo = (AsyncCallbackInfoAppUsage *)data; diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h index 5e8daf4642d1195c4b1037b9515b09ffcf867404..a8ff5e20beb17113cc1e6cf91f14253d44e8b29d 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h @@ -33,7 +33,7 @@ public: static napi_value NapiGetUndefined(napi_env env); - static napi_value GetCallbackErrorValue(napi_env env, int errCode); + static napi_value GetErrorValue(napi_env env, int errCode); static void SettingCallbackPromiseInfo( const napi_env &env, const napi_ref &callback, CallbackPromiseInfo &info, napi_value &promise); @@ -53,9 +53,10 @@ public: static void GetBundleStateInfoForResult(napi_env env, const std::shared_ptr> &packageStats, napi_value result); - static void SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, const napi_value &result); + static void SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, + const napi_value &result, const int &errorCode); - static napi_value JSParaError(const napi_env &env, const napi_ref &callback); + static napi_value JSParaError(const napi_env &env, const napi_ref &callback, const int &errorCode); static std::string GetTypeStringValue(napi_env env, napi_value param, const std::string &result); diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h index c854436457ebebaa61efb2b6335b29ef5ded1a4b..5d4f5652b1f3c6e9ae96871eaabc9736e7b7dfb6 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h @@ -39,6 +39,9 @@ namespace DeviceUsageStats { #define BUNDLE_STATE_OK 0 #define INTERVAL_TYPE_DEFAULT 0 +#define INTERVAL_NUMBER_MIN 0 +#define INTERVAL_NUMBER_MAX 4 +#define TIME_NUMBER_MIN 0 struct CallbackPromiseInfo { napi_ref callback = nullptr; @@ -93,16 +96,19 @@ struct AsyncCallbackInfoAppUsage { struct IsIdleStateParamsInfo { std::string bundleName; napi_ref callback = nullptr; + int errorCode = 0; }; struct PriorityGroupParamsInfo { napi_ref callback = nullptr; + int errorCode = 0; }; struct StatesParamsInfo { int64_t beginTime; int64_t endTime; napi_ref callback = nullptr; + int errorCode = 0; }; struct AppUsageParamsByIntervalInfo { @@ -110,12 +116,14 @@ struct AppUsageParamsByIntervalInfo { int64_t beginTime; int64_t endTime; napi_ref callback = nullptr; + int errorCode = 0; }; struct AppUsageParamsInfo { int64_t beginTime; int64_t endTime; napi_ref callback = nullptr; + int errorCode = 0; }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h new file mode 100644 index 0000000000000000000000000000000000000000..aa70a02b8fc3f21bb1c19e270fd0ef5f988e12fc --- /dev/null +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_INNER_ERRORS_H +#define FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_INNER_ERRORS_H + +#include "errors.h" + +namespace OHOS { +namespace DeviceUsageStats { +/** + * ErrCode layout + * + * +-----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + * | Bit |31|30|29|28|27|26|25|24|23|22|21|20|19|18|17|16|15|14|13|12|11|10|09|08|07|06|05|04|03|02|01|00| + * +-----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + * |Field|Reserved| Subsystem | Module | Code | + * +-----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + */ + +// DeviceUsageStats's module const defined. +enum : int { + DEVICE_USAGE_STATS_MODULE_COMMON = 0x01, +}; + +// Offset of device usage stats sub-system's errcode base, number : 39911424. +constexpr ErrCode DEVICE_USAGE_STATS_COMMON_ERR_OFFSET = + ErrCodeOffset(SUBSYS_IAWARE, DEVICE_USAGE_STATS_MODULE_COMMON); +// Device Usage Stats Common Error Code Defined. +enum : int { + ERR_USAGE_STATS_BUNDLENAME_EMPTY = DEVICE_USAGE_STATS_COMMON_ERR_OFFSET + 1, + ERR_USAGE_STATS_BUNDLENAME_TYPE, + ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR, + ERR_USAGE_STATS_BEGIN_TIME_INVALID, + ERR_USAGE_STATS_END_TIME_INVALID, + ERR_USAGE_STATS_TIME_INTERVAL, + ERR_USAGE_STATS_INTERVAL_TYPE, + ERR_USAGE_STATS_INTERVAL_NUMBER, +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_INNER_ERRORS_H \ No newline at end of file diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 5464548fdc4cb98683a4719612120e3afe075c5f..928e667f5814ae4afff19b83eeb2169ae8ced883 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -116,10 +116,11 @@ public: const int64_t timeStamp); // when received a USER_REMOVED commen event, call it to remove data. void OnUserRemoved(const int userId); + void OnUserSwitched(); // force set app group. void SetBundleGroup(const std::string& bundleName, const int newGroup, const int userId); // get all user in device - void GetAllActiveUser(std::vector &osAccountInfos); + void GetAllActiveUser(std::vector& activatedOsAccountIds); // when service stop, call it to unregister commen event and shutdown call back. void UnRegisterSubscriber(); int64_t GetSystemTimeMs(); @@ -140,6 +141,7 @@ private: void RegisterSubscriber(); std::shared_ptr commonEventSubscriber_; void RestoreAllData(); + int lastUsedUser_; }; } } diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 25fe675d5d0b703efff9a7c98c28dea84c847b6a..31b768e4d609928663ca265fd5983534451c7697 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -45,6 +45,7 @@ BundleActiveCore::BundleActiveCore() { systemTimeShot_ = -1; realTimeShot_ = -1; + lastUsedUser_ = -1; } BundleActiveCore::~BundleActiveCore() @@ -77,12 +78,11 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_REMOVE_USER, handlerobjToPtr); bundleActiveReportHandler_.lock()->SendEvent(event); } - } else if (action == CommonEventSupport::COMMON_EVENT_USER_ADDED) { + } else if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { int32_t userId = data.GetCode(); - BUNDLE_ACTIVE_LOGI("OnReceiveEvent receive add user event, user id is %{public}d", userId); - if (!activeGroupController_.expired() && userId >= 0) { - activeGroupController_.lock()->PeriodCheckBundleState(userId); - } + BUNDLE_ACTIVE_LOGI("OnReceiveEvent receive switched user event, user id is %{public}d", userId); + auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_SWITCH_USER); + bundleActiveReportHandler_.lock()->SendEvent(event); } else if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED || action == CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED) { int32_t userId = data.GetWant().GetIntParam("userId", 0); @@ -109,7 +109,7 @@ void BundleActiveCore::RegisterSubscriber() matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_OFF); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_ON); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_ADDED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); @@ -157,11 +157,15 @@ void BundleActiveCore::InitBundleGroupController() BUNDLE_ACTIVE_LOGI("Init Set group controller and handler done"); } RegisterSubscriber(); - std::vector osAccountInfos; - GetAllActiveUser(osAccountInfos); + std::vector activatedOsAccountIds; bundleGroupController_->bundleGroupEnable_ = true; - for (uint32_t i = 0; i < osAccountInfos.size(); i++) { - bundleGroupController_->PeriodCheckBundleState(osAccountInfos[i].GetLocalId()); + GetAllActiveUser(activatedOsAccountIds); + if (activatedOsAccountIds.size() == 0) { + BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated"); + return; + } + for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { + bundleGroupController_->PeriodCheckBundleState(activatedOsAccountIds[i]); } } @@ -236,7 +240,7 @@ void BundleActiveCore::RestoreAllData() bundleGroupController_->RestoreDurationToDatabase(); } if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event"); + BUNDLE_ACTIVE_LOGI("RestoreAllData remove flush to disk event"); handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); } } @@ -322,7 +326,7 @@ int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int userId) it->second->RenewTableTime(expectedSystemTime, actualSystemTime); it->second->LoadActiveStats(actualSystemTime, true, true); if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event"); + BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime remove flush to disk event"); handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); } } @@ -352,9 +356,37 @@ void BundleActiveCore::OnUserRemoved(const int userId) bundleGroupController_->OnUserRemoved(userId); } +void BundleActiveCore::OnUserSwitched() +{ + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + auto it = userStatServices_.find(lastUsedUser_); + if (it != userStatServices_.end()) { + if (it != userStatServices_.end()) { + BundleActiveEvent event; + event.eventId_ = BundleActiveEvent::FLUSH; + int64_t actualRealTime = timer->GetBootTimeMs(); + event.timeStamp_ = (actualRealTime - realTimeShot_) + systemTimeShot_; + event.abilityId_ = ""; + it->second->ReportEvent(event); + it->second->RestoreStats(true); + } + } + std::vector activatedOsAccountIds; + GetAllActiveUser(activatedOsAccountIds); + if (activatedOsAccountIds.size() == 0) { + BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated"); + return; + } + for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { + BUNDLE_ACTIVE_LOGI("start to period check for userId %{public}d", activatedOsAccountIds[i]); + bundleGroupController_->OnUserSwitched(activatedOsAccountIds[i]); + } +} + int BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int userId) { std::lock_guard lock(mutex_); + lastUsedUser_ = userId; if (userId == 0) { return -1; } @@ -468,14 +500,13 @@ int BundleActiveCore::IsBundleIdle(const std::string& bundleName, const int user return bundleGroupController_->IsBundleIdle(bundleName, userId); } -void BundleActiveCore::GetAllActiveUser(std::vector &osAccountInfos) +void BundleActiveCore::GetAllActiveUser(std::vector& activatedOsAccountIds) { - OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); - if (ret != ERR_OK) { - BUNDLE_ACTIVE_LOGI("GetAllActiveUser failed"); + if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds) != ERR_OK) { + BUNDLE_ACTIVE_LOGI("query activated account failed"); return; } - if (osAccountInfos.size() == 0) { + if (activatedOsAccountIds.size() == 0) { BUNDLE_ACTIVE_LOGI("GetAllActiveUser size is 0"); return; } diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index 4175d250fc70ad5bcfd45789f20722d945253b52..cc0f7a24bd9ef841a049f591ed0bca49b398b6fd 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -154,7 +154,7 @@ int32_t BundleActiveUsageDatabase::NearIndexOnOrAfterCurrentTime(int64_t current int64_t tableTime = -1; int32_t divisor = 2; while (low <= high) { - mid = (high - low) / divisor + low; + mid = (high + low) / divisor; tableTime = sortedTableArray.at(mid); if (currentTime > tableTime) { low = mid + 1; diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index 1de660fc0c4a8a0f29a6fd540407a3ec577e894a..67632020262716fde8046e027b883beb1963e9f4 100644 --- a/services/packagegroup/include/bundle_active_group_controller.h +++ b/services/packagegroup/include/bundle_active_group_controller.h @@ -84,6 +84,7 @@ public: int IsBundleIdle(const std::string& bundleName, const int userId); int QueryPackageGroup(const int userId, const std::string& bundleName); void ShutDown(const int64_t bootBasedTimeStamp); + void OnUserSwitched(const int userId); private: std::mutex mutex_; diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index f89d4bf08a94e3bfd1a4e55ec13d40f18c4b9515..519311f47333923321dccdb69892355d83bf9704 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -45,6 +45,18 @@ void BundleActiveGroupController::OnUserRemoved(const int userId) { std::lock_guard lock(mutex_); bundleUserHistory_->userHistory_.erase(userId); + if (!activeGroupHandler_.expired()) { + activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE); + } +} + +void BundleActiveGroupController::OnUserSwitched(const int userId) +{ + std::lock_guard lock(mutex_); + if (!activeGroupHandler_.expired()) { + activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE); + } + PeriodCheckBundleState(userId); } void BundleActiveGroupController::OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp) diff --git a/services/packageusage/include/bundle_active_report_handler.h b/services/packageusage/include/bundle_active_report_handler.h index bc9ea44107018c56147b28fc1a0706073fd5393a..ad2714dedaff5416d998b5e04be44b9c2cb3d975 100644 --- a/services/packageusage/include/bundle_active_report_handler.h +++ b/services/packageusage/include/bundle_active_report_handler.h @@ -39,8 +39,8 @@ public: static const int MSG_REPORT_EVENT_TO_ALL_USER = 1; static const int MSG_FLUSH_TO_DISK = 2; static const int MSG_REMOVE_USER = 3; - static const int MSG_DEVICE_SHUTDOWN = 4; - static const int MSG_BUNDLE_UNINSTALLED = 5; + static const int MSG_BUNDLE_UNINSTALLED = 4; + static const int MSG_SWITCH_USER = 5; private: std::shared_ptr bundleActiveCore_; diff --git a/services/packageusage/include/bundle_active_user_service.h b/services/packageusage/include/bundle_active_user_service.h index 6aa13e79464ec01e237502bc8d9580eb69d15800..2bce5f34f9952224ef37e5c54a53702fbecffbe9 100644 --- a/services/packageusage/include/bundle_active_user_service.h +++ b/services/packageusage/include/bundle_active_user_service.h @@ -71,7 +71,8 @@ private: BundleActiveCalendar::YEAR_MILLISECONDS}; void NotifyStatsChanged(); void NotifyNewUpdate(); - void printstat(); + void PrintInMemPackageStats(const int idx); + void PrintInMemEventStats(); }; } } diff --git a/services/packageusage/src/bundle_active_report_handler.cpp b/services/packageusage/src/bundle_active_report_handler.cpp index d02a40d18cdee7cbb6443cd1c4810529c6789aa5..33b734d06dbd952647057e5e421bc409a328da1a 100644 --- a/services/packageusage/src/bundle_active_report_handler.cpp +++ b/services/packageusage/src/bundle_active_report_handler.cpp @@ -61,10 +61,6 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point bundleActiveCore_->OnUserRemoved(tmpHandlerobj.userId_); break; } - case MSG_DEVICE_SHUTDOWN: { - bundleActiveCore_->ShutDown(); - break; - } case MSG_BUNDLE_UNINSTALLED: { BUNDLE_ACTIVE_LOGI("MSG_BUNDLE_UNINSTALLED CALLED"); auto ptrToHandlerobj = event->GetSharedObject(); @@ -72,6 +68,9 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point bundleActiveCore_->OnBundleUninstalled(tmpHandlerobj.userId_, tmpHandlerobj.bundleName_); break; } + case MSG_SWITCH_USER: { + bundleActiveCore_->OnUserSwitched(); + } default: { break; } diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index 4686d761c353be675076c5f65eec21066476da10..ed0dd0f6b0a2a782ff3c0b707c88017bab79dddb 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -304,7 +304,12 @@ std::vector BundleActiveUserService::QueryPackageStats return result; } int64_t truncatedEndTime = std::min(currentStats->beginTime_, endTime); + BUNDLE_ACTIVE_LOGI("Query package data in db from %{public}lld to %{public}lld, current begin %{public}lld", + beginTime, truncatedEndTime, currentStats->beginTime_); result = database_.QueryDatabaseUsageStats(intervalType, beginTime, truncatedEndTime, userId); + BUNDLE_ACTIVE_LOGI("Query package data in db result size is %{public}d", + static_cast(result.size())); + PrintInMemPackageStats(intervalType); // if we need a in-memory stats, combine current stats with result from database. if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { BUNDLE_ACTIVE_LOGI("QueryPackageStats need in memory stats"); @@ -339,9 +344,10 @@ std::vector BundleActiveUserService::QueryEvents(const int64_ if (beginTime >= currentStats->endTime_) { return result; } - BUNDLE_ACTIVE_LOGI("QueryEvents bundle name is %{public}s", bundleName.c_str()); + BUNDLE_ACTIVE_LOGI("Query event bundle name is %{public}s", bundleName.c_str()); result = database_.QueryDatabaseEvents(beginTime, endTime, userId, bundleName); - BUNDLE_ACTIVE_LOGI("event database query size is %{public}d", result.size()); + BUNDLE_ACTIVE_LOGI("Query event data in db result size is %{public}d", result.size()); + PrintInMemEventStats(); // if we need a in-memory stats, combine current stats with result from database. if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { BUNDLE_ACTIVE_LOGI("QueryEvents need in memory stats"); @@ -358,17 +364,25 @@ std::vector BundleActiveUserService::QueryEvents(const int64_ return result; } -void BundleActiveUserService::printstat() +void BundleActiveUserService::PrintInMemPackageStats(const int idx) { - BUNDLE_ACTIVE_LOGI("printstat called"); - int idx = 0; + BUNDLE_ACTIVE_LOGI("PrintInMemPackageStats called"); for (auto it : currentStats_[idx]->bundleStats_) { - BUNDLE_ACTIVE_LOGI("bundle name is %{public}s", it.first.c_str()); - int64_t lasttimeused = it.second->lastTimeUsed_; - int64_t totalusedtime = it.second->totalInFrontTime_; - BUNDLE_ACTIVE_LOGI("event stat is, totaltime is %{public}lld, lasttimeused is %{public}lld", - totalusedtime, lasttimeused); + BUNDLE_ACTIVE_LOGI("In mem, bundle name is %{public}s", it.first.c_str()); + int64_t lastTimeUsed = it.second->lastTimeUsed_; + int64_t totalUsedTime = it.second->totalInFrontTime_; + int64_t lastTimeContinuousTaskUsed = it.second->lastContiniousTaskUsed_; + int64_t totalTimeContinuousTaskUsed = it.second->totalContiniousTaskUsedTime_; + BUNDLE_ACTIVE_LOGI("In mem, event stat is, totaltime is %{public}lld, lastTimeUsed is %{public}lld" + "total continuous task is %{public}lld, lastTimeContinuousTaskUsed is %{public}lld", + totalUsedTime, lastTimeUsed, totalTimeContinuousTaskUsed, lastTimeContinuousTaskUsed); } +} + +void BundleActiveUserService::PrintInMemEventStats() +{ + BUNDLE_ACTIVE_LOGI("PrintInMemEventStats called"); + int idx = 0; int size = static_cast(currentStats_[idx]->events_.events_.size()); for (int i = 0; i < size; i++) { std::string abilityId = currentStats_[idx]->events_.events_[i].abilityId_; @@ -376,7 +390,7 @@ void BundleActiveUserService::printstat() std::string bundlename = currentStats_[idx]->events_.events_[i].bundleName_; int eventid = currentStats_[idx]->events_.events_[i].eventId_; int64_t timestamp = currentStats_[idx]->events_.events_[i].timeStamp_; - BUNDLE_ACTIVE_LOGI("event stat is, abilityid is %{public}s, abilityname is %{public}s, " + BUNDLE_ACTIVE_LOGI("In mem, event stat is, abilityid is %{public}s, abilityname is %{public}s, " "bundlename is %{public}s, eventid is %{public}d, timestamp is %{public}lld", abilityId.c_str(), abilityname.c_str(), bundlename.c_str(), eventid, timestamp); }