From f88ad4c8a5b41e43ac00d821f2032d54be9723d1 Mon Sep 17 00:00:00 2001 From: fengyang Date: Mon, 23 Dec 2024 14:46:36 +0800 Subject: [PATCH 1/3] push Signed-off-by: fengyang --- .../innerkits/include/bundle_active_client.h | 10 ++++ .../innerkits/include/bundle_active_proxy.h | 7 +++ .../innerkits/src/bundle_active_client.cpp | 10 ++++ .../innerkits/src/bundle_active_proxy.cpp | 16 ++++++ services/common/include/bundle_active_core.h | 6 +++ .../common/include/bundle_active_service.h | 11 ++++ services/common/include/bundle_active_stub.h | 1 + .../include/bundle_active_usage_database.h | 2 +- .../common/include/ibundle_active_service.h | 7 +++ ...bundle_active_service_ipc_interface_code.h | 3 +- services/common/src/bundle_active_core.cpp | 22 ++++++++ services/common/src/bundle_active_service.cpp | 21 ++++++++ services/common/src/bundle_active_stub.cpp | 51 +++++++++---------- .../src/bundle_active_usage_database.cpp | 7 ++- .../src/bundle_active_user_service.cpp | 4 +- .../bundleactiveobserver_fuzzer.cpp | 1 + ...leactivepowerstatecallbackproxy_fuzzer.cpp | 1 + .../device_usage_statistics_mock_test.cpp | 7 +++ .../unittest/device_usage_statistics_test.cpp | 14 +++++ 19 files changed, 170 insertions(+), 31 deletions(-) diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index aa1683e..3936b80 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -55,6 +55,16 @@ public: */ ErrCode IsBundleIdle(bool& isBundleIdle, const std::string& bundleName, int32_t userId = -1); + /** + * @brief IsBundleUsePeriod, used to check whether specific bundle is use period. + * + * @param isBundleIdle The result of IsBundleUsePeriod. + * @param bundleName the target of application's bundle name. + * @param userId default userId is -1 for JS API, if other SAs call this API, they should explicit define userId. + * @return errCode. + */ + ErrCode IsBundleUsePeriod(bool& IsUsePeriod, const std::string& bundleName, int32_t userId = -1); + /** * @brief QueryBundleStatsInfoByInterval, query all bundle usage statistics in specific time span for calling user. * diff --git a/interfaces/innerkits/include/bundle_active_proxy.h b/interfaces/innerkits/include/bundle_active_proxy.h index be3fbc9..f4c077f 100644 --- a/interfaces/innerkits/include/bundle_active_proxy.h +++ b/interfaces/innerkits/include/bundle_active_proxy.h @@ -42,6 +42,13 @@ public: */ ErrCode IsBundleIdle(bool& isBundleIdle, const std::string& bundleName, int32_t userId = -1) override; + /* + * function: IsBundleUsePeriod, used to check whether specific bundle is use period. + * parameters: bundleName, userId. + * return: errorcode. + */ + ErrCode IsBundleUsePeriod(bool& IsUsePeriod, const std::string& bundleName, int32_t userId = -1) override; + /* * function: QueryBundleStatsInfoByInterval, query all usage statistics in specific time span for calling user. * parameters: intervalType, beginTime, endTime, errCode diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 24eda35..1192637 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -82,6 +82,16 @@ ErrCode BundleActiveClient::IsBundleIdle(bool& isBundleIdle, const std::string& return bundleActiveProxy_->IsBundleIdle(isBundleIdle, bundleName, userId); } +ErrCode BundleActiveClient::IsBundleUsePeriod(bool& IsUsePeriod, const std::string& bundleName, int32_t userId) +{ + std::lock_guard lock(mutex_); + ErrCode ret = GetBundleActiveProxy(); + if (ret != ERR_OK) { + return ret; + } + return bundleActiveProxy_->IsBundleUsePeriod(IsUsePeriod, bundleName, userId); +} + ErrCode BundleActiveClient::QueryBundleStatsInfoByInterval(std::vector& PackageStats, const int32_t intervalType, const int64_t beginTime, const int64_t endTime, int32_t userId) { diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index c560ed7..6557b11 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -52,6 +52,22 @@ ErrCode BundleActiveProxy::IsBundleIdle(bool& isBundleIdle, const std::string& b return reply.ReadInt32(); } +ErrCode BundleActiveProxy::IsBundleUsePeriod(bool& IsUsePeriod, const std::string& bundleName, int32_t userId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(GetDescriptor()) || + !data.WriteString(bundleName) || + !data.WriteInt32(userId)) { + return ERR_PARCEL_WRITE_FALIED; + } + Remote() -> SendRequest( + static_cast(IBundleActiveServiceInterfaceCode::IS_BUNDLE_USE_PERIOD), data, reply, option); + IsUsePeriod = reply.ReadInt32(); + return reply.ReadInt32(); +} + ErrCode BundleActiveProxy::QueryBundleStatsInfoByInterval(std::vector& PackageStats, const int32_t intervalType, const int64_t beginTime, const int64_t endTime, int32_t userId) { diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 814c589..f9ff1b3 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -168,6 +168,9 @@ public: // check the app idle state for calling user. int32_t IsBundleIdle(const std::string& bundleName, const int32_t userId); + // check the app use period state for calling user. + bool IsBundleUsePeriod(const std::string& bundleName, const int32_t userId); + // query the app group for calling app. ErrCode QueryAppGroup(int32_t& appGroup, const std::string& bundleName, const int32_t userId); @@ -271,6 +274,9 @@ private: std::map, sptr> recipientMap_; void ObtainSystemEventName(BundleActiveEvent& event); bool debugCore_; + uint32_t minUseDays_ = 3; + uint32_t minUseTimes_ = 1; + uint32_t maxUseTimes_ = 10; }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index 9bbfc9f..d91c143 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -71,6 +71,17 @@ public: */ ErrCode IsBundleIdle(bool& isBundleIdle, const std::string& bundleName, int32_t userId) override; + /** + * @brief IsBundleUsePeriod, used to check whether specific bundle is use period. + * + * @param IsUsePeriod The result of IsBundleIdle. + + * @param bundleName the target of application's bundle name. + * @param userId default userId is -1 for JS API, if other SAs call this API, they should explicit define userId. + * @return errCode. + */ + ErrCode IsBundleUsePeriod(bool& IsUsePeriod, const std::string& bundleName, int32_t userId) override; + /** * @brief QueryBundleStatsInfoByInterval, query all bundle usage statistics in specific time span for calling user. * diff --git a/services/common/include/bundle_active_stub.h b/services/common/include/bundle_active_stub.h index 73c59eb..79f98be 100644 --- a/services/common/include/bundle_active_stub.h +++ b/services/common/include/bundle_active_stub.h @@ -37,6 +37,7 @@ public: private: ErrCode HandleReportEvent(MessageParcel& data, MessageParcel& reply); ErrCode HandleIsBundleIdle(MessageParcel& data, MessageParcel& reply); + ErrCode HandleIsBundleUsePeriod(MessageParcel& data, MessageParcel& reply); ErrCode HandleQueryBundleStatsInfoByInterval(MessageParcel& data, MessageParcel& reply); ErrCode HandleQueryBundleEvents(MessageParcel& data, MessageParcel& reply); ErrCode HandleQueryBundleStatsInfos(MessageParcel& data, MessageParcel& reply); diff --git a/services/common/include/bundle_active_usage_database.h b/services/common/include/bundle_active_usage_database.h index f9a4917..9e6f245 100644 --- a/services/common/include/bundle_active_usage_database.h +++ b/services/common/include/bundle_active_usage_database.h @@ -55,7 +55,7 @@ public: int32_t GetOptimalIntervalType(int64_t beginTime, int64_t endTime); void RemoveOldData(int64_t currentTime); std::vector QueryDatabaseUsageStats(int32_t databaseType, int64_t beginTime, - int64_t endTime, int32_t userId); + int64_t endTime, int32_t userId, const std::string& bundleName = ""); std::vector QueryDatabaseEvents(int64_t beginTime, int64_t endTime, int32_t userId, std::string bundleName); void PutDurationData(int64_t bootBasedDuration, int64_t screenOnDuration); diff --git a/services/common/include/ibundle_active_service.h b/services/common/include/ibundle_active_service.h index 2c2a671..8a6102c 100644 --- a/services/common/include/ibundle_active_service.h +++ b/services/common/include/ibundle_active_service.h @@ -62,6 +62,13 @@ public: */ virtual ErrCode IsBundleIdle(bool& isBundleIdle, const std::string& bundleName, int32_t userId) = 0; + /* + * function: IsUsePeriod, used to check whether specific bundle is use period. + * parameters: bundleName, userId + * return: if bundle is use period, return true. if bundle is not idle, return false. + */ + virtual ErrCode IsBundleUsePeriod(bool& IsUsePeriod, const std::string& bundleName, int32_t userId) = 0; + /* * function: QueryBundleStatsInfoByInterval, query all usage statistics in specific time span for calling user. * parameters: intervalType, beginTime, endTime, errCode diff --git a/services/common/include/ibundle_active_service_ipc_interface_code.h b/services/common/include/ibundle_active_service_ipc_interface_code.h index 73771e1..98bc2a4 100644 --- a/services/common/include/ibundle_active_service_ipc_interface_code.h +++ b/services/common/include/ibundle_active_service_ipc_interface_code.h @@ -32,7 +32,8 @@ namespace DeviceUsageStats { REGISTER_APP_GROUP_CALLBACK = 10, UNREGISTER_APP_GROUP_CALLBACK = 11, QUERY_DEVICE_EVENT_STATES = 12, - QUERY_NOTIFICATION_NUMBER = 13 + QUERY_NOTIFICATION_NUMBER = 13, + IS_BUNDLE_USE_PERIOD = 14 }; } // namespace BackgroundTaskMgr } // namespace OHOS diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index de59b28..fcffdf3 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -23,6 +23,7 @@ #include "bundle_active_group_common.h" #include "bundle_active_bundle_mgr_helper.h" #include "bundle_active_constant.h" +#include "bundle_active_util.h" #include "bundle_constants.h" namespace OHOS { @@ -660,6 +661,27 @@ int32_t BundleActiveCore::IsBundleIdle(const std::string& bundleName, const int3 return bundleGroupController_->IsBundleIdle(bundleName, userId); } +bool BundleActiveCore::IsBundleUsePeriod(const std::string& bundleName, const int32_t userId) +{ + if (!bundleGroupController_->IsBundleInstalled(bundleName, userId)) { + BUNDLE_ACTIVE_LOGI("IsBundleUsePeriod is not bundleInstalled"); + return false; + } + int64_t currentSystemTime = GetSystemTimeMs(); + int64_t aWeekAgo = currentSystemTime - ONE_WEEK_TIME; + int64_t startTime = BundleActiveUtil::GetIntervalTypeStartTime(aWeekAgo, BundleActiveUtil::PERIOD_DAILY); + std::vector packageStats; + QueryBundleStatsInfos(packageStats, userId, BundleActivePeriodStats::PERIOD_DAILY, startTime, + currentSystemTime, bundleName); + int32_t useDayPeriod = 0; + for (auto& item : packageStats) { + if (item.startCount_ >= minUseTimes_ && item.startCount_ <= maxUseTimes_) { + useDayPeriod ++; + } + } + return useDayPeriod >= minUseDays_; +} + void BundleActiveCore::GetAllActiveUser(std::vector& activatedOsAccountIds) { #ifdef OS_ACCOUNT_PART_ENABLED diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 3b3ea21..5cc1af2 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -311,6 +311,27 @@ ErrCode BundleActiveService::IsBundleIdle(bool& isBundleIdle, const std::string& return ERR_OK; } +ErrCode BundleActiveService::IsBundleUsePeriod(bool& IsUsePeriod, const std::string& bundleName, int32_t userId) +{ + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + if (AccessToken::AccessTokenKit::GetTokenType(tokenId) != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) { + return ERR_PERMISSION_DENIED; + } + auto ret = CheckNativePermission(tokenId); + if (ret != ERR_OK) { + return ret; + } + if (userId == -1) { + ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); + if (ret != ERR_OK || userId == -1) { + return ret; + } + } + IsUsePeriod = bundleActiveCore_->IsBundleUsePeriod(bundleName, userId); + return ERR_OK; +} + ErrCode BundleActiveService::QueryBundleStatsInfoByInterval(std::vector& PackageStats, const int32_t intervalType, const int64_t beginTime, const int64_t endTime, int32_t userId) { diff --git a/services/common/src/bundle_active_stub.cpp b/services/common/src/bundle_active_stub.cpp index a07f4da..d06a935 100644 --- a/services/common/src/bundle_active_stub.cpp +++ b/services/common/src/bundle_active_stub.cpp @@ -41,45 +41,34 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me return -1; } switch (code) { - case static_cast(IBundleActiveServiceInterfaceCode::REPORT_EVENT): { + case static_cast(IBundleActiveServiceInterfaceCode::REPORT_EVENT): return HandleReportEvent(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::IS_BUNDLE_IDLE): { + case static_cast(IBundleActiveServiceInterfaceCode::IS_BUNDLE_IDLE): return HandleIsBundleIdle(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::QUERY_BUNDLE_STATS_INFO_BY_INTERVAL): { + case static_cast(IBundleActiveServiceInterfaceCode::QUERY_BUNDLE_STATS_INFO_BY_INTERVAL): return HandleQueryBundleStatsInfoByInterval(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::QUERY_BUNDLE_EVENTS): { + case static_cast(IBundleActiveServiceInterfaceCode::QUERY_BUNDLE_EVENTS): return HandleQueryBundleEvents(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::SET_APP_GROUP): { + case static_cast(IBundleActiveServiceInterfaceCode::SET_APP_GROUP): return HandleSetAppGroup(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::QUERY_BUNDLE_STATS_INFOS): { + case static_cast(IBundleActiveServiceInterfaceCode::QUERY_BUNDLE_STATS_INFOS): return HandleQueryBundleStatsInfos(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::QUERY_CURRENT_BUNDLE_EVENTS): { + case static_cast(IBundleActiveServiceInterfaceCode::QUERY_CURRENT_BUNDLE_EVENTS): return HandleQueryCurrentBundleEvents(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::QUERY_APP_GROUP): { + case static_cast(IBundleActiveServiceInterfaceCode::QUERY_APP_GROUP): return HandleQueryAppGroup(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::QUERY_MODULE_USAGE_RECORDS): { + case static_cast(IBundleActiveServiceInterfaceCode::QUERY_MODULE_USAGE_RECORDS): return HandleQueryModuleUsageRecords(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::REGISTER_APP_GROUP_CALLBACK): { + case static_cast(IBundleActiveServiceInterfaceCode::REGISTER_APP_GROUP_CALLBACK): return HandleRegisterAppGroupCallBack(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::UNREGISTER_APP_GROUP_CALLBACK): { + case static_cast(IBundleActiveServiceInterfaceCode::UNREGISTER_APP_GROUP_CALLBACK): return HandleUnRegisterAppGroupCallBack(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::QUERY_DEVICE_EVENT_STATES): { + case static_cast(IBundleActiveServiceInterfaceCode::QUERY_DEVICE_EVENT_STATES): return HandleQueryDeviceEventStats(data, reply); - } - case static_cast(IBundleActiveServiceInterfaceCode::QUERY_NOTIFICATION_NUMBER): { + case static_cast(IBundleActiveServiceInterfaceCode::QUERY_NOTIFICATION_NUMBER): return HandleQueryNotificationEventStats(data, reply); - } + case static_cast(IBundleActiveServiceInterfaceCode::IS_BUNDLE_USE_PERIOD): + return HandleIsBundleUsePeriod(data, reply); default: return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } @@ -107,6 +96,16 @@ ErrCode BundleActiveStub::HandleIsBundleIdle(MessageParcel& data, MessageParcel& return reply.WriteInt32(errCode); } +ErrCode BundleActiveStub::HandleIsBundleUsePeriod(MessageParcel& data, MessageParcel& reply) +{ + bool IsUsePeriod = false; + std::string bundleName = data.ReadString(); + int32_t userId = data.ReadInt32(); + ErrCode errCode = IsBundleUsePeriod(IsUsePeriod, bundleName, userId); + reply.WriteInt32(IsUsePeriod); + return reply.WriteInt32(errCode); +} + ErrCode BundleActiveStub::HandleQueryBundleStatsInfoByInterval(MessageParcel& data, MessageParcel& reply) { std::vector result; diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index abb1095..c01c522 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -1435,7 +1435,7 @@ void BundleActiveUsageDatabase::GetQuerySqlCommand(const int64_t beginTime, } vector BundleActiveUsageDatabase::QueryDatabaseUsageStats(int32_t databaseType, - int64_t beginTime, int64_t endTime, int32_t userId) + int64_t beginTime, int64_t endTime, int32_t userId, const std::string& bundleName) { lock_guard lock(databaseMutex_); vector databaseUsageStats; @@ -1447,8 +1447,13 @@ vector BundleActiveUsageDatabase::QueryDatabaseUsageSt for (int32_t i = startIndex; i <= endIndex; i++) { string queryPackageSql; vector queryCondition; + GetQuerySqlCommand(beginTime, endTime, databaseType, i, startIndex, endIndex, userId, queryCondition, queryPackageSql); + if (bundleName != "") { + queryCondition.push_back(bundleName); + queryPackageSql += " and bundleName = ?"; + } auto bundleActiveResult = QueryStatsInfoByStep(databaseType, queryPackageSql, queryCondition); if (bundleActiveResult == nullptr) { diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index 897fe45..23685dd 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -441,14 +441,14 @@ ErrCode BundleActiveUserService::QueryBundleStatsInfos(std::vector currentStats->beginTime_ + periodLength_[intervalType]) { return ERR_QUERY_TIME_OUT_OF_RANGE; } else { - PackageStats = database_.QueryDatabaseUsageStats(intervalType, beginTime, endTime, userId); + PackageStats = database_.QueryDatabaseUsageStats(intervalType, beginTime, endTime, userId, bundleName); return ERR_OK; } } else if (beginTime >= currentStats->endTime_) { return ERR_QUERY_TIME_OUT_OF_RANGE; } int64_t truncatedEndTime = std::min(currentStats->beginTime_, endTime); - PackageStats = database_.QueryDatabaseUsageStats(intervalType, beginTime, truncatedEndTime, userId); + PackageStats = database_.QueryDatabaseUsageStats(intervalType, beginTime, truncatedEndTime, userId, bundleName); BUNDLE_ACTIVE_LOGI("Query package data in db PackageStats size is %{public}zu", PackageStats.size()); PrintInMemPackageStats(intervalType, debugUserService_); // if we need a in-memory stats, combine current stats with PackageStats from database. diff --git a/test/fuzztest/bundleactiveobserver_fuzzer/bundleactiveobserver_fuzzer.cpp b/test/fuzztest/bundleactiveobserver_fuzzer/bundleactiveobserver_fuzzer.cpp index 2964c16..3525909 100644 --- a/test/fuzztest/bundleactiveobserver_fuzzer/bundleactiveobserver_fuzzer.cpp +++ b/test/fuzztest/bundleactiveobserver_fuzzer/bundleactiveobserver_fuzzer.cpp @@ -52,6 +52,7 @@ namespace DeviceUsageStats { int32_t userId = static_cast(GetU32Data(data)); std::string inputBundlName(data); DelayedSingleton::GetInstance()->IsBundleIdle(result, inputBundlName, userId); + DelayedSingleton::GetInstance()->IsBundleUsePeriod(result, inputBundlName, userId); return true; } } // namespace DeviceUsageStats diff --git a/test/fuzztest/bundleactivepowerstatecallbackproxy_fuzzer/bundleactivepowerstatecallbackproxy_fuzzer.cpp b/test/fuzztest/bundleactivepowerstatecallbackproxy_fuzzer/bundleactivepowerstatecallbackproxy_fuzzer.cpp index 210c2b7..f3c8d72 100644 --- a/test/fuzztest/bundleactivepowerstatecallbackproxy_fuzzer/bundleactivepowerstatecallbackproxy_fuzzer.cpp +++ b/test/fuzztest/bundleactivepowerstatecallbackproxy_fuzzer/bundleactivepowerstatecallbackproxy_fuzzer.cpp @@ -113,6 +113,7 @@ namespace DeviceUsageStats { DelayedSingleton::GetInstance()->RegisterAppGroupCallBack(appGroupCallback); DelayedSingleton::GetInstance()->UnRegisterAppGroupCallBack(appGroupCallback); DelayedSingleton::GetInstance()->IsBundleIdle(result, inputBundleName, userId); + DelayedSingleton::GetInstance()->IsBundleUsePeriod(result, inputBundleName, userId); BundleActiveEvent event(g_defaultBundleName, g_defaultMoudleName, g_defaultFormName, DEFAULT_DIMENSION, DEFAULT_FORMID, BundleActiveEvent::FORM_IS_CLICKED); DelayedSingleton::GetInstance()->ReportEvent(event, userId); diff --git a/test/unittest/device_usage_statistics_mock_test.cpp b/test/unittest/device_usage_statistics_mock_test.cpp index b5c3630..5336bce 100644 --- a/test/unittest/device_usage_statistics_mock_test.cpp +++ b/test/unittest/device_usage_statistics_mock_test.cpp @@ -80,7 +80,10 @@ HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_GetBundleA EXPECT_NE(BundleActiveClient::GetInstance().ReportEvent(eventA, g_defaultUserId), ERR_OK); bool isIdle = false; + bool isUsePeriod = false; EXPECT_NE(BundleActiveClient::GetInstance().IsBundleIdle(isIdle, g_defaultBundleName, g_defaultUserId), ERR_OK); + EXPECT_NE(BundleActiveClient::GetInstance().IsBundleUsePeriod(isUsePeriod, g_defaultBundleName, g_defaultUserId), + ERR_OK); std::vector packageStats; EXPECT_NE(BundleActiveClient::GetInstance().QueryBundleStatsInfoByInterval(packageStats, @@ -121,8 +124,12 @@ HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_GetBundleM { std::string bundleName; bool isBundleIdle = false; + bool isUsePeriod = false; ErrCode code = DelayedSingleton::GetInstance()->IsBundleIdle(isBundleIdle, bundleName, -1); EXPECT_NE(code, ERR_OK); + code = DelayedSingleton::GetInstance()-> + IsBundleUsePeriod(isUsePeriod, bundleName, -1); + EXPECT_NE(code, ERR_OK); code = DelayedSingleton::GetInstance()->CheckBundleIsSystemAppAndHasPermission(100, 100000); EXPECT_NE(code, ERR_OK); diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 8d1072d..63e75e7 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -194,6 +194,20 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_IsBundleIdle_001, EXPECT_EQ(errCode, 0); } +/* + * @tc.name: DeviceUsageStatisticsTest_IsBundleUsePeriod_001 + * @tc.desc: IsBundleUsePeriod + * @tc.type: FUNC + * @tc.require: issueIBB2G4 + */ +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_IsBundleUsePeriod_001, Function | MediumTest | Level0) +{ + bool result = false; + int32_t errCode = BundleActiveClient::GetInstance().IsBundleUsePeriod(result, g_defaultBundleName, g_defaultUserId); + EXPECT_EQ(result, false); + EXPECT_EQ(errCode, ERR_PERMISSION_DENIED); +} + /* * @tc.name: DeviceUsageStatisticsTest_QueryModuleUsageRecords_001 * @tc.desc: QueryModuleUsageRecords -- Gitee From 0f7656a6a5a0e6e4ba196d99cbb19b7087ca67cf Mon Sep 17 00:00:00 2001 From: fengyang Date: Mon, 23 Dec 2024 14:49:17 +0800 Subject: [PATCH 2/3] push Signed-off-by: fengyang --- BUILD.gn | 8 + bundle.json | 2 + .../include/bundle_active_config_reader.h | 42 ++++++ services/common/include/bundle_active_core.h | 5 +- .../src/bundle_active_config_reader.cpp | 141 ++++++++++++++++++ services/common/src/bundle_active_core.cpp | 7 +- services/common/src/bundle_active_service.cpp | 1 + .../device_usage_statistics_service_test.cpp | 66 ++++++++ 8 files changed, 267 insertions(+), 5 deletions(-) create mode 100644 services/common/include/bundle_active_config_reader.h create mode 100644 services/common/src/bundle_active_config_reader.cpp diff --git a/BUILD.gn b/BUILD.gn index 86a83b0..d7740af 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -165,6 +165,7 @@ ohos_shared_library("usagestatservice") { "services/common/src/bundle_active_app_state_obsever.cpp", "services/common/src/bundle_active_binary_search.cpp", "services/common/src/bundle_active_bundle_mgr_helper.cpp", + "services/common/src/bundle_active_config_reader.cpp", "services/common/src/bundle_active_continuous_task_observer.cpp", "services/common/src/bundle_active_core.cpp", "services/common/src/bundle_active_debug_mode.cpp", @@ -202,6 +203,7 @@ ohos_shared_library("usagestatservice") { "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", "eventhandler:libeventhandler", "ffrt:libffrt", "hicollie:libhicollie", @@ -214,6 +216,8 @@ ohos_shared_library("usagestatservice") { "time_service:time_client", ] + public_external_deps = [ "jsoncpp:jsoncpp" ] + if (os_account_part_enabled) { cflags_cc += [ "-DOS_ACCOUNT_PART_ENABLED" ] external_deps += [ "os_account:os_account_innerkits" ] @@ -247,6 +251,7 @@ ohos_static_library("usagestatservice_static") { "services/common/src/bundle_active_app_state_obsever.cpp", "services/common/src/bundle_active_binary_search.cpp", "services/common/src/bundle_active_bundle_mgr_helper.cpp", + "services/common/src/bundle_active_config_reader.cpp", "services/common/src/bundle_active_continuous_task_observer.cpp", "services/common/src/bundle_active_core.cpp", "services/common/src/bundle_active_debug_mode.cpp", @@ -284,6 +289,7 @@ ohos_static_library("usagestatservice_static") { "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", "eventhandler:libeventhandler", "ffrt:libffrt", "hicollie:libhicollie", @@ -296,6 +302,8 @@ ohos_static_library("usagestatservice_static") { "time_service:time_client", ] + public_external_deps = [ "jsoncpp:jsoncpp" ] + if (os_account_part_enabled) { cflags_cc += [ "-DOS_ACCOUNT_PART_ENABLED" ] external_deps += [ "os_account:os_account_innerkits" ] diff --git a/bundle.json b/bundle.json index 83e467f..005b1f3 100644 --- a/bundle.json +++ b/bundle.json @@ -27,6 +27,7 @@ "relational_store", "safwk", "common_event_service", + "config_policy", "os_account", "ipc", "access_token", @@ -42,6 +43,7 @@ "power_manager", "time_service", "init", + "jsoncpp", "ffrt" ], "third_party": [] diff --git a/services/common/include/bundle_active_config_reader.h b/services/common/include/bundle_active_config_reader.h new file mode 100644 index 0000000..1400e4e --- /dev/null +++ b/services/common/include/bundle_active_config_reader.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 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_CONFIG_READER_H +#define BUNDLE_ACTIVE_CONFIG_READER_H +#include +#include "json/json.h" + +namespace OHOS { +namespace DeviceUsageStats { +struct AppUsePeriodicallyConfig { + int32_t minUseTimes; + int32_t maxUseTimes; + int32_t minUseDays; +}; +class BundleActiveConfigReader { +public: + void LoadConfig(); + AppUsePeriodicallyConfig GetApplicationUsePeriodicallyConfig(); +private: + void LoadApplicationUsePeriodically(const char* path); + bool GetJsonFromFile(const char* filePath, Json::Value& root); + bool ConvertFullPath(const std::string& partialPath, std::string& fullPath); + AppUsePeriodicallyConfig appUsePeriodicallyConfig_; +}; + +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_CONFIG_READER_H + diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index f9ff1b3..a497ab8 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -42,6 +42,7 @@ #include "bundle_active_group_handler.h" #include "bundle_active_common_event_subscriber.h" #include "bundle_active_constant.h" +#include "bundle_active_config_reader.h" namespace OHOS { namespace DeviceUsageStats { @@ -274,9 +275,7 @@ private: std::map, sptr> recipientMap_; void ObtainSystemEventName(BundleActiveEvent& event); bool debugCore_; - uint32_t minUseDays_ = 3; - uint32_t minUseTimes_ = 1; - uint32_t maxUseTimes_ = 10; + std::shared_ptr bundleActiveConfigReader_; }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/common/src/bundle_active_config_reader.cpp b/services/common/src/bundle_active_config_reader.cpp new file mode 100644 index 0000000..a7df1d9 --- /dev/null +++ b/services/common/src/bundle_active_config_reader.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2024 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_config_reader.h" +#include "config_policy_utils.h" +#include "bundle_active_log.h" +#include +#include + +using namespace std; +namespace OHOS { +namespace DeviceUsageStats { +const char* CONFIG_PATH = "etc/device_usage_statistics/device_usage_statistics_config.json"; +const std::string APPLICATION_USE_PERIODICALLY_KEY = "application_use_periodically"; +const std::string MIN_USE_TIMES = "MinUseTimes"; +const std::string MAX_USE_TIMES = "MaxUseTimes"; +const std::string MIN_USE_DAYS = "MinUseDays"; +const int32_t DEFAULT_MIN_USE_TIMES = 1; +const int32_t DEFAULT_MAX_USE_TIMES = 10; +const int32_t DEFAULT_MIN_USE_DAYS = 3; +const int32_t MAX_BUFFER = 2048; + + +void BundleActiveConfigReader::LoadConfig() +{ + appUsePeriodicallyConfig_ = { DEFAULT_MIN_USE_TIMES, DEFAULT_MAX_USE_TIMES, DEFAULT_MIN_USE_DAYS}; + auto cfgFiles = GetCfgFiles(CONFIG_PATH); + if (!cfgFiles) { + BUNDLE_ACTIVE_LOGE("GetCfgFiles failed"); + return; + } + for (const auto& filePath : cfgFiles->paths) { + LoadApplicationUsePeriodically(filePath); + } + BUNDLE_ACTIVE_LOGI("appUsePeriodicallyConfig minUseTimes:%{public}d, maxUseTimes:%{public}d," + "minUseDays:%{public}d", appUsePeriodicallyConfig_.minUseTimes, + appUsePeriodicallyConfig_.maxUseTimes, appUsePeriodicallyConfig_.minUseDays); +}; + +void BundleActiveConfigReader::LoadApplicationUsePeriodically(const char *filePath) +{ + if (!filePath) { + return; + } + Json::Value root; + if (!GetJsonFromFile(filePath, root) || root.empty()) { + BUNDLE_ACTIVE_LOGE("file is empty %{private}s", filePath); + return; + } + if (!root.isMember(APPLICATION_USE_PERIODICALLY_KEY)) { + BUNDLE_ACTIVE_LOGE("not have application_use_periodically key"); + return; + } + Json::Value appUsePeriodicallyRoot = root[APPLICATION_USE_PERIODICALLY_KEY]; + if (appUsePeriodicallyRoot.empty() || !appUsePeriodicallyRoot.isObject()) { + BUNDLE_ACTIVE_LOGE("application_use_periodically content is empty"); + return; + } + if (appUsePeriodicallyRoot[MIN_USE_TIMES].empty() || !appUsePeriodicallyRoot[MIN_USE_TIMES].isInt()) { + BUNDLE_ACTIVE_LOGE("not have MinUseTimes key"); + return; + } + int32_t minUseTimes = appUsePeriodicallyRoot[MIN_USE_TIMES].asInt(); + if (appUsePeriodicallyRoot[MAX_USE_TIMES].empty() || !appUsePeriodicallyRoot[MAX_USE_TIMES].isInt()) { + BUNDLE_ACTIVE_LOGE("not have MaxUseTimes key"); + return; + } + int32_t maxUseTimes = appUsePeriodicallyRoot[MAX_USE_TIMES].asInt(); + if (appUsePeriodicallyRoot[MIN_USE_DAYS].empty() || !appUsePeriodicallyRoot[MIN_USE_DAYS].isInt()) { + BUNDLE_ACTIVE_LOGE("not have MinUseDays key"); + return; + } + int32_t minUseDays = appUsePeriodicallyRoot[MIN_USE_DAYS].asInt(); + appUsePeriodicallyConfig_ = { minUseTimes, maxUseTimes, minUseDays}; +}; + +bool BundleActiveConfigReader::GetJsonFromFile(const char *filePath, Json::Value &root) +{ + ifstream fin; + std::string realPath; + if (!BundleActiveConfigReader::ConvertFullPath(filePath, realPath)) { + BUNDLE_ACTIVE_LOGE("Get real path failed %{private}s", filePath); + return false; + } + BUNDLE_ACTIVE_LOGD("Read from %{private}s", realPath.c_str()); + fin.open(realPath, ios::in); + if (!fin.is_open()) { + BUNDLE_ACTIVE_LOGE("cannot open file %{private}s", realPath.c_str()); + return false; + } + char buffer[MAX_BUFFER]; + ostringstream os; + while (fin.getline(buffer, MAX_BUFFER)) { + os << buffer; + } + string data = os.str(); + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + const unique_ptr jsonReader(readerBuilder.newCharReader()); + bool res = jsonReader->parse(data.c_str(), data.c_str() + data.length(), &root, &errs); + fin.close(); + if (!res || !errs.empty()) { + BUNDLE_ACTIVE_LOGE("parse %{private}s json error", realPath.c_str()); + return false; + } + return true; +} + +bool BundleActiveConfigReader::ConvertFullPath(const std::string& partialPath, std::string& fullPath) +{ + if (partialPath.empty() || partialPath.length() >= PATH_MAX) { + return false; + } + char tmpPath[PATH_MAX] = {0}; + if (realpath(partialPath.c_str(), tmpPath) == nullptr) { + return false; + } + fullPath = tmpPath; + return true; +} + +AppUsePeriodicallyConfig BundleActiveConfigReader::GetApplicationUsePeriodicallyConfig() +{ + return appUsePeriodicallyConfig_; +}; + +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index fcffdf3..f6b0fbe 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -188,6 +188,8 @@ void BundleActiveCore::Init() systemTimeShot_ = GetSystemTimeMs(); bundleGroupController_ = std::make_shared(debugCore_); BUNDLE_ACTIVE_LOGD("system time shot is %{public}lld", (long long)systemTimeShot_); + bundleActiveConfigReader_ = std::make_shared(); + bundleActiveConfigReader_->LoadConfig(); } void BundleActiveCore::InitBundleGroupController() @@ -675,11 +677,12 @@ bool BundleActiveCore::IsBundleUsePeriod(const std::string& bundleName, const in currentSystemTime, bundleName); int32_t useDayPeriod = 0; for (auto& item : packageStats) { - if (item.startCount_ >= minUseTimes_ && item.startCount_ <= maxUseTimes_) { + if (item.startCount_ >= bundleActiveConfigReader_->GetApplicationUsePeriodicallyConfig().minUseTimes + && item.startCount_ <= bundleActiveConfigReader_->GetApplicationUsePeriodicallyConfig().maxUseTimes) { useDayPeriod ++; } } - return useDayPeriod >= minUseDays_; + return useDayPeriod >= bundleActiveConfigReader_->GetApplicationUsePeriodicallyConfig().minUseDays; } void BundleActiveCore::GetAllActiveUser(std::vector& activatedOsAccountIds) diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 5cc1af2..d187bea 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -329,6 +329,7 @@ ErrCode BundleActiveService::IsBundleUsePeriod(bool& IsUsePeriod, const std::str } } IsUsePeriod = bundleActiveCore_->IsBundleUsePeriod(bundleName, userId); + BUNDLE_ACTIVE_LOGI("IsBundleUsePeriod %{public}d", IsUsePeriod); return ERR_OK; } diff --git a/test/unittest/device_usage_statistics_service_test.cpp b/test/unittest/device_usage_statistics_service_test.cpp index 3edd8b7..134203b 100644 --- a/test/unittest/device_usage_statistics_service_test.cpp +++ b/test/unittest/device_usage_statistics_service_test.cpp @@ -28,6 +28,7 @@ #include "bundle_active_user_history.h" #include "bundle_active_group_controller.h" #include "bundle_active_log.h" +#include "bundle_active_config_reader.h" using namespace testing::ext; @@ -1437,5 +1438,70 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Dele userService->DeleteUninstalledBundleStats("test", 100, appIndex); } +/* + * @tc.name: DeviceUsageStatisticsServiceTest_ConfigReader_001 + * @tc.desc: ConfigReader + * @tc.type: FUNC + * @tc.require: issuesIBCE1G + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_ConfigReader_001, + Function | MediumTest | Level0) +{ + auto bundleActiveConfigReader = std::make_shared(); + EXPECT_NE(bundleActiveConfigReader, nullptr); + bundleActiveConfigReader->LoadConfig(); + EXPECT_NE(bundleActiveConfigReader->GetApplicationUsePeriodicallyConfig().minUseTimes, 0); +} + +/* + * @tc.name: DeviceUsageStatisticsServiceTest_ConfigReader_002 + * @tc.desc: ConfigReader + * @tc.type: FUNC + * @tc.require: issuesIBCE1G + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_ConfigReader_002, + Function | MediumTest | Level0) +{ + auto bundleActiveConfigReader = std::make_shared(); + EXPECT_NE(bundleActiveConfigReader, nullptr); + const char *path = "test"; + bundleActiveConfigReader->LoadApplicationUsePeriodically(path); + EXPECT_EQ(bundleActiveConfigReader->GetApplicationUsePeriodicallyConfig().minUseTimes, 0); +} + +/* + * @tc.name: DeviceUsageStatisticsServiceTest_ConfigReader_003 + * @tc.desc: ConfigReader + * @tc.type: FUNC + * @tc.require: issuesIBCE1G + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_ConfigReader_003, + Function | MediumTest | Level0) +{ + auto bundleActiveConfigReader = std::make_shared(); + EXPECT_NE(bundleActiveConfigReader, nullptr); + const char *path = "test"; + Json::Value root; + bool result = bundleActiveConfigReader->GetJsonFromFile(path, root); + EXPECT_EQ(result, false); +} + +/* + * @tc.name: DeviceUsageStatisticsServiceTest_ConfigReader_004 + * @tc.desc: ConfigReader + * @tc.type: FUNC + * @tc.require: issuesIBCE1G + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_ConfigReader_004, + Function | MediumTest | Level0) +{ + auto bundleActiveConfigReader = std::make_shared(); + EXPECT_NE(bundleActiveConfigReader, nullptr); + std::string partialPath = "test"; + std::string fullPath = ""; + bool result = bundleActiveConfigReader->ConvertFullPath(partialPath, fullPath); + EXPECT_EQ(result, false); +} + } // namespace DeviceUsageStats } // namespace OHOS \ No newline at end of file -- Gitee From 365ce662639d2d65f99522104f6bab19c625330e Mon Sep 17 00:00:00 2001 From: fengyang Date: Tue, 24 Dec 2024 16:51:44 +0800 Subject: [PATCH 3/3] push Signed-off-by: fengyang --- .../common/include/bundle_active_service.h | 3 + services/common/src/bundle_active_service.cpp | 112 +++++++++++------- utils/include/bundle_active_util.h | 2 + utils/src/bundle_active_util.cpp | 25 ++++ 4 files changed, 99 insertions(+), 43 deletions(-) diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index d91c143..cf33fee 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -251,6 +251,9 @@ private: void DumpUsage(std::string &result); bool AllowDump(); int32_t ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); + int32_t DumpEvents(const std::vector &dumpOption, std::vector &dumpInfo); + int32_t DumpPackageUsage(const std::vector &dumpOption, std::vector &dumpInfo); + int32_t DumpModuleUsage(const std::vector &dumpOption, std::vector &dumpInfo); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index d187bea..d9203ca 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -32,6 +32,7 @@ #include "bundle_active_shutdown_callback_service.h" #include "tokenid_kit.h" #include "xcollie/watchdog.h" +#include "bundle_active_util.h" #include "bundle_active_service.h" @@ -546,13 +547,8 @@ ErrCode BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_ ErrCode BundleActiveService::CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId) { - int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, "ohos.permission.DUMP"); - if (ret == Security::AccessToken::PermissionState::PERMISSION_GRANTED) { - BUNDLE_ACTIVE_LOGD("check native permission success, request from dump"); - return ERR_OK; - } int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION); - if (bundleHasPermission != 0) { + if (bundleHasPermission != Security::AccessToken::PermissionState::PERMISSION_GRANTED) { BUNDLE_ACTIVE_LOGE("check native permission not have permission"); return ERR_PERMISSION_DENIED; } @@ -743,46 +739,76 @@ int32_t BundleActiveService::Dump(int32_t fd, const std::vector int32_t BundleActiveService::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) { int32_t ret = -1; + if (!bundleActiveCore_) { + return ret; + } if (dumpOption[1] == "Events") { - std::vector eventResult; - if (static_cast(dumpOption.size()) != EVENTS_PARAM) { - return ret; - } - int64_t beginTime = std::stoll(dumpOption[2]); - int64_t endTime = std::stoll(dumpOption[3]); - int32_t userId = std::stoi(dumpOption[4]); - this->QueryBundleEvents(eventResult, beginTime, endTime, userId); - for (auto& oneEvent : eventResult) { - dumpInfo.emplace_back(oneEvent.ToString()); - } + ret = DumpEvents(dumpOption, dumpInfo); } else if (dumpOption[1] == "PackageUsage") { - std::vector packageUsageResult; - if (static_cast(dumpOption.size()) != PACKAGE_USAGE_PARAM) { - return ret; - } - int32_t intervalType = std::stoi(dumpOption[2]); - int64_t beginTime = std::stoll(dumpOption[3]); - int64_t endTime = std::stoll(dumpOption[4]); - int32_t userId = std::stoi(dumpOption[5]); - this->QueryBundleStatsInfoByInterval(packageUsageResult, intervalType, beginTime, endTime, userId); - for (auto& onePackageRecord : packageUsageResult) { - dumpInfo.emplace_back(onePackageRecord.ToString()); - } + ret = DumpPackageUsage(dumpOption, dumpInfo); } else if (dumpOption[1] == "ModuleUsage") { - std::vector moduleResult; - if (static_cast(dumpOption.size()) != MODULE_USAGE_PARAM) { - return ret; - } - int32_t maxNum = std::stoi(dumpOption[2]); - int32_t userId = std::stoi(dumpOption[3]); - BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId); - ret = this->QueryModuleUsageRecords(maxNum, moduleResult, userId); - for (auto& oneModuleRecord : moduleResult) { - dumpInfo.emplace_back(oneModuleRecord.ToString()); - for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) { - std::string oneFormInfo = "form " + std::to_string(static_cast(i) + 1) + ", "; - dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString()); - } + ret = DumpModuleUsage(dumpOption, dumpInfo); + } + return ret; +} + +int32_t BundleActiveService::DumpEvents(const std::vector &dumpOption, std::vector &dumpInfo) +{ + int32_t ret = -1; + std::vector eventResult; + if (static_cast(dumpOption.size()) != EVENTS_PARAM) { + return ret; + } + int64_t beginTime = BundleActiveUtil::StringToInt64(dumpOption[2]); + int64_t endTime = BundleActiveUtil::StringToInt64(dumpOption[3]); + int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[4]); + bundleActiveCore_->QueryBundleEvents(eventResult, userId, beginTime, endTime, ""); + for (auto& oneEvent : eventResult) { + dumpInfo.emplace_back(oneEvent.ToString()); + } + return ret; +} + +int32_t BundleActiveService::DumpPackageUsage(const std::vector &dumpOption, + std::vector &dumpInfo) +{ + int32_t ret = -1; + std::vector packageUsageResult; + if (static_cast(dumpOption.size()) != PACKAGE_USAGE_PARAM) { + return ret; + } + int32_t intervalType = ConvertIntervalType(BundleActiveUtil::StringToInt32(dumpOption[2])); + int64_t beginTime = BundleActiveUtil::StringToInt64(dumpOption[3]); + int64_t endTime = BundleActiveUtil::StringToInt64(dumpOption[4]); + int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[5]); + bundleActiveCore_->QueryBundleStatsInfos( + packageUsageResult, userId, intervalType, beginTime, endTime, ""); + for (auto& onePackageRecord : packageUsageResult) { + dumpInfo.emplace_back(onePackageRecord.ToString()); + } + return ret; +} + +int32_t BundleActiveService::DumpModuleUsage(const std::vector &dumpOption, + std::vector &dumpInfo) +{ + int32_t ret = -1; + std::vector moduleResult; + if (static_cast(dumpOption.size()) != MODULE_USAGE_PARAM) { + return ret; + } + int32_t maxNum = BundleActiveUtil::StringToInt32(dumpOption[2]); + int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[3]); + BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId); + ret = bundleActiveCore_->QueryModuleUsageRecords(maxNum, moduleResult, userId); + for (auto& oneResult : moduleResult) { + QueryModuleRecordInfos(oneResult); + } + for (auto& oneModuleRecord : moduleResult) { + dumpInfo.emplace_back(oneModuleRecord.ToString()); + for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) { + std::string oneFormInfo = "form " + std::to_string(static_cast(i) + 1) + ", "; + dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString()); } } return ret; diff --git a/utils/include/bundle_active_util.h b/utils/include/bundle_active_util.h index 12a2c04..67f3805 100644 --- a/utils/include/bundle_active_util.h +++ b/utils/include/bundle_active_util.h @@ -30,6 +30,8 @@ public: static std::string GetBundleUsageKey(const std::string& bundleName, const int32_t uid); static int64_t GetFFRTDelayTime(const int64_t& delayTime); static int64_t GetIntervalTypeStartTime(const int64_t& timeStamp, const int32_t& intervalType); + static int32_t StringToInt32(const std::string& str); + static int64_t StringToInt64(const std::string& str); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/utils/src/bundle_active_util.cpp b/utils/src/bundle_active_util.cpp index a92f91f..8bc7444 100644 --- a/utils/src/bundle_active_util.cpp +++ b/utils/src/bundle_active_util.cpp @@ -14,6 +14,7 @@ */ #include +#include #include "bundle_active_util.h" namespace OHOS { @@ -74,6 +75,30 @@ int64_t BundleActiveUtil::GetIntervalTypeStartTime(const int64_t& timeStamp, con } return mktime(tm_time) * SECOND_TO_MILLISECOND; } + +int32_t BundleActiveUtil::StringToInt32(const std::string& str) +{ + char* pEnd = nullptr; + errno = 0; + int64_t res = std::strtol(str.c_str(), &pEnd, 10); + if (errno == ERANGE || pEnd == str.c_str() || *pEnd != '\0' || + (res < std::numeric_limits::min()) || + res > std::numeric_limits::max()) { + return 0; + } + return static_cast(res); +} + +int64_t BundleActiveUtil::StringToInt64(const std::string& str) +{ + char* pEnd = nullptr; + errno = 0; + int64_t res = std::strtol(str.c_str(), &pEnd, 10); + if (errno == ERANGE || pEnd == str.c_str() || *pEnd != '\0') { + return 0; + } + return res; +} } // namespace DeviceUsageStats } // namespace OHOS -- Gitee