diff --git a/BUILD.gn b/BUILD.gn index ed3b8b122d491415c709169c320904cf9989506c..fbe873b10abce873d1bebdbdb4176b2601f79e4c 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -238,6 +238,7 @@ ohos_shared_library("usagestatservice") { "services/common/src/bundle_active_service.cpp", "services/common/src/bundle_active_shutdown_callback_service.cpp", "services/common/src/bundle_active_usage_database.cpp", + "services/common/src/bundle_active_usage_database_upgrade.cpp", "services/packagegroup/src/bundle_active_group_controller.cpp", "services/packagegroup/src/bundle_active_group_handler.cpp", "services/packagegroup/src/bundle_active_user_history.cpp", @@ -318,6 +319,7 @@ ohos_static_library("usagestatservice_static") { "services/common/src/bundle_active_service.cpp", "services/common/src/bundle_active_shutdown_callback_service.cpp", "services/common/src/bundle_active_usage_database.cpp", + "services/common/src/bundle_active_usage_database_upgrade.cpp", "services/packagegroup/src/bundle_active_group_controller.cpp", "services/packagegroup/src/bundle_active_group_handler.cpp", "services/packagegroup/src/bundle_active_user_history.cpp", diff --git a/services/common/include/bundle_active_constant.h b/services/common/include/bundle_active_constant.h index b588ef501811ff84e407516c2887d3f36e9f5916..6276a4d4ed202d83e7669e0914b6c40deb4fdd98 100644 --- a/services/common/include/bundle_active_constant.h +++ b/services/common/include/bundle_active_constant.h @@ -36,7 +36,8 @@ const int32_t YEARLY_DATABASE_INDEX = 3; const int32_t EVENT_DATABASE_INDEX = 4; const int32_t APP_GROUP_DATABASE_INDEX = 5; const int32_t BUNDLE_ACTIVE_VERSION_V1 = 1; -const int32_t BUNDLE_ACTIVE_CURRENT_VERSION = 2; +const int32_t BUNDLE_ACTIVE_VERSION_V2 = 2; +const int32_t BUNDLE_ACTIVE_CURRENT_VERSION = 3; const int32_t BUNDLE_ACTIVE_SUCCESS = 0; const int32_t BUNDLE_ACTIVE_FAIL = -1; const int32_t BUNDLE_ACTIVE_RDB_VERSION = 1; @@ -63,6 +64,7 @@ const int32_t REASON_IN_GROUP_COLUMN_INDEX = 5; const int32_t BUNDLE_ALIVE_TIMEOUT_TIME_COLUMN_INDEX = 6; const int32_t BUNDLE_DAILY_TIMEOUT_TIME_COLUMN_INDEX = 7; const int32_t BUNDLE_HISTORY_LOG_UID_COLUMN_INDEX = 8; +const int32_t BUNDLE_HISTORY_LOG_FIRST_USE_TIME_COLUMN_INDEX = 9; const int32_t BOOT_BASED_DURATION_COLUMN_INDEX = 0; const int32_t SCREEN_ON_DURATION_COLUMN_INDEX = 1; const int32_t DURATION_FLAG_COLUMN_INDEX = 2; @@ -95,6 +97,7 @@ const int64_t ONE_YEAR_TIME = 365 * 24 * 60 * 60 * 1000LL; const int64_t LAST_TIME_IN_MILLIS_MIN = 0LL; const int64_t EVENT_TIME_IN_MILLIS_MIN = 0LL; const int64_t EVENT_BEGIN_TIME_INITIAL_VALUE = -1LL; +const int64_t MAX_END_TIME = 20000000000000; const std::string PACKAGE_LOG_TABLE = "PackageLog"; const std::string PACKAGE_LOG_TABLE_INDEX_PREFIX = "PackageLogIndex"; const std::string EVENT_LOG_TABLE = "DeviceEventLog"; @@ -131,8 +134,9 @@ const std::string BUNDLE_ACTIVE_DB_BUNDLE_ALIVE_TIMEOUT_TIME = "bundleAliveTimeo const std::string BUNDLE_ACTIVE_DB_BUNDLE_DAILY_TIMEOUT_TIME = "bundleDailyTimeoutTime"; const std::string BUNDLE_ACTIVE_DB_BOOT_BASED_DURATION = "bootBasedDuration"; const std::string BUNDLE_ACTIVE_DB_SCREEN_ON_DURATION = "screenOnDuration"; -const std::string RDB_STORE_COLUMN_TYPE_INT = "INTERGER"; +const std::string RDB_STORE_COLUMN_TYPE_INT = "INTEGER"; const std::string BUNDLE_ACTIVE_DB_UID = "uid"; +const std::string BUNDLE_ACTIVE_DB_FIRST_USE_TIME = "firstUseTime"; const std::string REFRESH_DATABASE_RUNNER_NAME = "RefreshDatabase"; const std::string BUNDLE_ACTIVE_DATABASE_DIR = "/data/service/el1/public/bundle_usage/"; diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 43d7640ebdb1da1dba49d5607b19fec13268b468..3c5f46a3690e784082b31f1db04f81a352ae66fa 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -218,9 +218,6 @@ public: // when service stop, call it to unregister commen event and shutdown call back. void UnRegisterSubscriber(); - // get system time in MS. - int64_t GetSystemTimeMs(); - /* * function: RegisterAppGroupCallBack, register the observer to groupObservers. * parameters: observer diff --git a/services/common/include/bundle_active_usage_database.h b/services/common/include/bundle_active_usage_database.h index 95427ae137941b48e0efcfeff692d7ecb7ef9108..b1439717c7fcd17d763beccf03ff02c69694ff97 100644 --- a/services/common/include/bundle_active_usage_database.h +++ b/services/common/include/bundle_active_usage_database.h @@ -110,7 +110,6 @@ private: void DeleteUninstalledInfo(const int32_t userId, const std::string& bundleName, const int32_t uid, const std::string& tableName, uint32_t databaseType, const int32_t appIndex); int32_t CreateDatabasePath(); - int64_t GetSystemTimeMs(); void CheckDatabaseFile(uint32_t databaseType); void UpdateFormData(const int32_t userId, const std::string bundleName, const std::string moduleName, const BundleActiveFormRecord& formRecord, @@ -137,12 +136,16 @@ private: int32_t GetVersionByFileInput(const std::string& FileVersionInput); void CreateRecordTable(const int64_t timeStamp); void HandleAllTableName(const uint32_t databaseType, std::vector>& allTableName); - void UpgradleDatabase(const int32_t oldVersion, const int32_t curVersion); + void UpgradeDatabase(const int32_t oldVersion, const int32_t curVersion); void UpdateOldDataUid(const std::shared_ptr store, const std::string& tableName, const int32_t userId, std::map& bundleNameUidMap); void SupportAppTwin(); void AddRdbColumn(const std::shared_ptr store, const std::string& tableName, const std::string& columnName, const std::string& columnType); + void SupportFirstUseTime(); + void UpdateFirstUseTime(const std::shared_ptr store, + const std::string& tableName, const int32_t userId); + std::map GetAllBundleFirstUseTime(const int32_t userId); std::vector databaseFiles_; std::vector> sortedTableArray_; std::map> bundleActiveRdbStoreCache_; diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 2212de01722eeec9deba783984f4815f8f8265c8..e1d0a08f4f6580d24bdcc156e096fd9b09b20510 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -246,10 +246,10 @@ void BundleActiveCore::Init() sptr timer = MiscServices::TimeServiceClient::GetInstance(); do { realTimeShot_ = timer->GetBootTimeMs(); - systemTimeShot_ = GetSystemTimeMs(); + systemTimeShot_ = BundleActiveUtil::GetSystemTimeMs(); } while (realTimeShot_ == -1 && systemTimeShot_ == -1); realTimeShot_ = timer->GetBootTimeMs(); - systemTimeShot_ = GetSystemTimeMs(); + systemTimeShot_ = BundleActiveUtil::GetSystemTimeMs(); BUNDLE_ACTIVE_LOGD("system time shot is %{public}lld", (long long)systemTimeShot_); bundleActiveConfigReader_ = std::make_shared(); bundleActiveConfigReader_->LoadConfig(); @@ -399,7 +399,7 @@ void BundleActiveCore::RestoreToDatabase(const int32_t userId) BUNDLE_ACTIVE_LOGD("RestoreToDatabase called"); BundleActiveEvent event; event.eventId_ = BundleActiveEvent::FLUSH; - event.timeStamp_ = GetSystemTimeMs(); + event.timeStamp_ = BundleActiveUtil::GetSystemTimeMs(); event.abilityId_ = ""; auto it = userStatServices_.find(userId); if (it != userStatServices_.end()) { @@ -482,7 +482,7 @@ int64_t WEAK_FUNC BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId { BUNDLE_ACTIVE_LOGD("CheckTimeChangeAndGetWallTime called, userId is %{public}d", userId); sptr timer = MiscServices::TimeServiceClient::GetInstance(); - int64_t actualSystemTime = GetSystemTimeMs(); + int64_t actualSystemTime = BundleActiveUtil::GetSystemTimeMs(); int64_t actualRealTime = timer->GetBootTimeMs(); int64_t expectedSystemTime = (actualRealTime - realTimeShot_) + systemTimeShot_; int64_t diffSystemTime = actualSystemTime - expectedSystemTime; @@ -774,7 +774,10 @@ bool BundleActiveCore::IsBundleUsePeriod(const std::string& bundleName, const in BUNDLE_ACTIVE_LOGI("IsBundleUsePeriod is not bundleInstalled"); return false; } - int64_t currentSystemTime = GetSystemTimeMs(); + if (BundleActiveGroupController::GetInstance().IsUsedOverOneWeek(bundleName, userId)) { + return true; + } + int64_t currentSystemTime = BundleActiveUtil::GetSystemTimeMs(); int64_t aWeekAgo = currentSystemTime - ONE_WEEK_TIME; int64_t startTime = BundleActiveUtil::GetIntervalTypeStartTime(aWeekAgo, BundleActiveUtil::PERIOD_DAILY); std::vector packageStats; @@ -808,24 +811,6 @@ void BundleActiveCore::GetAllActiveUser(std::vector& activatedOsAccount } } -int64_t BundleActiveCore::GetSystemTimeMs() -{ - time_t now; - (void)time(&now); // unit is seconds. - if (static_cast(now) < 0) { - BUNDLE_ACTIVE_LOGE("Get now time error"); - return 0; - } - auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now); - auto tarDuration = std::chrono::duration_cast(tarEndTimePoint.time_since_epoch()); - int64_t tarDate = tarDuration.count(); - if (tarDate < 0) { - BUNDLE_ACTIVE_LOGE("tarDuration is less than 0."); - return -1; - } - return static_cast(tarDate); -} - void BundleActiveCore::OnAppGroupChanged(const AppGroupCallbackInfo& callbackInfo) { std::shared_ptr bundleActiveCore = shared_from_this(); @@ -842,7 +827,7 @@ void BundleActiveCore::OnAppGroupChanged(const AppGroupCallbackInfo& callbackInf "UPDATE_GROUP_BUNDLENAME", callbackInfo.GetBundleName(), "UPDATE_GROUP_USERID", callbackInfo.GetUserId(), "UPDATE_GROUP_REASON", callbackInfo.GetChangeReason(), - "UPDATE_GROUP_TIME", GetSystemTimeMs(), + "UPDATE_GROUP_TIME", BundleActiveUtil::GetSystemTimeMs(), "UPDATE_GROUP_OLD_GROUP", callbackInfo.GetOldGroup(), "UPDATE_GROUP_NEW_GROUP", callbackInfo.GetNewGroup()); } diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index 0104f5cf73c4aa421e58525271ccadcb575c019d..e8c4e778eb816258c184160cefa03f0d083d73de 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -35,6 +35,7 @@ #include "bundle_active_account_helper.h" #include "hisysevent.h" #include "bundle_active_core.h" +#include "bundle_active_util.h" namespace OHOS { namespace DeviceUsageStats { using namespace OHOS::NativeRdb; @@ -43,7 +44,6 @@ namespace { const int32_t MAX_FILES_EVERY_INTERVAL_TYPE[SORTED_TABLE_ARRAY_NUMBER] = {30, 30, 12, 10}; const int32_t MAIN_APP_INDEX = 0; const int32_t FILE_VERSION_LINE_NUM = 50; - const int64_t MAX_END_TIME = 20000000000000; static constexpr char RSS[] = "RSS"; } BundleActiveUsageDatabase::BundleActiveUsageDatabase() @@ -138,12 +138,12 @@ int32_t BundleActiveUsageDatabase::CreateDatabasePath() void BundleActiveUsageDatabase::InitDatabaseTableInfo(int64_t currentTime) { - lock_guard lock(databaseMutex_); if (CreateDatabasePath() == BUNDLE_ACTIVE_FAIL) { BUNDLE_ACTIVE_LOGE("database path is not exist"); return; } CheckDatabaseVersion(); + lock_guard lock(databaseMutex_); for (uint32_t i = 0; i < databaseFiles_.size(); i++) { HandleTableInfo(i); DeleteExcessiveTableData(i); @@ -448,7 +448,7 @@ void BundleActiveUsageDatabase::CheckDatabaseVersion() if (access(BUNDLE_ACTIVE_DATABASE_DIR.c_str(), F_OK) == 0) { int32_t oldVersion = GetOldDbVersion(); if (oldVersion != BUNDLE_ACTIVE_FAIL && oldVersion < BUNDLE_ACTIVE_CURRENT_VERSION) { - UpgradleDatabase(oldVersion, BUNDLE_ACTIVE_CURRENT_VERSION); + UpgradeDatabase(oldVersion, BUNDLE_ACTIVE_CURRENT_VERSION); } std::string fileVersion = "version : " + std::to_string(BUNDLE_ACTIVE_CURRENT_VERSION); SaveStringToFile(BUNDLE_ACTIVE_VERSION_DIRECTORY_PATH, fileVersion, true); @@ -483,93 +483,6 @@ int32_t BundleActiveUsageDatabase::GetVersionByFileInput(const std::string& File return atoi(databaseVersion.c_str()); } -void BundleActiveUsageDatabase::UpgradleDatabase(const int32_t oldVersion, const int32_t curVersion) -{ - BUNDLE_ACTIVE_LOGI("upgradle database oldVersion: %{public}d, curVersion: %{public}d", oldVersion, curVersion); - if (oldVersion < curVersion && curVersion == BUNDLE_ACTIVE_CURRENT_VERSION) { - if (oldVersion == BUNDLE_ACTIVE_VERSION_V1) { - SupportAppTwin(); - } - } -} - -void BundleActiveUsageDatabase::SupportAppTwin() -{ - vector> allTableName = vector>(ALL_TABLE_ARRAY_NUMBER); - for (uint32_t i = 0; i bundleNameUidMap; - vector activatedOsAccountIds; - BundleActiveAccountHelper::GetActiveUserId(activatedOsAccountIds); - for (uint32_t i = 0; i < allTableName.size(); i++) { - auto tableNames = allTableName.at(i); - shared_ptr rdbStore = GetBundleActiveRdbStore(i); - if (!rdbStore) { - BUNDLE_ACTIVE_LOGI("get RdbStore fail, databaseType: %{public}u", i); - continue; - } - for (string tableName: tableNames) { - if (DURATION_LOG_TABLE == tableName) { - continue; - } - AddRdbColumn(rdbStore, tableName, BUNDLE_ACTIVE_DB_UID, RDB_STORE_COLUMN_TYPE_INT); - for (auto userId: activatedOsAccountIds) { - UpdateOldDataUid(rdbStore, tableName, userId, bundleNameUidMap); - } - } - } -} - -void BundleActiveUsageDatabase::AddRdbColumn(const shared_ptr store, - const string& tableName, const string& columnName, const string& columnType) -{ - string sqlStr = ""; - if (columnType == RDB_STORE_COLUMN_TYPE_INT) { - sqlStr = "ALTER TABLE " + tableName + " ADD " + columnName + " " + columnType + " NOT NULL DEFAULT -1"; - } - store->ExecuteSql(sqlStr); -} - -void BundleActiveUsageDatabase::UpdateOldDataUid(const shared_ptr store, - const string& tableName, const int32_t userId, map& bundleNameUidMap) -{ - vector queryCondition; - string querySql = "select * from " + tableName; - shared_ptr bundleActiveResult; - bundleActiveResult = store->QueryByStep(querySql); - int32_t tableRowNumber = 0; - bundleActiveResult->GetRowCount(tableRowNumber); - string bundleName; - int32_t uid; - int32_t changeRow = BUNDLE_ACTIVE_FAIL; - NativeRdb::ValuesBucket valuesBucket; - for (int32_t i = 0; i < tableRowNumber; i++) { - bundleActiveResult->GoToRow(i); - bundleActiveResult->GetString(BUNDLE_NAME_COLUMN_INDEX, bundleName); - AppExecFwk::ApplicationInfo appInfo; - string bundleNameUserIdKey = bundleName + to_string(userId); - auto it = bundleNameUidMap.find(bundleNameUserIdKey); - if (it == bundleNameUidMap.end()) { - BundleActiveBundleMgrHelper::GetInstance()->GetApplicationInfo(bundleName, - AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); - uid = appInfo.uid; - bundleNameUidMap[bundleNameUserIdKey] = uid; - } else { - uid = it->second; - } - queryCondition.push_back(to_string(userId)); - queryCondition.push_back(bundleName); - valuesBucket.PutInt(BUNDLE_ACTIVE_DB_UID, uid); - store->Update(changeRow, tableName, valuesBucket, "userId = ? and bundleName = ?", queryCondition); - queryCondition.clear(); - valuesBucket.Clear(); - changeRow = BUNDLE_ACTIVE_FAIL; - } - bundleActiveResult->Close(); -} - shared_ptr WEAK_FUNC BundleActiveUsageDatabase::GetBundleActiveRdbStore(uint32_t databaseType) { shared_ptr rdbStore; @@ -809,7 +722,9 @@ int32_t BundleActiveUsageDatabase::CreateBundleHistoryTable(uint32_t databaseTyp + BUNDLE_ACTIVE_DB_REASON_IN_GROUP + " INTEGER NOT NULL, " + BUNDLE_ACTIVE_DB_BUNDLE_ALIVE_TIMEOUT_TIME + " INTEGER NOT NULL, " + BUNDLE_ACTIVE_DB_BUNDLE_DAILY_TIMEOUT_TIME + " INTEGER NOT NULL, " - + BUNDLE_ACTIVE_DB_UID + " INTEGER NOT NULL DEFAULT -1);"; + + BUNDLE_ACTIVE_DB_UID + " INTEGER NOT NULL DEFAULT -1, " + + BUNDLE_ACTIVE_DB_FIRST_USE_TIME + " INTEGER NOT NULL DEFAULT " + + std::to_string(MAX_END_TIME) + ");"; int32_t createBundleHistoryTable = rdbStore->ExecuteSql(createBundleHistoryTableSql); if (createBundleHistoryTable != NativeRdb::E_OK) { BUNDLE_ACTIVE_LOGE("create bundleHistory table failed, rdb error number: %{public}d", createBundleHistoryTable); @@ -866,6 +781,7 @@ void BundleActiveUsageDatabase::PutBundleHistoryData(int32_t userId, valuesBucket.PutInt(BUNDLE_ACTIVE_DB_REASON_IN_GROUP, static_cast(iter->second->reasonInGroup_)); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_BUNDLE_ALIVE_TIMEOUT_TIME, iter->second->bundleAliveTimeoutTimeStamp_); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_BUNDLE_DAILY_TIMEOUT_TIME, iter->second->bundleDailyTimeoutTimeStamp_); + valuesBucket.PutLong(BUNDLE_ACTIVE_DB_FIRST_USE_TIME, iter->second->bundlefirstUseTimeStamp_); rdbStore->Update(changeRow, BUNDLE_HISTORY_LOG_TABLE, valuesBucket, "userId = ? and bundleName = ? and uid = ?", queryCondition); if (changeRow == NO_UPDATE_ROW) { @@ -931,6 +847,8 @@ shared_ptr>> BundleActiveUsag bundleActiveResult->GetLong(BUNDLE_DAILY_TIMEOUT_TIME_COLUMN_INDEX, usageHistory->bundleDailyTimeoutTimeStamp_); bundleActiveResult->GetInt(BUNDLE_HISTORY_LOG_UID_COLUMN_INDEX, usageHistory->uid_); + bundleActiveResult->GetLong(BUNDLE_HISTORY_LOG_FIRST_USE_TIME_COLUMN_INDEX, + usageHistory->bundlefirstUseTimeStamp_); string usageHistoryKey = usageHistory->bundleName_ + to_string(usageHistory->uid_); userUsageHistory->insert(pair>(usageHistoryKey, usageHistory)); @@ -1058,7 +976,7 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa if (databaseType == DAILY_DATABASE_INDEX) { eventBeginTime_ = currentPackageTime; } - int64_t systemTime = GetSystemTimeMs(); + int64_t systemTime = BundleActiveUtil::GetSystemTimeMs(); intervalStats->lastTimeSaved_ = systemTime; return intervalStats; } @@ -1410,7 +1328,7 @@ void BundleActiveUsageDatabase::UpdateBundleUsageData(int32_t databaseType, Bund "UPDATE_BUNDLE_USAGE_EVENT_SIZE", stats.events_.Size(), "UPDATE_BUNDLE_USAGE_STATS_SIZE", stats.bundleStats_.size() - bundleStatsSize, "UPDATE_BUNDLE_USAGE_USERID", stats.userId_, - "UPDATE_BUNDLE_USAGE_TIME", bundleActiveCore->GetSystemTimeMs()); + "UPDATE_BUNDLE_USAGE_TIME", BundleActiveUtil::GetSystemTimeMs()); } lock_guard lock(databaseMutex_); if (databaseType < 0 || databaseType >= EVENT_DATABASE_INDEX) { @@ -1431,7 +1349,7 @@ void BundleActiveUsageDatabase::UpdateBundleUsageData(int32_t databaseType, Bund DeleteExcessiveTableData(databaseType); } FlushPackageInfo(databaseType, stats); - int64_t systemTime = GetSystemTimeMs(); + int64_t systemTime = BundleActiveUtil::GetSystemTimeMs(); stats.lastTimeSaved_ = systemTime; } @@ -1658,24 +1576,6 @@ void BundleActiveUsageDatabase::DeleteUninstalledInfo(const int32_t userId, cons rdbStore->Delete(deletedRows, tableName, "userId = ? and bundleName = ? and uid = ?", queryCondition); } -int64_t BundleActiveUsageDatabase::GetSystemTimeMs() -{ - time_t now; - (void)time(&now); // unit is seconds. - if (static_cast(now) < 0) { - BUNDLE_ACTIVE_LOGE("Get now time error"); - return 0; - } - auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now); - auto tarDuration = std::chrono::duration_cast(tarEndTimePoint.time_since_epoch()); - int64_t tarDate = tarDuration.count(); - if (tarDate < 0) { - BUNDLE_ACTIVE_LOGE("tarDuration is less than 0."); - return -1; - } - return static_cast(tarDate); -} - void BundleActiveUsageDatabase::UpdateModuleData(const int32_t userId, std::map>& moduleRecords, const int64_t timeStamp) { diff --git a/services/common/src/bundle_active_usage_database_upgrade.cpp b/services/common/src/bundle_active_usage_database_upgrade.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c53391997489e1b92239b7719e6bfe5b446da2c --- /dev/null +++ b/services/common/src/bundle_active_usage_database_upgrade.cpp @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2022-2025 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 +#include +#include +#include +#include "bundle_active_constant.h" +#include "bundle_active_log.h" +#include "bundle_active_package_stats.h" +#include "bundle_active_period_stats.h" +#include "bundle_active_usage_database.h" +#include "bundle_active_account_helper.h" +#include "bundle_active_bundle_mgr_helper.h" +#include "bundle_active_util.h" + +namespace OHOS { +namespace DeviceUsageStats { +using namespace OHOS::NativeRdb; +using namespace std; +namespace { + const int64_t MIN_START_TIME = 0; +} +void BundleActiveUsageDatabase::UpgradeDatabase(const int32_t oldVersion, const int32_t curVersion) +{ + BUNDLE_ACTIVE_LOGI("upgradle database oldVersion: %{public}d, curVersion: %{public}d", oldVersion, curVersion); + if (oldVersion < curVersion && curVersion == BUNDLE_ACTIVE_CURRENT_VERSION) { + if (oldVersion == BUNDLE_ACTIVE_VERSION_V1) { + SupportAppTwin(); + SupportFirstUseTime(); + } + if (oldVersion == BUNDLE_ACTIVE_VERSION_V2) { + SupportFirstUseTime(); + } + currentVersion_ = curVersion; + } +} + +void BundleActiveUsageDatabase::SupportAppTwin() +{ + vector> allTableName = vector>(ALL_TABLE_ARRAY_NUMBER); + for (uint32_t i = 0; i bundleNameUidMap; + vector activatedOsAccountIds; + BundleActiveAccountHelper::GetActiveUserId(activatedOsAccountIds); + for (uint32_t i = 0; i < allTableName.size(); i++) { + auto tableNames = allTableName.at(i); + shared_ptr rdbStore = GetBundleActiveRdbStore(i); + if (!rdbStore) { + BUNDLE_ACTIVE_LOGI("get RdbStore fail, databaseType: %{public}u", i); + continue; + } + for (string tableName: tableNames) { + if (DURATION_LOG_TABLE == tableName) { + continue; + } + AddRdbColumn(rdbStore, tableName, BUNDLE_ACTIVE_DB_UID, RDB_STORE_COLUMN_TYPE_INT); + for (auto userId: activatedOsAccountIds) { + UpdateOldDataUid(rdbStore, tableName, userId, bundleNameUidMap); + } + } + } +} + +void BundleActiveUsageDatabase::SupportFirstUseTime() +{ + shared_ptr rdbStore = GetBundleActiveRdbStore(APP_GROUP_DATABASE_INDEX); + if (!rdbStore) { + BUNDLE_ACTIVE_LOGE("get RdbStore fail, databaseType: %{public}u", APP_GROUP_DATABASE_INDEX); + return; + } + vector> allTableName = vector>(ALL_TABLE_ARRAY_NUMBER); + { + lock_guard lock(databaseMutex_); + for (uint32_t i = 0; i < databaseFiles_.size(); i++) { + HandleTableInfo(i); + } + HandleAllTableName(APP_GROUP_DATABASE_INDEX, allTableName); + } + auto it = std::find(allTableName.at(APP_GROUP_DATABASE_INDEX).begin(), + allTableName.at(APP_GROUP_DATABASE_INDEX).end(), BUNDLE_HISTORY_LOG_TABLE); + if (it == allTableName.at(APP_GROUP_DATABASE_INDEX).end()) { + BUNDLE_ACTIVE_LOGE("not have bundle history table"); + return; + } + vector activatedOsAccountIds; + BundleActiveAccountHelper::GetActiveUserId(activatedOsAccountIds); + { + lock_guard lock(databaseMutex_); + AddRdbColumn(rdbStore, BUNDLE_HISTORY_LOG_TABLE, BUNDLE_ACTIVE_DB_FIRST_USE_TIME, RDB_STORE_COLUMN_TYPE_INT); + } + for (auto userId: activatedOsAccountIds) { + UpdateFirstUseTime(rdbStore, BUNDLE_HISTORY_LOG_TABLE, userId); + } +} + +void BundleActiveUsageDatabase::AddRdbColumn(const shared_ptr store, + const string& tableName, const string& columnName, const string& columnType) +{ + if (columnType != RDB_STORE_COLUMN_TYPE_INT) { + return; + } + string sqlStr = ""; + sqlStr = "ALTER TABLE " + tableName + " ADD " + columnName + " " + columnType; + if (columnName == BUNDLE_ACTIVE_DB_UID) { + sqlStr += " NOT NULL DEFAULT -1"; + } + if (columnName == BUNDLE_ACTIVE_DB_FIRST_USE_TIME) { + sqlStr += " NOT NULL DEFAULT " + std::to_string(MAX_END_TIME); + } + auto ret = store->ExecuteSql(sqlStr); + if (ret != E_OK) { + BUNDLE_ACTIVE_LOGE("add column failed columnName %{public}s", columnName.c_str()); + } +} + +void BundleActiveUsageDatabase::UpdateOldDataUid(const shared_ptr store, + const string& tableName, const int32_t userId, map& bundleNameUidMap) +{ + vector queryCondition; + string querySql = "select * from " + tableName; + shared_ptr bundleActiveResult; + bundleActiveResult = store->QueryByStep(querySql); + int32_t tableRowNumber = 0; + bundleActiveResult->GetRowCount(tableRowNumber); + string bundleName; + int32_t uid; + int32_t changeRow = BUNDLE_ACTIVE_FAIL; + NativeRdb::ValuesBucket valuesBucket; + for (int32_t i = 0; i < tableRowNumber; i++) { + bundleActiveResult->GoToRow(i); + bundleActiveResult->GetString(BUNDLE_NAME_COLUMN_INDEX, bundleName); + AppExecFwk::ApplicationInfo appInfo; + string bundleNameUserIdKey = bundleName + to_string(userId); + auto it = bundleNameUidMap.find(bundleNameUserIdKey); + if (it == bundleNameUidMap.end()) { + BundleActiveBundleMgrHelper::GetInstance()->GetApplicationInfo(bundleName, + AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); + uid = appInfo.uid; + bundleNameUidMap[bundleNameUserIdKey] = uid; + } else { + uid = it->second; + } + queryCondition.push_back(to_string(userId)); + queryCondition.push_back(bundleName); + valuesBucket.PutInt(BUNDLE_ACTIVE_DB_UID, uid); + store->Update(changeRow, tableName, valuesBucket, "userId = ? and bundleName = ?", queryCondition); + queryCondition.clear(); + valuesBucket.Clear(); + changeRow = BUNDLE_ACTIVE_FAIL; + } + bundleActiveResult->Close(); +} + +void BundleActiveUsageDatabase::UpdateFirstUseTime(const shared_ptr store, + const string& tableName, const int32_t userId) +{ + map allBundleFirstUseTime = GetAllBundleFirstUseTime(userId); + lock_guard lock(databaseMutex_); + vector queryCondition; + string querySql = "select * from " + tableName; + shared_ptr bundleActiveResult; + bundleActiveResult = store->QueryByStep(querySql); + int32_t tableRowNumber = 0; + bundleActiveResult->GetRowCount(tableRowNumber); + int32_t uid; + string bundleName; + int32_t changeRow = BUNDLE_ACTIVE_FAIL; + int64_t firstUseTime = MAX_END_TIME; + NativeRdb::ValuesBucket valuesBucket; + for (int32_t i = 0; i < tableRowNumber; i++) { + bundleActiveResult->GoToRow(i); + bundleActiveResult->GetInt(BUNDLE_HISTORY_LOG_UID_COLUMN_INDEX, uid); + bundleActiveResult->GetString(BUNDLE_NAME_COLUMN_INDEX, bundleName); + string bundleUidKey = BundleActiveUtil::GetBundleUsageKey(bundleName, uid); + auto it = allBundleFirstUseTime.find(bundleUidKey); + if (it != allBundleFirstUseTime.end()) { + firstUseTime = it->second; + } + queryCondition.push_back(to_string(userId)); + queryCondition.push_back(bundleName); + queryCondition.push_back(to_string(uid)); + valuesBucket.PutLong(BUNDLE_ACTIVE_DB_FIRST_USE_TIME, firstUseTime); + store->Update(changeRow, tableName, valuesBucket, "userId = ? and bundleName = ? and uid = ?", queryCondition); + queryCondition.clear(); + valuesBucket.Clear(); + changeRow = BUNDLE_ACTIVE_FAIL; + } + bundleActiveResult->Close(); +} + +map BundleActiveUsageDatabase::GetAllBundleFirstUseTime(const int32_t userId) +{ + vector events = QueryDatabaseEvents(MIN_START_TIME, MAX_END_TIME, userId, ""); + map allBundleFirstUseTime; + for (auto event : events) { + string bundleUidKey = BundleActiveUtil::GetBundleUsageKey(event.bundleName_, event.uid_); + auto it = allBundleFirstUseTime.find(bundleUidKey); + if (it == allBundleFirstUseTime.end()) { + allBundleFirstUseTime[bundleUidKey] = event.timeStamp_; + continue; + } + allBundleFirstUseTime[bundleUidKey] = std::min(allBundleFirstUseTime[bundleUidKey], event.timeStamp_); + } + + vector packageStatsVector = QueryDatabaseUsageStats(YEARLY_DATABASE_INDEX, + MIN_START_TIME, MAX_END_TIME, userId, ""); + for (auto packageStats : packageStatsVector) { + string bundleUidKey = BundleActiveUtil::GetBundleUsageKey(packageStats.bundleName_, packageStats.uid_); + auto it = allBundleFirstUseTime.find(bundleUidKey); + if (it == allBundleFirstUseTime.end()) { + allBundleFirstUseTime[bundleUidKey] = packageStats.lastTimeUsed_; + continue; + } + allBundleFirstUseTime[bundleUidKey] = std::min(allBundleFirstUseTime[bundleUidKey], packageStats.lastTimeUsed_); + } + return allBundleFirstUseTime; +} +} // namespace DeviceUsageStats +} // namespace OHOS + \ No newline at end of file diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index ed69f48d015f9ff847e96cb7aa359eddf4ce7e8f..8e338a3d6977904da4eaf449eaddce82c459677b 100644 --- a/services/packagegroup/include/bundle_active_group_controller.h +++ b/services/packagegroup/include/bundle_active_group_controller.h @@ -85,6 +85,7 @@ public: void OnUserSwitched(const int32_t userId, const int32_t currentUsedUser); void SetBundleGroupEnable(bool bundleGroupEnable); bool GetBundleGroupEnable(); + bool IsUsedOverOneWeek(const std::string& bundleName, const int32_t userId); std::shared_ptr GetBundleGroupHandler(); private: BundleActiveGroupController() = default; diff --git a/services/packagegroup/include/bundle_active_package_history.h b/services/packagegroup/include/bundle_active_package_history.h index df59df968d8f3d7ec12902081238848828407b07..77d5e754efa45e6e7f839ad90d7e034571567691 100644 --- a/services/packagegroup/include/bundle_active_package_history.h +++ b/services/packagegroup/include/bundle_active_package_history.h @@ -32,6 +32,7 @@ public: uint32_t reasonInGroup_; int64_t bundleAliveTimeoutTimeStamp_; int64_t bundleDailyTimeoutTimeStamp_; + int64_t bundlefirstUseTimeStamp_; bool isChanged_; BundleActivePackageHistory(); ~BundleActivePackageHistory() {} diff --git a/services/packagegroup/include/bundle_active_user_history.h b/services/packagegroup/include/bundle_active_user_history.h index 761a043a14601dfb5e55bd72badba1136c019ae6..2591389da6ce69493b577fb6d70af79b6ec6ee22 100644 --- a/services/packagegroup/include/bundle_active_user_history.h +++ b/services/packagegroup/include/bundle_active_user_history.h @@ -49,9 +49,9 @@ public: int64_t bootBasedTimeStamp, bool create, const int32_t uid); int64_t GetBootBasedTimeStamp(int64_t bootBasedTimeStamp); int64_t GetScreenOnTimeStamp(int64_t bootBasedTimeStamp); - void ReportUsage(std::shared_ptr oneBundleUsageHistory, const std::string& bundleName, + void ReportUsage(std::shared_ptr oneBundleUsageHistory, const BundleActiveEvent& event, const int32_t newGroup, const uint32_t groupReason, const int64_t bootBasedTimeStamp, - const int64_t timeUntilNextCheck, const int32_t userId, const int32_t uid); + const int64_t timeUntilNextCheck, const int32_t userId); int32_t SetAppGroup(const std::string& bundleName, const int32_t userId, const int32_t uid, int64_t bootBasedTimeStamp, int32_t newGroup, uint32_t groupReason, const bool isFlush); int32_t GetLevelIndex(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, @@ -63,6 +63,7 @@ public: const bool& isShutdown = false); void OnBundleUninstalled(const int32_t userId, const std::string bundleName, const int32_t uid, const int32_t appIndex); + int64_t GetFirstUseTime(const std::string& bundleName, const int32_t userId); private: ffrt::mutex setGroupMutex_; diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index a62e31188ba30ff57cd06ccf659b06a26d20c1ff..787c77214a48f0b006e4a0d9ed0649c2d612c033 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -268,20 +268,20 @@ void BundleActiveGroupController::ReportEvent(const BundleActiveEvent& event, co int32_t checkBundleMsgEventId = BundleActiveGroupHandler::MSG_CHECK_DEFAULT_BUNDLE_STATE; switch (eventId) { case BundleActiveEvent::NOTIFICATION_SEEN: - bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_DAILY, - eventReason, 0, bootBasedTimeStamp + timeoutForNotifySeen_, userId, event.uid_); + bundleUserHistory_->ReportUsage(bundleUsageHistory, event, ACTIVE_GROUP_DAILY, + eventReason, 0, bootBasedTimeStamp + timeoutForNotifySeen_, userId); timeUntilNextCheck = timeoutForNotifySeen_; checkBundleMsgEventId = BundleActiveGroupHandler::MSG_CHECK_NOTIFICATION_SEEN_BUNDLE_STATE; break; case BundleActiveEvent::SYSTEM_INTERACTIVE: - bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_ALIVE, - eventReason, 0, bootBasedTimeStamp + timeoutForSystemInteraction_, userId, event.uid_); + bundleUserHistory_->ReportUsage(bundleUsageHistory, event, ACTIVE_GROUP_ALIVE, + eventReason, 0, bootBasedTimeStamp + timeoutForSystemInteraction_, userId); timeUntilNextCheck = timeoutForSystemInteraction_; checkBundleMsgEventId = BundleActiveGroupHandler::MSG_CHECK_SYSTEM_INTERACTIVE_BUNDLE_STATE; break; default: - bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_ALIVE, - eventReason, bootBasedTimeStamp, bootBasedTimeStamp + timeoutForDirectlyUse_, userId, event.uid_); + bundleUserHistory_->ReportUsage(bundleUsageHistory, event, ACTIVE_GROUP_ALIVE, + eventReason, bootBasedTimeStamp, bootBasedTimeStamp + timeoutForDirectlyUse_, userId); timeUntilNextCheck = timeoutForDirectlyUse_; break; } @@ -474,6 +474,21 @@ bool BundleActiveGroupController::IsScreenOn() BUNDLE_ACTIVE_LOGI("IsScreenOn() is %{public}d", result); return result; } +bool BundleActiveGroupController::IsUsedOverOneWeek(const std::string& bundleName, const int32_t userId) +{ + if (bundleUserHistory_ == nullptr) { + return false; + } + int64_t firstUseTime = bundleUserHistory_->GetFirstUseTime(bundleName, userId); + if (firstUseTime == MAX_END_TIME) { + return false; + } + int64_t curTime = BundleActiveUtil::GetSystemTimeMs(); + if (curTime < 0 || curTime - firstUseTime > ONE_WEEK_TIME) { + return false; + } + return true; +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packagegroup/src/bundle_active_user_history.cpp b/services/packagegroup/src/bundle_active_user_history.cpp index 729417e5febea7ea99e83ccf1795c0e536142512..cfe483645f9e24018d624939b3b4a21ceb3d8808 100644 --- a/services/packagegroup/src/bundle_active_user_history.cpp +++ b/services/packagegroup/src/bundle_active_user_history.cpp @@ -36,6 +36,7 @@ BundleActivePackageHistory::BundleActivePackageHistory() uid_ = 0; lastCalculatedGroup_ = ACTIVE_GROUP_NEVER; isChanged_ = false; + bundlefirstUseTimeStamp_ = MAX_END_TIME; }; void BundleActiveUserHistory::WriteDeviceDuration() @@ -156,6 +157,7 @@ shared_ptr BundleActiveUserHistory::GetUsageHistoryI usageHistoryInserted->bundleAliveTimeoutTimeStamp_ = 0; usageHistoryInserted->bundleDailyTimeoutTimeStamp_ = 0; usageHistoryInserted->uid_ = uid; + usageHistoryInserted->bundlefirstUseTimeStamp_ = INT64_MAX; (*oneUserHistory)[userHistoryKey] = usageHistoryInserted; } return (*oneUserHistory)[userHistoryKey]; @@ -177,9 +179,13 @@ shared_ptr BundleActiveUserHistory::GetUsageHistoryF } void BundleActiveUserHistory::ReportUsage(shared_ptr oneBundleUsageHistory, - const string& bundleName, const int32_t newGroup, const uint32_t groupReason, const int64_t bootBasedTimeStamp, - const int64_t timeUntilNextCheck, const int32_t userId, const int32_t uid) + const BundleActiveEvent& event, const int32_t newGroup, const uint32_t groupReason, + const int64_t bootBasedTimeStamp, const int64_t timeUntilNextCheck, const int32_t userId) { + string bundleName = event.bundleName_; + int32_t uid = event.uid_; + oneBundleUsageHistory->bundlefirstUseTimeStamp_ = + std::min(oneBundleUsageHistory->bundlefirstUseTimeStamp_, event.timeStamp_); if ((oneBundleUsageHistory->reasonInGroup_ & GROUP_CONTROL_REASON_MASK) == GROUP_CONTROL_REASON_FORCED) { return; } @@ -292,6 +298,23 @@ void BundleActiveUserHistory::PrintData(int32_t userId) (long long)oneBundleUsage.second->bundleAliveTimeoutTimeStamp_); } } + +int64_t BundleActiveUserHistory::GetFirstUseTime(const std::string& bundleName, const int32_t userId) +{ + int64_t firstUseTime = MAX_END_TIME; + auto userHistory = GetUserHistory(userId, false); + if (userHistory == nullptr) { + BUNDLE_ACTIVE_LOGI("WriteBundleUsage called, no existed user history, return"); + return firstUseTime; + } + for (auto packageHistoryIter : *userHistory) { + if (packageHistoryIter.first.find(bundleName) == std::string::npos || packageHistoryIter.second == nullptr) { + continue; + } + firstUseTime = std::min(firstUseTime, packageHistoryIter.second->bundlefirstUseTimeStamp_); + } + return firstUseTime; +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/test/unittest/bundle_active_usage_database_test.cpp b/test/unittest/bundle_active_usage_database_test.cpp index 1be5d8429d0325d669664760e085f9f5a986d367..6baab04936e182cd57c97810671cad3bf6eae7ff 100644 --- a/test/unittest/bundle_active_usage_database_test.cpp +++ b/test/unittest/bundle_active_usage_database_test.cpp @@ -20,6 +20,7 @@ #include "bundle_active_usage_database.h" #include "bundle_active_util.h" +#include "bundle_active_constant.h" using namespace testing::ext; @@ -150,22 +151,49 @@ HWTEST_F(BundleActiveUsageDatabaseTest, BundleActiveUsageDatabaseTest_GetVersion } /* - * @tc.name: BundleActiveUsageDatabaseTest_UpgradleDatabase_001 - * @tc.desc: UpgradleDatabase + * @tc.name: BundleActiveUsageDatabaseTest_UpgradeDatabase_001 + * @tc.desc: UpgradeDatabase * @tc.type: FUNC * @tc.require: issuesI9Q9ZJ */ -HWTEST_F(BundleActiveUsageDatabaseTest, BundleActiveUsageDatabaseTest_UpgradleDatabase_001, +HWTEST_F(BundleActiveUsageDatabaseTest, BundleActiveUsageDatabaseTest_UpgradeDatabase_001, Function | MediumTest | Level0) { auto database = std::make_shared(); + database->currentVersion_ = 0; int32_t oldVersion = 1; int32_t curVersion = 2; - database->UpgradleDatabase(oldVersion, curVersion); + database->UpgradeDatabase(oldVersion, curVersion); + oldVersion = 2; - curVersion = 2; - database->UpgradleDatabase(oldVersion, curVersion); - EXPECT_NE(database, nullptr); + curVersion = 3; + database->UpgradeDatabase(oldVersion, curVersion); + EXPECT_EQ(database->currentVersion_, curVersion); +} + +/* + * @tc.name: BundleActiveUsageDatabaseTest_UpgradeDatabase_001 + * @tc.desc: UpgradeDatabase + * @tc.type: FUNC + * @tc.require: issuesI9Q9ZJ + */ +HWTEST_F(BundleActiveUsageDatabaseTest, BundleActiveUsageDatabaseTest_UpgradeDatabase_002, + Function | MediumTest | Level0) +{ + auto database = std::make_shared(); + database->currentVersion_ = 0; + int32_t oldVersion = 1; + int32_t curVersion = 3; + database->UpgradeDatabase(oldVersion, curVersion); + EXPECT_EQ(database->currentVersion_, curVersion); + database->currentVersion_ = 0; + oldVersion = 2; + curVersion = 3; + database->UpgradeDatabase(oldVersion, curVersion); + EXPECT_EQ(database->currentVersion_, curVersion); + oldVersion = 3; + database->UpgradeDatabase(oldVersion, curVersion); + EXPECT_EQ(database->currentVersion_, curVersion); } /* @@ -249,5 +277,35 @@ HWTEST_F(BundleActiveUsageDatabaseTest, BundleActiveUsageDatabaseTest_CreateReco int64_t resultInt64 = BundleActiveUtil::StringToInt64("11"); EXPECT_EQ(resultInt64, 11); } + +/* + * @tc.name: BundleActiveUsageDatabaseTest_SupportFirstUseTime_001 + * @tc.desc: SupportFirstUseTime + * @tc.type: FUNC + * @tc.require: issuesICCZ27 + */ +HWTEST_F(BundleActiveUsageDatabaseTest, SupportFirstUseTime_001, + Function | MediumTest | Level0) +{ + auto database = std::make_shared(); + + database->SupportFirstUseTime(); + EXPECT_NE(database, nullptr); +} + +/* + * @tc.name: BundleActiveUsageDatabaseTest_UpdateFirstUseTime_002 + * @tc.desc: UpdateFirstUseTime + * @tc.type: FUNC + * @tc.require: issuesICCZ27 + */ +HWTEST_F(BundleActiveUsageDatabaseTest, UpdateFirstUseTime_002, + Function | MediumTest | Level0) +{ + auto database = std::make_shared(); + auto rdb = database->GetBundleActiveRdbStore(APP_GROUP_DATABASE_INDEX); + database->UpdateFirstUseTime(rdb, BUNDLE_HISTORY_LOG_TABLE, 100); + EXPECT_NE(database, nullptr); +} } // namespace DeviceUsageStats } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/device_usage_statistics_service_test.cpp b/test/unittest/device_usage_statistics_service_test.cpp index 2f567aa2fed2baee4a433239363a884adbc9d357..4a884222de4507bd898916eae9d49677a0f1af46 100644 --- a/test/unittest/device_usage_statistics_service_test.cpp +++ b/test/unittest/device_usage_statistics_service_test.cpp @@ -34,6 +34,8 @@ #include "nativetoken_kit.h" #include "bundle_active_report_controller.h" #include "bundle_active_test_util.h" +#include "bundle_active_util.h" +#include "bundle_active_constant.h" using namespace testing::ext; @@ -679,20 +681,6 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Quer EXPECT_NE(database, nullptr); } -/* - * @tc.name: DeviceUsageStatisticsServiceTest_GetSystemTimeMs_001 - * @tc.desc: GetSystemTimeMs - * @tc.type: FUNC - * @tc.require: issuesI5SOZY - */ -HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_GetSystemTimeMs_001, - Function | MediumTest | Level0) -{ - auto database = std::make_shared(); - database->GetSystemTimeMs(); - EXPECT_NE(database, nullptr); -} - /* * @tc.name: DeviceUsageStatisticsServiceTest_ReportEvent_001 * @tc.desc: ReportEvent @@ -1029,15 +1017,16 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveUserHistoryTest_003, int64_t bootBasedTimeStamp = 2000; auto oneBundleUsageHistory = std::make_shared(); auto bundleUserHistory_ = std::make_shared(bootBasedTimeStamp, bundleActiveCore_); - bundleUserHistory_->ReportUsage(oneBundleUsageHistory, "test", 0, 0, 1000, 2000, 100, 0); + BundleActiveEvent event; + bundleUserHistory_->ReportUsage(oneBundleUsageHistory, event, 0, 0, 1000, 2000, 100); SUCCEED(); - bundleUserHistory_->ReportUsage(oneBundleUsageHistory, "test", 0, 0, 2000, 1000, 100, 0); + bundleUserHistory_->ReportUsage(oneBundleUsageHistory, event, 0, 0, 2000, 1000, 100); SUCCEED(); - bundleUserHistory_->ReportUsage(oneBundleUsageHistory, "test", 10, 0, 1000, 2000, 100, 0); + bundleUserHistory_->ReportUsage(oneBundleUsageHistory, event, 10, 0, 1000, 2000, 100); SUCCEED(); - bundleUserHistory_->ReportUsage(oneBundleUsageHistory, "test", 20, 0, 1000, 2000, 100, 0); + bundleUserHistory_->ReportUsage(oneBundleUsageHistory, event, 20, 0, 1000, 2000, 100); SUCCEED(); - bundleUserHistory_->ReportUsage(oneBundleUsageHistory, "test", 20, 0, 0, 2000, 100, 0); + bundleUserHistory_->ReportUsage(oneBundleUsageHistory, event, 20, 0, 0, 2000, 100); SUCCEED(); } @@ -1595,5 +1584,58 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Merg EXPECT_EQ(MergeResult.size(), 2); } +/* + * @tc.name: DeviceUsageStatisticsServiceTest_IsUsedOverOneWeek_001 + * @tc.desc: IsUsedOverOneWeek + * @tc.type: FUNC + * @tc.require: issuesICCZ27 + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_IsUsedOverOneWeek_001, + Function | MediumTest | Level0) +{ + std::string bundleName = "test"; + int32_t userId = 100; + BundleActiveGroupController::GetInstance().bundleUserHistory_ = nullptr; + EXPECT_FALSE(BundleActiveGroupController::GetInstance().IsUsedOverOneWeek(bundleName, userId)); + BundleActiveGroupController::GetInstance().CreateUserHistory(0, bundleActiveCore_); + EXPECT_FALSE(BundleActiveGroupController::GetInstance().IsUsedOverOneWeek(bundleName, userId)); + auto userHistory = BundleActiveGroupController::GetInstance().bundleUserHistory_->GetUserHistory(userId, true); + EXPECT_NE(userHistory, nullptr); + std::shared_ptr usageHistoryInserted = + std::make_shared(); + usageHistoryInserted->bundleName_ = bundleName; + + (*userHistory)[bundleName] = usageHistoryInserted; + EXPECT_FALSE(BundleActiveGroupController::GetInstance().IsUsedOverOneWeek(bundleName, userId)); + int64_t curTime = BundleActiveUtil::GetSystemTimeMs(); + int64_t testTime = 100000; + usageHistoryInserted->bundlefirstUseTimeStamp_ = curTime - (ONE_WEEK_TIME - testTime); + (*userHistory)[bundleName] = usageHistoryInserted; + EXPECT_TRUE(BundleActiveGroupController::GetInstance().IsUsedOverOneWeek(bundleName, userId)); +} + +/* + * @tc.name: DeviceUsageStatisticsServiceTest_GetFirstUseTime_001 + * @tc.desc: GetFirstUseTime + * @tc.type: FUNC + * @tc.require: issuesICCZ27 + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_GetFirstUseTime_001, + Function | MediumTest | Level0) +{ + int64_t bootBasedTimeStamp = 2000; + auto bundleUserHistory = std::make_shared(bootBasedTimeStamp, bundleActiveCore_); + std::string bundleName = "com.ohos.camera"; + int32_t userId = 100; + EXPECT_EQ(bundleUserHistory->GetFirstUseTime(bundleName, userId), MAX_END_TIME); + auto userHistoryMap = bundleUserHistory->GetUserHistory(userId, true); + (*userHistoryMap)[bundleName] = nullptr; + EXPECT_EQ(bundleUserHistory->GetFirstUseTime(bundleName, userId), MAX_END_TIME); + (*userHistoryMap)[bundleName] = std::make_shared(); + EXPECT_EQ(bundleUserHistory->GetFirstUseTime(bundleName, userId), MAX_END_TIME); + (*userHistoryMap)[bundleName]->bundlefirstUseTimeStamp_ = 100; + EXPECT_EQ(bundleUserHistory->GetFirstUseTime(bundleName, userId), 100); +} + } // namespace DeviceUsageStats } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/package_usage_test.cpp b/test/unittest/package_usage_test.cpp index 345e6fd710d97f52a3f0804a17abee9789a89615..803677a9a0f1f2436b520e31c732ce1083ca8a49 100644 --- a/test/unittest/package_usage_test.cpp +++ b/test/unittest/package_usage_test.cpp @@ -33,6 +33,7 @@ #include "bundle_active_group_controller.h" #include "bundle_active_event_list.h" #include "bundle_active_test_util.h" +#include "bundle_active_util.h" using namespace testing::ext; @@ -1186,7 +1187,7 @@ HWTEST_F(PackageUsageTest, BundleActivePackageStats_005, Function | MediumTest | */ HWTEST_F(PackageUsageTest, BundleActiveCalendar_001, Function | MediumTest | Level0) { - int64_t nowTime = bundleActiveCore_->GetSystemTimeMs(); + int64_t nowTime = BundleActiveUtil::GetSystemTimeMs(); BundleActiveCalendar testCalendar(nowTime); testCalendar.TruncateToDay(); EXPECT_TRUE(nowTime - testCalendar.GetMilliseconds() >= 0); @@ -1209,7 +1210,7 @@ HWTEST_F(PackageUsageTest, BundleActiveCalendar_001, Function | MediumTest | Lev */ HWTEST_F(PackageUsageTest, BundleActiveCalendar_002, Function | MediumTest | Level0) { - int64_t nowTime = bundleActiveCore_->GetSystemTimeMs(); + int64_t nowTime = BundleActiveUtil::GetSystemTimeMs(); BundleActiveCalendar testCalendar(nowTime); testCalendar.ChangeToDebug(); testCalendar.TruncateToDay(); diff --git a/utils/include/bundle_active_util.h b/utils/include/bundle_active_util.h index 67f3805957976f19cd4b9ee0dae0fa7e72212a85..e9b669086f580676f9e0eedd6597f42303e1b8ab 100644 --- a/utils/include/bundle_active_util.h +++ b/utils/include/bundle_active_util.h @@ -32,6 +32,7 @@ public: 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); + static int64_t GetSystemTimeMs(); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/utils/src/bundle_active_util.cpp b/utils/src/bundle_active_util.cpp index 8bc74445d9a2a75ed4398e11985ef7366aaa042e..8c6b6756e10eb68e488404bfe1d30cf62c9d27db 100644 --- a/utils/src/bundle_active_util.cpp +++ b/utils/src/bundle_active_util.cpp @@ -16,6 +16,7 @@ #include #include #include "bundle_active_util.h" +#include "bundle_active_log.h" namespace OHOS { namespace DeviceUsageStats { @@ -99,6 +100,24 @@ int64_t BundleActiveUtil::StringToInt64(const std::string& str) } return res; } + +int64_t BundleActiveUtil::GetSystemTimeMs() +{ + time_t now; + (void)time(&now); // unit is seconds. + if (static_cast(now) < 0) { + BUNDLE_ACTIVE_LOGE("Get now time error"); + return 0; + } + auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now); + auto tarDuration = std::chrono::duration_cast(tarEndTimePoint.time_since_epoch()); + int64_t tarDate = tarDuration.count(); + if (tarDate < 0) { + BUNDLE_ACTIVE_LOGE("tarDuration is less than 0."); + return -1; + } + return static_cast(tarDate); +} } // namespace DeviceUsageStats } // namespace OHOS