diff --git a/BUILD.gn b/BUILD.gn index 1a9d6724d82300c3c140c9e7936fd6489cb35eb2..0ba5f34ba28d63902f5c65f16a58fe0a1fde9c04 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -98,6 +98,9 @@ ohos_shared_library("usagestatservice") { "services/common/src/bundle_active_debug_mode.cpp", "services/common/src/bundle_active_log.cpp", "services/common/src/bundle_active_open_callback.cpp", + "services/common/src/bundle_active_power_state_callback_proxy.cpp", + "services/common/src/bundle_active_power_state_callback_service.cpp", + "services/common/src/bundle_active_power_state_callback_stub.cpp", "services/common/src/bundle_active_service.cpp", "services/common/src/bundle_active_shutdown_callback_proxy.cpp", "services/common/src/bundle_active_shutdown_callback_service.cpp", diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index ae6a6d52bb30833861798993a034fd65150da467..c5efe405da6eaea29dd83ab3a6f63718efb1a362 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -16,7 +16,7 @@ #include "securec.h" #include "bundle_active_log.h" -#include "bundle_state_data.h" +#include "bundle_state_inner_errors.h" #include "bundle_state_common.h" namespace OHOS { @@ -128,6 +128,58 @@ void BundleStateCommon::GetBundleStateInfoByIntervalForResult( } } +void BundleStateCommon::GetBundleActiveEventStatsForResult(napi_env env, + const std::vector &eventStats, napi_value result) +{ + int32_t index = 0; + for (const auto &item : eventStats) { + napi_value eventStatsObject = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &eventStatsObject)); + + napi_value name = nullptr; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, item.name_.c_str(), NAPI_AUTO_LENGTH, &name)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "name", name)); + + napi_value eventId = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "eventId", eventId)); + + napi_value count = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.count_, &count)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "count", count)); + + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, eventStatsObject)); + index++; + } +} + +void BundleStateCommon::GetBundleActiveNotificationNumberForResult(napi_env env, + const std::vector &eventStats, napi_value result) +{ + int32_t index = 0; + for (const auto &item : eventStats) { + napi_value eventStatsObject = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &eventStatsObject)); + + napi_value name = nullptr; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, item.name_.c_str(), NAPI_AUTO_LENGTH, &name)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "name", name)); + + napi_value eventId = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "eventId", eventId)); + + napi_value count = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.count_, &count)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "count", count)); + + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, eventStatsObject)); + index++; + } +} + void BundleStateCommon::GetBundleStateInfoForResult(napi_env env, const std::shared_ptr> &packageStats, napi_value result) { @@ -394,6 +446,27 @@ void BundleStateCommon::MergePackageStats(BundleActivePackageStats &left, const left.totalContiniousTaskUsedTime_ += right.totalContiniousTaskUsedTime_; left.bundleStartedCount_ += right.bundleStartedCount_; } + +std::unique_ptr BundleStateCommon::HandleEventStatsInfo( + AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo ¶ms) +{ + if (!asyncCallbackInfo) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return nullptr; + } + if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return nullptr; + } + std::unique_ptr callbackPtr {asyncCallbackInfo}; + callbackPtr->beginTime = params.beginTime; + callbackPtr->endTime = params.endTime; + BUNDLE_ACTIVE_LOGI("CallbackPtr->beginTime: %{public}lld, callbackPtr->endTime: %{public}lld", + (long long)callbackPtr->beginTime, (long long)callbackPtr->endTime); + return callbackPtr; +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/frameworks/src/bundle_state_init.cpp b/frameworks/src/bundle_state_init.cpp index 56e36f89b19d0ca4be68425304fcf744fb134228..27b3e5ac4105b93e6bef337231d372850f4ae595 100644 --- a/frameworks/src/bundle_state_init.cpp +++ b/frameworks/src/bundle_state_init.cpp @@ -40,7 +40,9 @@ static napi_value BundleStateInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("queryBundleActiveStates", QueryBundleActiveStates), DECLARE_NAPI_FUNCTION("queryBundleStateInfoByInterval", QueryBundleStateInfoByInterval), DECLARE_NAPI_FUNCTION("queryBundleStateInfos", QueryBundleStateInfos), - DECLARE_NAPI_FUNCTION("getRecentlyUsedModules", GetModuleUsageRecord) + DECLARE_NAPI_FUNCTION("getRecentlyUsedModules", GetModuleUsageRecord), + DECLARE_NAPI_FUNCTION("queryBundleActiveEventStates", QueryBundleActiveEventStates), + DECLARE_NAPI_FUNCTION("queryAppNotificationNumber", QueryAppNotificationNumber) }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index 7b840ef2e1889b1c220f3b79fb1a8df34223bee5..891e8897b5a93510ec36366943cac29e0f80bb36 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -39,6 +39,8 @@ const uint32_t MODULE_RECORDS_PARAMS = 2; const uint32_t SECOND_ARG = 2; const uint32_t THIRD_ARG = 3; const int32_t MAXNUM_UP_LIMIT = 1000; +const uint32_t EVENT_STATES_MIN_PARAMS = 2; +const uint32_t EVENT_STATES_PARAMS = 3; napi_value ParseModuleRecordsParameters(const napi_env &env, const napi_callback_info &info, ModuleRecordParamsInfo ¶ms) @@ -724,6 +726,152 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) return promise; } } + +napi_value ParseEventStatesParameters(const napi_env &env, const napi_callback_info &info, + EventStatesParamsInfo ¶ms) +{ + size_t argc = EVENT_STATES_PARAMS; + napi_value argv[EVENT_STATES_PARAMS] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc == EVENT_STATES_MIN_PARAMS || argc == EVENT_STATES_PARAMS, + "Invalid number of parameters"); + + // argv[0] : beginTime + if ((params.errorCode == ERR_OK) + && ((BundleStateCommon::GetInt64NumberValue(env, argv[0], params.beginTime) == nullptr) + || (params.beginTime < TIME_NUMBER_MIN))) { + BUNDLE_ACTIVE_LOGE("ParseEventStatesParameters failed, beginTime is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; + } + + // argv[1] : endTime + if ((params.errorCode == ERR_OK) + && ((BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr) + || (params.endTime < TIME_NUMBER_MIN))) { + BUNDLE_ACTIVE_LOGE("ParseEventStatesParameters failed, endTime is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) && (params.endTime <= params.beginTime)) { + BUNDLE_ACTIVE_LOGE("ParseEventStatesParameters endTime(%{public}lld) <= beginTime(%{public}lld)", + (long long)params.endTime, (long long)params.beginTime); + params.errorCode = ERR_USAGE_STATS_TIME_INTERVAL; + } + + // argv[SECOND_ARG]: callback + if (argc == EVENT_STATES_PARAMS) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[SECOND_ARG], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "ParseEventStatesParameters invalid parameter type. " + "Function expected."); + napi_create_reference(env, argv[SECOND_ARG], 1, ¶ms.callback); + } + return BundleStateCommon::NapiGetNull(env); +} + +napi_value QueryBundleActiveEventStates(napi_env env, napi_callback_info info) +{ + EventStatesParamsInfo params; + ParseEventStatesParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + napi_value promise = nullptr; + AsyncCallbackInfoEventStats *asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfoEventStats(env); + std::unique_ptr callbackPtr = + BundleStateCommon::HandleEventStatsInfo(asyncCallbackInfo, params); + if (!callbackPtr) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, "QueryBundleActiveEventStates", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data; + if (asyncCallbackInfo != nullptr) { + asyncCallbackInfo->errorCode = BundleActiveClient::GetInstance() + .QueryEventStats(asyncCallbackInfo->beginTime, + asyncCallbackInfo->endTime, asyncCallbackInfo->eventStats); + } else { + BUNDLE_ACTIVE_LOGE("QueryBundleActiveEventStates, asyncCallbackInfo == nullptr"); + } + }, + [](napi_env env, napi_status status, void *data) { + AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data; + if (asyncCallbackInfo != nullptr) { + napi_value result = nullptr; + napi_create_array(env, &result); + BundleStateCommon::GetBundleActiveEventStatsForResult(env, asyncCallbackInfo->eventStats, result); + BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); + } + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); + if (callbackPtr->isCallback) { + callbackPtr.release(); + return BundleStateCommon::NapiGetNull(env); + } else { + callbackPtr.release(); + return promise; + } +} + +napi_value QueryAppNotificationNumber(napi_env env, napi_callback_info info) +{ + EventStatesParamsInfo params; + ParseEventStatesParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + napi_value promise = nullptr; + AsyncCallbackInfoEventStats *asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfoEventStats(env); + std::unique_ptr callbackPtr = + BundleStateCommon::HandleEventStatsInfo(asyncCallbackInfo, params); + if (!callbackPtr) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, "QueryAppNotificationNumber", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data; + if (asyncCallbackInfo != nullptr) { + asyncCallbackInfo->errorCode = BundleActiveClient::GetInstance() + .QueryAppNotificationNumber(asyncCallbackInfo->beginTime, + asyncCallbackInfo->endTime, asyncCallbackInfo->eventStats); + } else { + BUNDLE_ACTIVE_LOGE("QueryAppNotificationNumber, asyncCallbackInfo == nullptr"); + } + }, + [](napi_env env, napi_status status, void *data) { + AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data; + if (asyncCallbackInfo != nullptr) { + napi_value result = nullptr; + napi_create_array(env, &result); + BundleStateCommon::GetBundleActiveNotificationNumberForResult(env, + asyncCallbackInfo->eventStats, result); + BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); + } + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); + if (callbackPtr->isCallback) { + callbackPtr.release(); + return BundleStateCommon::NapiGetNull(env); + } else { + callbackPtr.release(); + return promise; + } +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index 3e60e1c5a45a18df265baf8e351adb3bfdd48302..872b5e4eeef7ab3debbae8bb1a52c847d8d03645 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -19,6 +19,7 @@ #include "ibundle_active_service.h" #include "bundle_active_package_stats.h" #include "bundle_active_event.h" +#include "bundle_active_event_stats.h" #include "bundle_active_package_stats.h" #include "bundle_active_module_record.h" @@ -80,11 +81,28 @@ public: /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, - * if other SAs call this API, they should explicit define userId + * if other SAs call this API, they should explicit define userId. * return: errorcode. */ int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId = -1); /* + * function: QueryEventStats, query all from event stats in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId = -1); + + /* + * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId = -1); + /* * function: GetInstance, get instance of client. * return: object of BundleActiveClient. */ diff --git a/interfaces/innerkits/include/bundle_active_proxy.h b/interfaces/innerkits/include/bundle_active_proxy.h index 50db119b8562420253f222480a039971aa6cc1ff..10a32290335b59291e88a775bf5a33c53076ba7e 100644 --- a/interfaces/innerkits/include/bundle_active_proxy.h +++ b/interfaces/innerkits/include/bundle_active_proxy.h @@ -18,6 +18,7 @@ #include "ibundle_active_service.h" #include "bundle_active_event.h" +#include "bundle_active_event_stats.h" #include "bundle_active_package_stats.h" #include "bundle_active_package_stats.h" #include "bundle_active_module_record.h" @@ -78,12 +79,28 @@ public: /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, - * if other SAs call this API, they should explicit define userId + * if other SAs call this API, they should explicit define userId. * return: errorcode. */ int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId = -1) override; /* + * function: QueryEventStats, query all from event stats in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) override; + /* + * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) override; + /* * function: BundleActiveProxy, default constructor. * parameters: impl */ @@ -96,6 +113,8 @@ public: private: static inline BrokerDelegator delegator_; + int32_t IPCCommunication(int64_t beginTime, int64_t endTime, std::vector& eventStats, + int32_t userId, int32_t communicationFlag); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index ae9f26322e15ab40394d62a5db1d5eed1c763af5..beddc8c82514501ad451151e05c4676aa3e52c0f 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -132,6 +132,24 @@ int32_t BundleActiveClient::QueryFormStatistics(int32_t maxNum, std::vectorQueryFormStatistics(maxNum, results, userId); } +int32_t BundleActiveClient::QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + if (!GetBundleActiveProxy()) { + return -1; + } + return bundleActiveProxy_->QueryEventStats(beginTime, endTime, eventStats, userId); +} + +int32_t BundleActiveClient::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + if (!GetBundleActiveProxy()) { + return -1; + } + return bundleActiveProxy_->QueryAppNotificationNumber(beginTime, endTime, eventStats, userId); +} + int32_t BundleActiveClient::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) { int32_t ret = -1; diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index 43cfd63e8681295e3d7a08d577c8521bcda09e03..d811a9a6355270f00cfa39cadcfeb01942c6dedc 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -242,6 +242,54 @@ int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector& eventStats, int32_t userId) +{ + int32_t errCode = IPCCommunication(beginTime, endTime, eventStats, userId, QUERY_EVENT_STATS); + for (const auto& singleEvent : eventStats) { + BUNDLE_ACTIVE_LOGI("name is %{public}s, eventId is %{public}d, count is %{public}d", + singleEvent.name_.c_str(), singleEvent.eventId_, singleEvent.count_); + } + return errCode; +} + +int32_t BundleActiveProxy::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + int32_t errCode = IPCCommunication(beginTime, endTime, eventStats, userId, QUERY_APP_NOTIFICATION_NUMBER); + for (const auto& singleEvent : eventStats) { + BUNDLE_ACTIVE_LOGI("name is %{public}s, eventId is %{public}d, count is %{public}d", + singleEvent.name_.c_str(), singleEvent.eventId_, singleEvent.count_); + } + return errCode; +} + +int32_t BundleActiveProxy::IPCCommunication(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId, int32_t communicationFlag) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return -1; + } + data.WriteInt64(beginTime); + data.WriteInt64(endTime); + data.WriteInt32(userId); + Remote() -> SendRequest(communicationFlag, data, reply, option); + int32_t errCode = reply.ReadInt32(); + int32_t size = reply.ReadInt32(); + std::shared_ptr tmp; + for (int32_t i = 0; i < size; i++) { + tmp = tmp->UnMarshalling(reply); + if (!tmp) { + continue; + } + eventStats.emplace_back(*tmp); + } + return errCode; +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index 100791b48bf5abf63c747a480b2f3a3fbbeb150b..28ce96454eab96b950a304c3b1d360d5d2d82336 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -174,6 +174,27 @@ declare namespace bundleState { formRecords: Array; } + /** + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + */ + interface BundleActiveEventState { + /** + * the bundle name or system event name. + */ + name?: string; + + /** + * the event id. + */ + eventId: number; + + /** + * the the event occurrence number. + */ + count: number; + } + /** * @since 7 * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App @@ -343,6 +364,34 @@ declare namespace bundleState { */ function getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback>): void; function getRecentlyUsedModules(maxNum?: number): Promise>; + + /** + * Queries system event states data within a specified period identified by the start and end time. + * + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @permission ohos.permission.BUNDLE_ACTIVE_INFO + * @systemapi Hide this for inner system use. + * @param begin Indicates the start time of the query period, in milliseconds. + * @param end Indicates the end time of the query period, in milliseconds. + * @return Returns the {@link BundleActiveEventState} object Array containing the event states data. + */ + function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback>): void; + function queryBundleActiveEventStates(begin: number, end: number): Promise>; + + /** + * Queries app notification number within a specified period identified by the start and end time. + * + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @permission ohos.permission.BUNDLE_ACTIVE_INFO + * @systemapi Hide this for inner system use. + * @param begin Indicates the start time of the query period, in milliseconds. + * @param end Indicates the end time of the query period, in milliseconds. + * @return Returns the {@link BundleActiveEventState} object Array containing the event states data. + */ + function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback>): void; + function queryAppNotificationNumber(begin: number, end: number): Promise>; } export default bundleState; diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h index f2a172aa2f08fce36dc6f07cab6252226d040f19..a0f551216710e83afa8c18789fff4c379132f29e 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h @@ -50,6 +50,12 @@ public: static void GetBundleStateInfoByIntervalForResult( napi_env env, const std::vector &packageStats, napi_value result); + static void GetBundleActiveEventStatsForResult(napi_env env, + const std::vector &eventStats, napi_value result); + + static void GetBundleActiveNotificationNumberForResult(napi_env env, + const std::vector &eventStats, napi_value result); + static void GetBundleStateInfoForResult(napi_env env, const std::shared_ptr> &packageStats, napi_value result); @@ -74,6 +80,9 @@ public: int64_t &beginTime, int64_t &endTime, int32_t &errCode); static void MergePackageStats(BundleActivePackageStats &left, const BundleActivePackageStats &right); + + static std::unique_ptr HandleEventStatsInfo( + AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo ¶ms); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h index b27b51d8a639e7ccc8e6501b1caca69cced3f1f1..f882e04bfc83504a288eecee559cc1745747446b 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h @@ -23,6 +23,7 @@ #include "napi/native_node_api.h" #include "bundle_active_event.h" +#include "bundle_active_event_stats.h" #include "bundle_active_package_stats.h" namespace OHOS { @@ -80,6 +81,13 @@ struct AsyncCallbackInfoAppUsageByInterval : public AsyncWorkData { std::vector packageStats; }; +struct AsyncCallbackInfoEventStats : public AsyncWorkData { + explicit AsyncCallbackInfoEventStats(napi_env env) : AsyncWorkData(env) {} + int64_t beginTime = -1; + int64_t endTime = -1; + std::vector eventStats; +}; + struct AsyncCallbackInfoAppUsage : public AsyncWorkData { explicit AsyncCallbackInfoAppUsage(napi_env env) : AsyncWorkData(env) {} int64_t beginTime = -1; @@ -131,6 +139,13 @@ struct ModuleRecordParamsInfo { napi_ref callback = nullptr; int32_t errorCode = 0; }; + +struct EventStatesParamsInfo { + int64_t beginTime = -1; + int64_t endTime = -1; + napi_ref callback = nullptr; + int32_t errorCode = 0; +}; } // namespace DeviceUsageStats } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_DATA_H diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h index 3576ab1afd0f8e4c371058740de79e2157ce5509..d079997d14c7b217ecb28e3133ddec85566d8f5b 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h @@ -50,6 +50,8 @@ enum : int32_t { ERR_USAGE_STATS_INTERVAL_TYPE, ERR_USAGE_STATS_INTERVAL_NUMBER, ERR_MODULE_STATS_MAXNUM_INVALID, + ERR_EVENT_TYPE, + ERR_EVENT_TYPE_NUMBER, }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_query.h b/interfaces/kits/bundlestats/napi/include/bundle_state_query.h index 0a0492aaa541cfe9d4e674c5668a6ad8513e28e5..0d36f55a17dea05af263657f84c68946d8c6bf80 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_query.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_query.h @@ -28,6 +28,8 @@ namespace DeviceUsageStats { napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info); napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info); napi_value GetModuleUsageRecord(napi_env env, napi_callback_info info); + napi_value QueryBundleActiveEventStates(napi_env env, napi_callback_info info); + napi_value QueryAppNotificationNumber(napi_env env, napi_callback_info info); } // namespace DeviceUsageStats } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_QUERY_H diff --git a/services/common/include/bundle_active_common_event_subscriber.h b/services/common/include/bundle_active_common_event_subscriber.h index 5ffc4030da50b5a03a1a85fb6c7a1a3c73641131..28bfe69947046c906c2a4fd2b53ba9d5d7592c72 100644 --- a/services/common/include/bundle_active_common_event_subscriber.h +++ b/services/common/include/bundle_active_common_event_subscriber.h @@ -46,6 +46,7 @@ public: bundleActiveReportHandler_(bundleActiveReportHandler) {} ~BundleActiveCommonEventSubscriber() = default; void OnReceiveEvent(const CommonEventData &data) override; + void HandleLockEvent(const std::string& action); private: std::mutex mutex_; diff --git a/services/common/include/bundle_active_constant.h b/services/common/include/bundle_active_constant.h index 82bf37e637b0716c61507e2978d5664c2ad387d3..8cd7ba58b7f79ca8338b827ae4a8ed966a374150 100644 --- a/services/common/include/bundle_active_constant.h +++ b/services/common/include/bundle_active_constant.h @@ -69,6 +69,8 @@ const int32_t FORM_DIMENSION_COLUMN_INDEX = 4; const int32_t FORM_ID_COLUMN_INDEX = 5; const int32_t FORM_COUNT_COLUMN_INDEX = 6; const int32_t FORM_LAST_TIME_COLUMN_INDEX = 7; +const int32_t QUERY_CONDITION_VALID = 0; +const int32_t QUERY_CONDITION_INVALID = -1; const int64_t TWO_SECONDS = 2 * 1000LL; const int64_t THIRTY_MINUTE = 30 * 60 * 1000LL; const int64_t SIX_DAY_IN_MILLIS_MAX_DEBUG = 6 * 1 * 10 * 60 * 1000LL; @@ -125,8 +127,14 @@ const std::string BUNDLE_ACTIVE_DATABASE_DIR = "/data/service/el1/public/bundle_ const std::string BUNDLE_ACTIVE_VERSION_FILE = "/version"; const std::string DATABASE_FILE_TABLE_NAME = "table"; const std::string SQLITE_MASTER_NAME = "name"; +const std::string COMMON_EVENT_UNLOCK_SCREEN = "common.event.UNLOCK_SCREEN"; +const std::string COMMON_EVENT_LOCK_SCREEN = "common.event.LOCK_SCREEN"; const std::string DATABASE_TYPE[] = {"daily", "weekly", "monthly", "yearly", "event", "usageGroup"}; const std::string SUFFIX_TYPE[] = {".db", ".db-shm", ".db-wal"}; +const std::string OPERATION_SYSTEM_LOCK = "SYSTEM_LOCK"; +const std::string OPERATION_SYSTEM_UNLOCK = "SYSTEM_UNLOCK"; +const std::string OPERATION_SYSTEM_SLEEP = "SYSTEM_SLEEP"; +const std::string OPERATION_SYSTEM_WAKEUP = "SYSTEM_WAKEUP"; } // namespace DeviceUsageStats } // namespace OHOS #endif // BUNDLE_ACTIVE_CONSTANT_H diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 3c861ce114a3dc465d943d84b8c1a01a188a2cd9..fb933eba0ba5beae6535be2776dcc14b2ddb837e 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -54,7 +54,7 @@ public: * function: ReportEvent, used to report ability fourground/background/destroy event. * parameters: event, userId */ - int32_t ReportEvent(BundleActiveEvent& event, const int32_t userId); + int32_t ReportEvent(BundleActiveEvent& event, int32_t userId); /* * function: ReportEventToAllUserId, report flush to disk, end_of_day event to service. * parameters: event @@ -112,6 +112,10 @@ public: */ void ShutDown(); /* + * function: PreservePowerStateInfo, called when device change power state, preserve power state info. + */ + void PreservePowerStateInfo(const int32_t eventId); + /* * function: QueryPackageStats, query the package stat for calling user. * parameters: userId, intervalType, beginTime, endTime, bundleName * return: vector of BundleActivePackageStats @@ -126,6 +130,23 @@ public: // query the app group for calling app. int32_t QueryPackageGroup(const int32_t userId, const std::string bundleName); int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId); + /* + * function: QueryEventStats, query all from event stats in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId); + + /* + * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId); // get the wall time and check if the wall time is changed. int64_t CheckTimeChangeAndGetWallTime(int32_t userId = 0); // convert event timestamp from boot based time to wall time. @@ -163,6 +184,7 @@ private: void RegisterSubscriber(); std::shared_ptr commonEventSubscriber_; void RestoreAllData(); + void ObtainSystemEventName(BundleActiveEvent& event); bool debugCore_; }; } // namespace DeviceUsageStats diff --git a/services/common/include/bundle_active_log.h b/services/common/include/bundle_active_log.h index 0dae499429053ba09c28100bea212a8274618293..b61c5a6781a87f08066391bd2179d2c471d4c486 100644 --- a/services/common/include/bundle_active_log.h +++ b/services/common/include/bundle_active_log.h @@ -60,7 +60,7 @@ private: static BundleActiveLogLevel logLevel_; }; -#define PRINT_LOG(LEVEL, Level, fmt, ...) \ +#define BUNDLE_ACTIVE_PRINT_LOG(LEVEL, Level, fmt, ...) \ if (BundleActiveLog::JudgeValidLevel(BundleActiveLogLevel::LEVEL)) \ OHOS::HiviewDFX::HiLog::Level(BUNDLE_ACTIVE_LOG_LABEL, \ "[%{public}s(%{public}s):%{public}d] " fmt, \ @@ -69,11 +69,11 @@ private: __LINE__, \ ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGD(fmt, ...) PRINT_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGI(fmt, ...) PRINT_LOG(INFO, Info, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGW(fmt, ...) PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGE(fmt, ...) PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGF(fmt, ...) PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGD(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGI(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(INFO, Info, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGW(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGE(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGF(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) } // namespace DeviceUsageStats } // namespace OHOS #endif // BUNDLE_ACTIVE_LOG_H diff --git a/services/common/include/bundle_active_power_state_callback_proxy.h b/services/common/include/bundle_active_power_state_callback_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..c0a158a610d66fd98b7366a661a0cf851d5b4a8d --- /dev/null +++ b/services/common/include/bundle_active_power_state_callback_proxy.h @@ -0,0 +1,39 @@ +/* + * 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 BUNDLE_ACTIVE_POWER_STATE_CALLBACK_PROXY_H +#define BUNDLE_ACTIVE_POWER_STATE_CALLBACK_PROXY_H + +#include "ibundle_active_service.h" +#include "ipower_state_callback.h" +#include "nocopyable.h" + +namespace OHOS { +namespace DeviceUsageStats { +using IPowerStateCallback = OHOS::PowerMgr::IPowerStateCallback; +class BundleActivePowerStateCallbackProxy : public IRemoteProxy { +public: + explicit BundleActivePowerStateCallbackProxy(const sptr& impl) + : IRemoteProxy(impl) {} + ~BundleActivePowerStateCallbackProxy() = default; + DISALLOW_COPY_AND_MOVE(BundleActivePowerStateCallbackProxy); + void OnPowerStateChanged(PowerMgr::PowerState state) override; +private: + static inline BrokerDelegator delegator_; +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_POWER_STATE_CALLBACK_PROXY_H + diff --git a/services/common/include/bundle_active_power_state_callback_service.h b/services/common/include/bundle_active_power_state_callback_service.h new file mode 100644 index 0000000000000000000000000000000000000000..7cca1ea5e8f845d3d0cf5e4c3eceae27bef49c54 --- /dev/null +++ b/services/common/include/bundle_active_power_state_callback_service.h @@ -0,0 +1,36 @@ + /* + * 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 BUNDLE_ACTIVE_POWER_STATE_CALLBACK_SERVICE_H +#define BUNDLE_ACTIVE_POWER_STATE_CALLBACK_SERVICE_H + +#include "bundle_active_power_state_callback_stub.h" +#include "bundle_active_core.h" + +namespace OHOS { +namespace DeviceUsageStats { +using OHOS::PowerMgr::PowerState; +class BundleActivePowerStateCallbackService : public BundleActivePowerStateCallbackStub { +public: + BundleActivePowerStateCallbackService(std::shared_ptr bundleActiveCore); + virtual ~BundleActivePowerStateCallbackService() {} + void OnPowerStateChanged(PowerState state) override; +private: + std::shared_ptr bundleActiveCore_; +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_POWER_STATE_CALLBACK_SERVICE_H + diff --git a/services/common/include/bundle_active_power_state_callback_stub.h b/services/common/include/bundle_active_power_state_callback_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..93ec067c8636cb01992f33b91860898e2e610544 --- /dev/null +++ b/services/common/include/bundle_active_power_state_callback_stub.h @@ -0,0 +1,40 @@ +/* + * 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 BUNDLE_ACTIVE_POWER_STATE_CALLBACK_STUB_H +#define BUNDLE_ACTIVE_POWER_STATE_CALLBACK_STUB_H + +#include "ipower_state_callback.h" +#include "nocopyable.h" + +#include "ibundle_active_service.h" + +namespace OHOS { +namespace DeviceUsageStats { +using IPowerStateCallback = OHOS::PowerMgr::IPowerStateCallback; +using PowerState = OHOS::PowerMgr::PowerState; +class BundleActivePowerStateCallbackStub : public IRemoteStub { +public: + DISALLOW_COPY_AND_MOVE(BundleActivePowerStateCallbackStub); + BundleActivePowerStateCallbackStub() = default; + virtual ~BundleActivePowerStateCallbackStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, MessageOption &option) override; +private: + void PowerStateStub(PowerState state); +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_POWER_STATE_CALLBACK_STUB_H + diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index e8921a47ed0ed02e28fe2e4b927f54cd366407a9..d8000efc4ae8d691da1322579c92dc7286804428 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -24,6 +24,7 @@ #include "bundle_active_core.h" #include "bundle_active_report_handler.h" #include "bundle_active_shutdown_callback_service.h" +#include "bundle_active_power_state_callback_service.h" #include "bundle_active_app_state_observer.h" #include "bundle_active_continuous_task_observer.h" #include "bundle_active_account_helper.h" @@ -35,7 +36,6 @@ class BundleActiveService : public SystemAbility, public BundleActiveStub, DISALLOW_COPY_AND_MOVE(BundleActiveService); DECLARE_SYSTEM_ABILITY(BundleActiveService); DECLARE_DELAYED_SINGLETON(BundleActiveService); - public: using IBundleMgr = OHOS::AppExecFwk::IBundleMgr; using BundleInfo = OHOS::AppExecFwk::BundleInfo; @@ -97,12 +97,28 @@ public: /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, - * if other SAs call this API, they should explicit define userId + * if other SAs call this API, they should explicit define userId. * return: errorcode. */ int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId = -1) override; /* + * function: QueryEventStats, query all from event stats in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) override; + /* + * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) override; + /* * function: BundleActiveService, default constructor. * parameters: systemAbilityId, runOnCreate */ @@ -123,6 +139,7 @@ private: std::shared_ptr continuousTaskObserver_; sptr sptrBundleMgr_; sptr shutdownCallback_; + sptr powerStateCallback_; std::shared_ptr runner_; std::shared_ptr handler_; bool ready_ {false}; diff --git a/services/common/include/bundle_active_usage_database.h b/services/common/include/bundle_active_usage_database.h index f26373cbbc4d5b873831444f2c66e2c494dacae3..23cfe58259279a52b7c8054178954c5fa506deb3 100644 --- a/services/common/include/bundle_active_usage_database.h +++ b/services/common/include/bundle_active_usage_database.h @@ -67,6 +67,10 @@ public: std::shared_ptr>& moduleRecords); void LoadFormData(const int32_t userId, std::map>& moduleRecords); + void QueryEventStats(int32_t eventId, int64_t beginTime, int64_t endTime, + std::map& eventStats, int32_t userId); + void QueryAppNotificationNumber(int32_t eventId, int64_t beginTime, int64_t endTime, + std::map& notificationEventStats, int32_t userId); private: void CheckDatabaseVersion(); @@ -102,6 +106,8 @@ private: void UpdateFormData(const int32_t userId, const std::string bundleName, const std::string moduleName, const BundleActiveFormRecord& formRecord, std::shared_ptr rdbStore); + int32_t JudgeQueryCondition(const int64_t beginTime, const int64_t endTime, const int64_t eventTableTime); + std::string GetSystemEventName(const int32_t userId); private: std::vector databaseFiles_; diff --git a/services/common/include/ibundle_active_service.h b/services/common/include/ibundle_active_service.h index 63d332c2bac2a7d65d779fb9dccf9ecdce54b91f..8d8b70fc3d967b1c4bb6df4be6dc9187d3588be5 100644 --- a/services/common/include/ibundle_active_service.h +++ b/services/common/include/ibundle_active_service.h @@ -40,6 +40,7 @@ namespace OHOS { namespace DeviceUsageStats { class BundleActivePackageStats; class BundleActiveEvent; +class BundleActiveEventStats; class BundleActiveModuleRecord; class IBundleActiveService : public IRemoteBroker { @@ -99,12 +100,27 @@ public: /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, - * if other SAs call this API, they should explicit define userId + * if other SAs call this API, they should explicit define userId. * return: errorcode. */ virtual int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId) = 0; - + /* + * function: QueryEventStats, query all from event stats in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + virtual int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) = 0; + /* + * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + virtual int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) = 0; public: enum { REPORT_EVENT = 1, @@ -115,7 +131,9 @@ public: QUERY_CURRENT_EVENTS = 6, QUERY_BUNDLE_GROUP = 7, SET_BUNDLE_GROUP = 8, - QUERY_FORM_STATS = 9 + QUERY_FORM_STATS = 9, + QUERY_EVENT_STATS = 10, + QUERY_APP_NOTIFICATION_NUMBER = 11 }; public: DECLARE_INTERFACE_DESCRIPTOR(u"Resourceschedule.IBundleActiveService"); diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 15dcdc5e2513361564e75f65eea31a54b1e2f95a..600a3747045f1f4d09fdf9eebbb3dcfc134b9d67 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -17,6 +17,7 @@ #include "time_service_client.h" #include "bundle_active_event.h" +#include "bundle_active_event_stats.h" #include "bundle_active_report_handler.h" #include "bundle_active_group_common.h" #include "bundle_active_constant.h" @@ -111,9 +112,32 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da handlerobjToPtr); bundleActiveReportHandler_.lock()->SendEvent(event); } + } else if (action == COMMON_EVENT_UNLOCK_SCREEN || action == COMMON_EVENT_LOCK_SCREEN) { + HandleLockEvent(action); } } +void BundleActiveCommonEventSubscriber::HandleLockEvent(const std::string& action) +{ + if (bundleActiveReportHandler_.expired()) { + return; + } + BundleActiveReportHandlerObject tmpHandlerObject(-1, ""); + BundleActiveEvent newEvent; + tmpHandlerObject.event_ = newEvent; + if (action == COMMON_EVENT_UNLOCK_SCREEN) { + tmpHandlerObject.event_.eventId_ = BundleActiveEvent::SYSTEM_UNLOCK; + } else { + tmpHandlerObject.event_.eventId_ = BundleActiveEvent::SYSTEM_LOCK; + } + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); + auto handlerobjToPtr = std::make_shared(tmpHandlerObject); + auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_REPORT_EVENT, + handlerobjToPtr); + bundleActiveReportHandler_.lock()->SendEvent(event); +} + void BundleActiveCore::RegisterSubscriber() { MatchingSkills matchingSkills; @@ -124,6 +148,8 @@ void BundleActiveCore::RegisterSubscriber() matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); + matchingSkills.AddEvent(COMMON_EVENT_UNLOCK_SCREEN); + matchingSkills.AddEvent(COMMON_EVENT_LOCK_SCREEN); CommonEventSubscribeInfo subscriberInfo(matchingSkills); commonEventSubscriber_ = std::make_shared(subscriberInfo, bundleGroupController_, handler_); @@ -293,6 +319,28 @@ void BundleActiveCore::RestoreToDatabaseLocked(const int32_t userId) } } +void BundleActiveCore::PreservePowerStateInfo(const int32_t eventId) +{ + if (!handler_.expired()) { + int32_t userId = -1; + std::vector currentActiveUser; + BundleActiveCore::GetAllActiveUser(currentActiveUser); + if (currentActiveUser.size() == 1) { + userId = currentActiveUser.front(); + } + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); + BundleActiveEvent newEvent; + tmpHandlerObject.event_ = newEvent; + tmpHandlerObject.event_.eventId_ = eventId; + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); + handler_.lock()->SendEvent(event); + } +} + void BundleActiveCore::ShutDown() { std::lock_guard lock(mutex_); @@ -410,11 +458,19 @@ void BundleActiveCore::OnUserSwitched(const int32_t userId) OnStatsChanged(userId); } -int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int32_t userId) +int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId) { BUNDLE_ACTIVE_LOGI("FLUSH interval is %{public}lld, debug is %{public}d", (long long)flushInterval_, debugCore_); event.PrintEvent(debugCore_); std::lock_guard lock(mutex_); + if (event.eventId_ == BundleActiveEvent::SYSTEM_LOCK || event.eventId_ == BundleActiveEvent::SYSTEM_UNLOCK) { + std::vector currentActiveUser; + BundleActiveCore::GetAllActiveUser(currentActiveUser); + if (currentActiveUser.size() == 1) { + userId = currentActiveUser.front(); + } + } + ObtainSystemEventName(event); if (userId == 0 || userId == -1) { return -1; } @@ -422,7 +478,6 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int32_t us currentUsedUser_ = userId; BUNDLE_ACTIVE_LOGI("last used id change to %{public}d", currentUsedUser_); } - sptr timer = MiscServices::TimeServiceClient::GetInstance(); int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); if (event.bundleName_ == LAUNCHER_BUNDLE_NAME) { @@ -430,7 +485,6 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int32_t us bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId); return 0; } - BUNDLE_ACTIVE_LOGI("report event called, bundle name %{public}s time %{public}lld userId %{public}d, " "eventid %{public}d, in lock range", event.bundleName_.c_str(), (long long)event.timeStamp_, userId, event.eventId_); @@ -455,6 +509,26 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int32_t us return 0; } +void BundleActiveCore::ObtainSystemEventName(BundleActiveEvent& event) +{ + switch (event.eventId_) { + case BundleActiveEvent::SYSTEM_LOCK: + event.bundleName_ = OPERATION_SYSTEM_LOCK; + break; + case BundleActiveEvent::SYSTEM_UNLOCK: + event.bundleName_ = OPERATION_SYSTEM_UNLOCK; + break; + case BundleActiveEvent::SYSTEM_SLEEP: + event.bundleName_ = OPERATION_SYSTEM_SLEEP; + break; + case BundleActiveEvent::SYSTEM_WAKEUP: + event.bundleName_ = OPERATION_SYSTEM_WAKEUP; + break; + default: + break; + } +} + int32_t BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) { BUNDLE_ACTIVE_LOGI("ReportEventToAllUserId called"); @@ -543,6 +617,38 @@ int32_t BundleActiveCore::QueryFormStatistics(int32_t maxNum, std::vector& eventStats, int32_t userId) +{ + std::lock_guard lock(mutex_); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); + if (timeNow == -1) { + return -1; + } + std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_); + if (!service) { + return -1; + } + int32_t errCode = service->QueryEventStats(beginTime, endTime, eventStats, userId); + return errCode; +} + +int32_t BundleActiveCore::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + std::lock_guard lock(mutex_); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); + if (timeNow == -1) { + return -1; + } + std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_); + if (!service) { + return -1; + } + int32_t errCode = service->QueryAppNotificationNumber(beginTime, endTime, eventStats, userId); + return errCode; +} + void BundleActiveCore::SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId) { int32_t newReason = GROUP_CONTROL_REASON_FORCED; diff --git a/services/common/src/bundle_active_power_state_callback_proxy.cpp b/services/common/src/bundle_active_power_state_callback_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..356183f8434feb840eb0c85de2d71c407ba0f6c5 --- /dev/null +++ b/services/common/src/bundle_active_power_state_callback_proxy.cpp @@ -0,0 +1,41 @@ +/* + * 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. + */ + +#include "bundle_active_power_state_callback_proxy.h" +#include "power_state_machine_info.h" + +namespace OHOS { +namespace DeviceUsageStats { +void BundleActivePowerStateCallbackProxy::OnPowerStateChanged(PowerMgr::PowerState state) +{ + sptr remote = Remote(); + if (remote == nullptr) { + return; + } + MessageParcel data; + data.WriteInt32((int32_t)state); + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(BundleActivePowerStateCallbackProxy::GetDescriptor())) { + return; + } + int32_t ret = remote->SendRequest(IPowerStateCallback::POWER_STATE_CHANGED, data, reply, option); + if (ret != ERR_OK) { + BUNDLE_ACTIVE_LOGE("BundleActivePowerStateCallbackProxy::PowerStateCallback failed!"); + } +} +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_power_state_callback_service.cpp b/services/common/src/bundle_active_power_state_callback_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcbdb3709b13cbf0c366081c36f5c90e14f6840a --- /dev/null +++ b/services/common/src/bundle_active_power_state_callback_service.cpp @@ -0,0 +1,45 @@ +/* + * 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. + */ + +#include "bundle_active_power_state_callback_service.h" +#include "power_state_machine_info.h" + +namespace OHOS { +namespace DeviceUsageStats { +using OHOS::PowerMgr::PowerState; +BundleActivePowerStateCallbackService::BundleActivePowerStateCallbackService( + std::shared_ptr bundleActiveCore) +{ + if (bundleActiveCore != nullptr) { + bundleActiveCore_ = bundleActiveCore; + } +} + +void BundleActivePowerStateCallbackService::OnPowerStateChanged(PowerState state) +{ + int32_t eventId; + BUNDLE_ACTIVE_LOGD("BundleActDvePowerStateCallbackService::OnPowerStateChanged power state is %{public}u", state); + if (state == PowerState::AWAKE) { + eventId = BundleActiveEvent::SYSTEM_WAKEUP; + } else if (state == PowerState::SLEEP) { + eventId = BundleActiveEvent::SYSTEM_SLEEP; + } else { + return; + } + bundleActiveCore_->PreservePowerStateInfo(eventId); +} +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_power_state_callback_stub.cpp b/services/common/src/bundle_active_power_state_callback_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ec2ff17d6e6023fdb831ce91634e797685f33a2 --- /dev/null +++ b/services/common/src/bundle_active_power_state_callback_stub.cpp @@ -0,0 +1,47 @@ +/* + * 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. + */ + +#include "bundle_active_power_state_callback_stub.h" +#include "bundle_active_event.h" + +namespace OHOS { +namespace DeviceUsageStats { +int32_t BundleActivePowerStateCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, + MessageOption &option) +{ + std::u16string descriptor = BundleActivePowerStateCallbackStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + PowerMgr::PowerState state = (PowerMgr::PowerState)data.ReadInt32(); + if (descriptor != remoteDescriptor) { + BUNDLE_ACTIVE_LOGE("BundleActivePowerStateCallbackStub::OnRemoteRequest cannot get power mgr service"); + return -1; + } + switch (code) { + case IPowerStateCallback::POWER_STATE_CHANGED: { + PowerStateStub(state); + return ERR_OK; + } + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } +} + +void BundleActivePowerStateCallbackStub::PowerStateStub(PowerMgr::PowerState state) +{ + OnPowerStateChanged(state); +} +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index d21188902487a5e8348f8fd939bb14852909e792..c4c691dd34a499538d46a380284ae7e794d14b5e 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -131,10 +131,14 @@ void BundleActiveService::InitService() return; } shutdownCallback_ = new (std::nothrow) BundleActiveShutdownCallbackService(bundleActiveCore_); + powerStateCallback_ = new (std::nothrow) BundleActivePowerStateCallbackService(bundleActiveCore_); auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); if (shutdownCallback_) { powerManagerClient.RegisterShutdownCallback(shutdownCallback_); } + if (powerStateCallback_) { + powerManagerClient.RegisterPowerStateCallback(powerStateCallback_); + } InitAppStateSubscriber(reportHandler_); InitContinuousSubscriber(reportHandler_); bundleActiveCore_->InitBundleGroupController(); @@ -205,6 +209,7 @@ void BundleActiveService::OnStop() if (shutdownCallback_ != nullptr) { auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); powerManagerClient.UnRegisterShutdownCallback(shutdownCallback_); + powerManagerClient.UnRegisterPowerStateCallback(powerStateCallback_); return; } BUNDLE_ACTIVE_LOGI("[Server] OnStop"); @@ -506,6 +511,60 @@ int32_t BundleActiveService::QueryFormStatistics(int32_t maxNum, std::vector& eventStats, int32_t userId) +{ + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + BUNDLE_ACTIVE_LOGI("QueryEventStats UID is %{public}d", callingUid); + // get userid when userId is -1 + int32_t errCode = 0; + if (userId == -1) { + OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); + if (ret != ERR_OK) { + errCode = -1; + return errCode; + } + } + if (userId != -1) { + BUNDLE_ACTIVE_LOGI("QueryEventStats userid is %{public}d", userId); + AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + if ((CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode)) || + (AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == + AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE)) { + errCode = bundleActiveCore_->QueryEventStats(beginTime, endTime, eventStats, userId); + } + } + BUNDLE_ACTIVE_LOGI("QueryEventStats result size is %{public}zu", eventStats.size()); + return errCode; +} + +int32_t BundleActiveService::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber UID is %{public}d", callingUid); + // get userid when userId is -1 + int32_t errCode = 0; + if (userId == -1) { + OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); + if (ret != ERR_OK) { + errCode = -1; + return errCode; + } + } + if (userId != -1) { + BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber userid is %{public}d", userId); + AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + if ((CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode)) || + (AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == + AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE)) { + errCode = bundleActiveCore_->QueryAppNotificationNumber(beginTime, endTime, eventStats, userId); + } + } + BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber result size is %{public}zu", eventStats.size()); + return errCode; +} + void BundleActiveService::QueryModuleRecordInfos(BundleActiveModuleRecord& moduleRecord) { if (!GetBundleMgrProxy()) { diff --git a/services/common/src/bundle_active_stub.cpp b/services/common/src/bundle_active_stub.cpp index ad5037cd8e4eb7371c9c42f8a929d51185d407fe..7b148788a692b3451497cb473428db9503241195 100644 --- a/services/common/src/bundle_active_stub.cpp +++ b/services/common/src/bundle_active_stub.cpp @@ -16,6 +16,7 @@ #include "bundle_active_stub.h" #include "bundle_active_package_stats.h" #include "bundle_active_event.h" +#include "bundle_active_event_stats.h" #include "bundle_active_module_record.h" namespace OHOS { @@ -142,6 +143,40 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me } return size == 0; } + case QUERY_EVENT_STATS: { + std::vector result; + int64_t beginTime = data.ReadInt64(); + int64_t endTime = data.ReadInt64(); + int32_t userId = data.ReadInt32(); + int32_t errCode = QueryEventStats(beginTime, endTime, result, userId); + int32_t size = static_cast(result.size()); + reply.WriteInt32(errCode); + reply.WriteInt32(size); + for (int32_t i = 0; i < size; i++) { + bool tmp = result[i].Marshalling(reply); + if (!tmp) { + return 1; + } + } + return size == 0; + } + case QUERY_APP_NOTIFICATION_NUMBER: { + std::vector result; + int64_t beginTime = data.ReadInt64(); + int64_t endTime = data.ReadInt64(); + int32_t userId = data.ReadInt32(); + int32_t errCode = QueryAppNotificationNumber(beginTime, endTime, result, userId); + int32_t size = static_cast(result.size()); + reply.WriteInt32(errCode); + reply.WriteInt32(size); + for (int32_t i = 0; i < size; i++) { + bool tmp = result[i].Marshalling(reply); + if (!tmp) { + return 1; + } + } + return size == 0; + } default: return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index 2195f2e220a440c994366841a66c1d19a2536098..aa8118fc619e8da49c68870bd14abed96cfd4a35 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -1297,19 +1297,8 @@ vector BundleActiveUsageDatabase::QueryDatabaseEvents(int64_t { lock_guard lock(databaseMutex_); vector databaseEvents; - if (eventTableName_ == UNKNOWN_TABLE_NAME) { - BUNDLE_ACTIVE_LOGE("eventTable does not exist"); - return databaseEvents; - } - if (endTime <= beginTime) { - BUNDLE_ACTIVE_LOGE("endTime(%{public}lld) <= beginTime(%{public}lld)", - (long long)endTime, (long long)beginTime); - return databaseEvents; - } int64_t eventTableTime = ParseStartTime(eventTableName_); - if (endTime < eventTableTime) { - BUNDLE_ACTIVE_LOGE("endTime(%{public}lld) <= eventTableTime(%{public}lld)", - (long long)endTime, (long long)eventTableTime); + if (JudgeQueryCondition(beginTime, endTime, eventTableTime) == QUERY_CONDITION_INVALID) { return databaseEvents; } vector queryCondition; @@ -1597,6 +1586,131 @@ void BundleActiveUsageDatabase::LoadFormData(const int32_t userId, std::map& eventStats, int32_t userId) +{ + lock_guard lock(databaseMutex_); + int64_t eventTableTime = ParseStartTime(eventTableName_); + if (JudgeQueryCondition(beginTime, endTime, eventTableTime) == QUERY_CONDITION_INVALID) { + return; + } + vector queryCondition; + int64_t diff = beginTime - eventTableTime; + if (diff >= 0) { + queryCondition.push_back(to_string(diff)); + } else { + queryCondition.push_back(to_string(EVENT_TIME_IN_MILLIS_MIN)); + } + queryCondition.push_back(to_string(endTime - eventTableTime)); + queryCondition.push_back(to_string(userId)); + queryCondition.push_back(to_string(eventId)); + string queryEventSql = "select * from " + eventTableName_ + + " where timeStamp >= ? and timeStamp <= ? and userId = ? and eventId = ?"; + unique_ptr bundleActiveResult = QueryStatsInfoByStep(EVENT_DATABASE_INDEX, + queryEventSql, queryCondition); + if (bundleActiveResult == nullptr) { + return; + } + int32_t tableRowNumber; + bundleActiveResult->GetRowCount(tableRowNumber); + if (tableRowNumber == 0) { + return; + } + BundleActiveEventStats event; + event.name_= GetSystemEventName(eventId); + event.count_ = tableRowNumber; + event.eventId_ = eventId; + eventStats.insert(std::pair(event.name_, event)); +} + +std::string BundleActiveUsageDatabase::GetSystemEventName(const int32_t userId) +{ + std::string systemEventName = ""; + switch (userId) { + case BundleActiveEvent::SYSTEM_LOCK: + systemEventName = OPERATION_SYSTEM_LOCK; + break; + case BundleActiveEvent::SYSTEM_UNLOCK: + systemEventName = OPERATION_SYSTEM_UNLOCK; + break; + case BundleActiveEvent::SYSTEM_SLEEP: + systemEventName = OPERATION_SYSTEM_SLEEP; + break; + case BundleActiveEvent::SYSTEM_WAKEUP: + systemEventName = OPERATION_SYSTEM_WAKEUP; + break; + default: + break; + } + return systemEventName; +} + +void BundleActiveUsageDatabase::QueryAppNotificationNumber(int32_t eventId, int64_t beginTime, + int64_t endTime, std::map& notificationEventStats, int32_t userId) +{ + lock_guard lock(databaseMutex_); + int64_t eventTableTime = ParseStartTime(eventTableName_); + if (JudgeQueryCondition(beginTime, endTime, eventTableTime) == QUERY_CONDITION_INVALID) { + return; + } + vector queryCondition; + int64_t diff = beginTime - eventTableTime; + if (diff >= 0) { + queryCondition.push_back(to_string(diff)); + } else { + queryCondition.push_back(to_string(EVENT_TIME_IN_MILLIS_MIN)); + } + queryCondition.push_back(to_string(endTime - eventTableTime)); + queryCondition.push_back(to_string(userId)); + queryCondition.push_back(to_string(eventId)); + string queryEventSql = "select * from " + eventTableName_ + + " where timeStamp >= ? and timeStamp <= ? and userId = ? and eventId = ?"; + unique_ptr bundleActiveResult = QueryStatsInfoByStep(EVENT_DATABASE_INDEX, + queryEventSql, queryCondition); + if (bundleActiveResult == nullptr) { + return; + } + int32_t tableRowNumber; + bundleActiveResult->GetRowCount(tableRowNumber); + if (tableRowNumber == 0) { + return; + } + BundleActiveEventStats event; + std::map::iterator iter; + for (int32_t i = 0; i < tableRowNumber; i++) { + bundleActiveResult->GoToRow(i); + bundleActiveResult->GetString(BUNDLE_NAME_COLUMN_INDEX, event.name_); + bundleActiveResult->GetInt(EVENT_ID_COLUMN_INDEX, event.eventId_); + iter = notificationEventStats.find(event.name_); + if (iter != notificationEventStats.end()) { + iter->second.count_++; + } else { + event.count_ = 1; + notificationEventStats.insert(std::pair(event.name_, event)); + } + } +} + +int32_t BundleActiveUsageDatabase::JudgeQueryCondition(const int64_t beginTime, + const int64_t endTime, const int64_t eventTableTime) +{ + if (eventTableName_ == UNKNOWN_TABLE_NAME) { + BUNDLE_ACTIVE_LOGE("eventTable does not exist"); + return QUERY_CONDITION_INVALID; + } + if (endTime <= beginTime) { + BUNDLE_ACTIVE_LOGE("endTime(%{public}lld) <= beginTime(%{public}lld)", + (long long)endTime, (long long)beginTime); + return QUERY_CONDITION_INVALID; + } + if (endTime < eventTableTime) { + BUNDLE_ACTIVE_LOGE("endTime(%{public}lld) <= eventTableTime(%{public}lld)", + (long long)endTime, (long long)eventTableTime); + return QUERY_CONDITION_INVALID; + } + return QUERY_CONDITION_VALID; +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packageusage/include/bundle_active_event.h b/services/packageusage/include/bundle_active_event.h index 57ce14b3f4bd67edff2c70454bba1585bb6d91ca..963ca49c30023d245c7e0b94b8cb27a1412722a4 100644 --- a/services/packageusage/include/bundle_active_event.h +++ b/services/packageusage/include/bundle_active_event.h @@ -38,11 +38,15 @@ public: static const int32_t FLUSH = 12; static const int32_t SCREEN_INTERACTIVE = 13; static const int32_t SCREEN_NON_INTERACTIVE = 14; - static const int32_t KEYGUARD_SHOWN = 15; - static const int32_t KEYGUARD_HIDDEN = 16; - static const int32_t NOTIFICATION_SEEN = 17; - static const int32_t FORM_IS_CLICKED = 18; - static const int32_t FORM_IS_REMOVED = 19; + static const int32_t FORM_IS_CLICKED = 15; + static const int32_t FORM_IS_REMOVED = 16; + static const int32_t KEYGUARD_SHOWN = 17; + static const int32_t KEYGUARD_HIDDEN = 18; + static const int32_t NOTIFICATION_SEEN = 19; + static const int32_t SYSTEM_LOCK = 20; + static const int32_t SYSTEM_UNLOCK = 21; + static const int32_t SYSTEM_SLEEP = 22; + static const int32_t SYSTEM_WAKEUP = 23; inline static const std::string DEVICE_EVENT_PACKAGE_NAME = "openharmony"; std::string bundleName_; std::string continuousTaskAbilityName_; @@ -71,6 +75,11 @@ public: */ BundleActiveEvent(int32_t eventId, int64_t timeStamp); /* + * function: BundleActiveEvent, constructor using event Id, time stamp. + * parameters: eventId, bundleName. + */ + BundleActiveEvent(const int32_t eventId, const std::string bundleName); + /* * function: BundleActiveEvent, constructor of continuous task event. * parameters: bundleName, continuousTaskAbilityName */ diff --git a/services/packageusage/include/bundle_active_event_stats.h b/services/packageusage/include/bundle_active_event_stats.h index 34ee080bca180e31451e89f6793956531dd94c4d..59360b761b572cb84b8d56535df04df314b340e3 100644 --- a/services/packageusage/include/bundle_active_event_stats.h +++ b/services/packageusage/include/bundle_active_event_stats.h @@ -20,7 +20,7 @@ namespace OHOS { namespace DeviceUsageStats { -class BundleActiveEventStats { +class BundleActiveEventStats : public Parcelable { public: int32_t eventId_; int64_t beginTimeStamp_; @@ -28,6 +28,8 @@ public: int64_t lastEventTime_; int64_t totalTime_; int32_t count_; + std::string name_; + /* * function: BundleActiveEventStats, default constructor. */ @@ -72,6 +74,20 @@ public: * parameters: right */ void add(const BundleActiveEventStats& right); + + /* + * function: Marshalling, mashalling event stats object to parcel. + * parameters: parcel + * return: result of mashalling, true means successful, flase means failed. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /* + * function: UnMarshalling, Unmashalling event stats object from parcel. + * parameters: parcel + * return: point to a BundleActiveEventStats. + */ + std::shared_ptr UnMarshalling(Parcel &parcel); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packageusage/include/bundle_active_user_service.h b/services/packageusage/include/bundle_active_user_service.h index cb56fc9a73fd146c67cf7337f3815f2a28c91759..c412f61a75d8c0620f60f72c5f8ecd3339bb6470 100644 --- a/services/packageusage/include/bundle_active_user_service.h +++ b/services/packageusage/include/bundle_active_user_service.h @@ -71,6 +71,10 @@ public: std::vector QueryEvents(const int64_t beginTime, const int64_t endTime, const int32_t userId, const std::string& bundleName); int32_t QueryFormStatistics(int32_t maxNum, std::vector& results); + int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId); + int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId); void LoadActiveStats(const int64_t timeStamp, const bool& force, const bool& timeChanged); void LoadModuleAndFormStats(); @@ -90,6 +94,10 @@ private: void PrintInMemPackageStats(const int32_t idx, const bool debug); void PrintInMemEventStats(const bool debug); void PrintInMemFormStats(const bool debug, const bool printform); + void GetCachedSystemEvents(std::shared_ptr currentStats, int64_t beginTime, + int64_t endTime, std::map& systemEventStats); + void GetCachedNotificationEvents(std::shared_ptr currentStats, int64_t beginTime, + int64_t endTime, std::map& notificationEventStats); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packageusage/src/bundle_active_event.cpp b/services/packageusage/src/bundle_active_event.cpp index a96c4cf0a6a175d91e61153dfd72091b730c5a3f..c8451b72448e8e3fb4e528d295710300bc0a0d19 100644 --- a/services/packageusage/src/bundle_active_event.cpp +++ b/services/packageusage/src/bundle_active_event.cpp @@ -59,6 +59,20 @@ BundleActiveEvent::BundleActiveEvent(int32_t eventId, int64_t timeStamp) eventId_ = eventId; } +BundleActiveEvent::BundleActiveEvent(const int32_t eventId, const std::string bundleName) +{ + bundleName_ = bundleName; + continuousTaskAbilityName_.clear(); + abilityName_.clear(); + abilityId_.clear(); + moduleName_.clear(); + formName_.clear(); + formDimension_ = 0; + formId_ = 0; + timeStamp_ = 0; + eventId_ = eventId; +} + BundleActiveEvent::BundleActiveEvent(const std::string bundleName, const std::string continuousTaskAbilityName) { bundleName_ = bundleName; diff --git a/services/packageusage/src/bundle_active_event_stats.cpp b/services/packageusage/src/bundle_active_event_stats.cpp index a433446a259532faa74f1c17f4b59d513c14ba30..739019ed9d22f32d952c630ee17ab86310a4932c 100644 --- a/services/packageusage/src/bundle_active_event_stats.cpp +++ b/services/packageusage/src/bundle_active_event_stats.cpp @@ -25,6 +25,7 @@ BundleActiveEventStats::BundleActiveEventStats() lastEventTime_ = 0; totalTime_ = 0; count_ = 0; + name_.clear(); } BundleActiveEventStats::BundleActiveEventStats(const BundleActiveEventStats& orig) @@ -35,6 +36,7 @@ BundleActiveEventStats::BundleActiveEventStats(const BundleActiveEventStats& ori lastEventTime_ = orig.lastEventTime_; totalTime_ = orig.totalTime_; count_ = orig.count_; + name_ = orig.name_; } int32_t BundleActiveEventStats::GetEventId() @@ -81,6 +83,33 @@ void BundleActiveEventStats::add(const BundleActiveEventStats& right) totalTime_ += right.totalTime_; count_ += right.count_; } + +bool BundleActiveEventStats::Marshalling(Parcel &parcel) const +{ + if (parcel.WriteInt32(eventId_) && + parcel.WriteInt64(beginTimeStamp_) && + parcel.WriteInt64(endTimeStamp_) && + parcel.WriteInt64(lastEventTime_) && + parcel.WriteInt64(totalTime_) && + parcel.WriteInt32(count_) && + parcel.WriteString(name_)) { + return true; + } + return false; +} + +std::shared_ptr BundleActiveEventStats::UnMarshalling(Parcel &parcel) +{ + std::shared_ptr result = std::make_shared(); + result->eventId_ = parcel.ReadInt32(); + result->beginTimeStamp_ = parcel.ReadInt64(); + result->endTimeStamp_ = parcel.ReadInt64(); + result->lastEventTime_ = parcel.ReadInt64(); + result->totalTime_ = parcel.ReadInt64(); + result->count_ = parcel.ReadInt32(); + result->name_ = parcel.ReadString(); + return result; +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index c79f1d62e4a6a98de00d1354296fd4499ef8702b..9084d788f0466bfd01b78f3d8796b361a116ee0e 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -410,6 +410,117 @@ int32_t BundleActiveUserService::QueryFormStatistics(int32_t maxNum, std::vector return 0; } +int32_t BundleActiveUserService::QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + BUNDLE_ACTIVE_LOGI("QueryEventStats called"); + auto currentStats = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]; + if (currentStats == nullptr) { + BUNDLE_ACTIVE_LOGE("current interval stat is null!"); + return BUNDLE_ACTIVE_FAIL; + } + if (beginTime >= currentStats->endTime_) { + return BUNDLE_ACTIVE_FAIL; + } + std::map systemEventStats; + database_.QueryEventStats(BundleActiveEvent::SYSTEM_LOCK, beginTime, endTime, systemEventStats, userId); + database_.QueryEventStats(BundleActiveEvent::SYSTEM_UNLOCK, beginTime, endTime, systemEventStats, userId); + database_.QueryEventStats(BundleActiveEvent::SYSTEM_SLEEP, beginTime, endTime, systemEventStats, userId); + database_.QueryEventStats(BundleActiveEvent::SYSTEM_WAKEUP, beginTime, endTime, systemEventStats, userId); + BUNDLE_ACTIVE_LOGI("Query eventStats data in db result size is %{public}zu", systemEventStats.size()); + PrintInMemEventStats(debugUserService_); + // if we need a in-memory stats, combine current stats with result from database. + if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { + BUNDLE_ACTIVE_LOGI("QueryEventStats need in memory stats"); + GetCachedSystemEvents(currentStats, beginTime, endTime, systemEventStats); + } + std::map::iterator iter; + for (iter = systemEventStats.begin(); iter != systemEventStats.end(); iter++) { + eventStats.push_back(iter->second); + } + return BUNDLE_ACTIVE_SUCCESS; +} + +void BundleActiveUserService::GetCachedSystemEvents(std::shared_ptr currentStats, + int64_t beginTime, int64_t endTime, std::map& systemEventStats) +{ + int32_t eventBeginIdx = currentStats->events_.FindBestIndex(beginTime); + int32_t eventSize = currentStats->events_.Size(); + BundleActiveEventStats singleEventStats; + std::map::iterator iter; + for (int32_t i = eventBeginIdx; i < eventSize; i++) { + if ((currentStats->events_.events_[i].timeStamp_ <= endTime) + && ((currentStats->events_.events_[i].eventId_== BundleActiveEvent::SYSTEM_LOCK) + || (currentStats->events_.events_[i].eventId_== BundleActiveEvent::SYSTEM_UNLOCK) + || (currentStats->events_.events_[i].eventId_== BundleActiveEvent::SYSTEM_SLEEP) + || (currentStats->events_.events_[i].eventId_== BundleActiveEvent::SYSTEM_WAKEUP))) { + singleEventStats.name_ = currentStats->events_.events_[i].bundleName_; + iter = systemEventStats.find(singleEventStats.name_); + if (iter != systemEventStats.end()) { + iter->second.count_++; + } else { + singleEventStats.eventId_ = currentStats->events_.events_[i].eventId_; + singleEventStats.count_ = 1; + systemEventStats.insert(std::pair( + singleEventStats.name_, singleEventStats)); + } + } + } +} + +int32_t BundleActiveUserService::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber called"); + auto currentStats = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]; + if (currentStats == nullptr) { + BUNDLE_ACTIVE_LOGE("current interval stat is null!"); + return BUNDLE_ACTIVE_FAIL; + } + if (beginTime >= currentStats->endTime_) { + return BUNDLE_ACTIVE_FAIL; + } + std::map notificationEventStats; + database_.QueryAppNotificationNumber(BundleActiveEvent::NOTIFICATION_SEEN, + beginTime, endTime, notificationEventStats, userId); + BUNDLE_ACTIVE_LOGI("Query eventStats data in db result size is %{public}zu", notificationEventStats.size()); + PrintInMemEventStats(debugUserService_); + // if we need a in-memory stats, combine current stats with result from database. + if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { + BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber need in memory stats"); + GetCachedNotificationEvents(currentStats, beginTime, endTime, notificationEventStats); + } + std::map::iterator iter; + for (iter = notificationEventStats.begin(); iter != notificationEventStats.end(); iter++) { + eventStats.push_back(iter->second); + } + return BUNDLE_ACTIVE_SUCCESS; +} + +void BundleActiveUserService::GetCachedNotificationEvents(std::shared_ptr currentStats, + int64_t beginTime, int64_t endTime, std::map& notificationEventStats) +{ + int32_t eventBeginIdx = currentStats->events_.FindBestIndex(beginTime); + int32_t eventSize = currentStats->events_.Size(); + std::map::iterator iter; + BundleActiveEventStats singleEventStats; + for (int32_t i = eventBeginIdx; i < eventSize; i++) { + if ((currentStats->events_.events_[i].timeStamp_ <= endTime) + && (currentStats->events_.events_[i].eventId_== BundleActiveEvent::NOTIFICATION_SEEN)) { + singleEventStats.name_ = currentStats->events_.events_[i].bundleName_; + iter = notificationEventStats.find(singleEventStats.name_); + if (iter != notificationEventStats.end()) { + iter->second.count_++; + } else { + singleEventStats.eventId_ = BundleActiveEvent::NOTIFICATION_SEEN; + singleEventStats.count_ = 1; + notificationEventStats.insert(std::pair( + singleEventStats.name_, singleEventStats)); + } + } + } +} + void BundleActiveUserService::PrintInMemPackageStats(const int32_t idx, const bool debug) { if (!debug) {