1 /* 2 * Copyright (c) 2022-2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef BUNDLE_ACTIVE_CORE_H 17 #define BUNDLE_ACTIVE_CORE_H 18 19 #ifdef DEVICE_USAGE_UNIT_TEST 20 #define WEAK_FUNC __attribute__((weak)) 21 #else 22 #define WEAK_FUNC 23 #endif 24 25 #include <mutex> 26 #ifdef DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE 27 #include "power_mgr_client.h" 28 #endif 29 #include "accesstoken_kit.h" 30 #ifdef OS_ACCOUNT_PART_ENABLED 31 #include "os_account_manager.h" 32 #endif // OS_ACCOUNT_PART_ENABLED 33 #include "ibundle_active_service.h" 34 #include "remote_death_recipient.h" 35 #include "iapp_group_callback.h" 36 #include "ffrt.h" 37 #include "bundle_active_debug_mode.h" 38 #include "bundle_active_stats_update_listener.h" 39 #include "bundle_state_inner_errors.h" 40 #include "bundle_active_user_service.h" 41 #include "bundle_active_group_controller.h" 42 #include "bundle_active_group_handler.h" 43 #include "bundle_active_common_event_subscriber.h" 44 #include "bundle_active_constant.h" 45 #include "bundle_active_config_reader.h" 46 #include "bundle_active_high_frequency_period.h" 47 48 namespace OHOS { 49 namespace DeviceUsageStats { 50 using namespace OHOS::Security; 51 52 class BundleActiveReportHandlerObject { 53 public: 54 BundleActiveEvent event_; 55 int32_t userId_; 56 std::string bundleName_; 57 int32_t uid_ = 0; 58 int32_t appIndex_ = 0; 59 BundleActiveReportHandlerObject(); 60 BundleActiveReportHandlerObject(const int32_t userId, const std::string bundleName); 61 BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject& orig); ~BundleActiveReportHandlerObject()62 ~BundleActiveReportHandlerObject() {} 63 ToString()64 std::string ToString() 65 { 66 std::string result; 67 result += "userid is " + std::to_string(userId_) + ", " + event_.ToString(); 68 return result; 69 } 70 }; 71 72 73 class BundleActiveCore : public BundleActiveStatsUpdateListener, 74 public std::enable_shared_from_this<BundleActiveCore> { 75 public: 76 BundleActiveCore(); 77 virtual ~BundleActiveCore(); 78 79 /* 80 * function: ReportEvent, used to report ability fourground/background/destroy event. 81 * parameters: event, userId 82 */ 83 int32_t ReportEvent(BundleActiveEvent& event, int32_t userId); 84 85 /* 86 * function: ReportEventToAllUserId, report flush to disk, end_of_day event to service. 87 * parameters: event 88 */ 89 int32_t ReportEventToAllUserId(BundleActiveEvent& event); 90 91 /* 92 * function: OnStatsChanged, report flush to disk, end_of_day event to service. 93 * parameters: userId 94 */ 95 void OnStatsChanged(const int32_t userId) override; 96 97 /* 98 * function: OnStatsChanged, when device reboot after more than one day, BundleActiveUserService 99 * will use it to flush group info. 100 */ 101 void OnStatsReload() override; 102 103 /* 104 * function: OnSystemUpdate, now is emtpy, later will called when system is updated. 105 * parameters: userId 106 */ 107 void OnSystemUpdate(int32_t userId) override; 108 109 /* 110 * function: OnBundleUninstalled when received a PACKATE_REMOVED commen event, 111 * BundleActiveCommonEventSubscriber call it to remove data. 112 * parameters: userId, bundleName 113 */ 114 void OnBundleUninstalled(const int32_t userId, const std::string& bundleName, const int32_t uid, 115 const int32_t appIndex); 116 117 /* 118 * function: Init, BundleAciveService call it to init systemTimeShot_, realTimeShot_, 119 * create bundleGroupController_ object. 120 */ 121 void Init(); 122 123 /* 124 * function: InitBundleGroupController, BundleAciveService call it to init bundleGroupController_ object, 125 * set its handler and subscribe needed common event. 126 * create bundleGroupController_ object. 127 */ 128 void InitBundleGroupController(); 129 130 /* 131 * function: RestoreToDatabase, restore bundle usage data and form data to database 132 * parameters: userId 133 */ 134 void RestoreToDatabase(const int32_t userId); 135 136 /* 137 * function: RestoreToDatabaseLocked, flush database for one user data 138 * parameters: userId 139 */ 140 void RestoreToDatabaseLocked(const int32_t userId); 141 142 /* 143 * function: ShutDown, called when device shutdown, update the in-memory stat and flush the database. 144 */ 145 void ShutDown(); 146 /* 147 * function: PreservePowerStateInfo, called when device change power state, preserve power state info. 148 */ 149 void PreservePowerStateInfo(const int32_t eventId); 150 151 /* 152 * function: queryBundleStatsInfos, query the package stat for calling user. 153 * parameters: userId, intervalType, beginTime, endTime, bundleName 154 * return: vector of BundleActivePackageStats 155 */ 156 ErrCode QueryBundleStatsInfos(std::vector<BundleActivePackageStats>& packageStats, const int32_t userId, 157 const int32_t intervalType, const int64_t beginTime, const int64_t endTime, std::string bundleName); 158 159 // query the event stat for calling user. 160 ErrCode QueryBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvent, const int32_t userId, 161 const int64_t beginTime, const int64_t endTime, std::string bundleName); 162 163 // check the app idle state for calling user. 164 int32_t IsBundleIdle(const std::string& bundleName, const int32_t userId); 165 166 // check the app use period state for calling user. 167 bool IsBundleUsePeriod(const std::string& bundleName, const int32_t userId); 168 169 // query the app group for calling app. 170 ErrCode QueryAppGroup(int32_t& appGroup, const std::string& bundleName, const int32_t userId); 171 172 ErrCode QueryModuleUsageRecords(int32_t maxNum, std::vector<BundleActiveModuleRecord>& results, int32_t userId); 173 174 /* 175 * function: QueryDeviceEventStats, query all from event stats in specific time span for calling user. 176 * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, 177 * if other SAs call this API, they should explicit define userId. 178 * return: errorcode. 179 */ 180 ErrCode QueryDeviceEventStats(int64_t beginTime, int64_t endTime, 181 std::vector<BundleActiveEventStats>& eventStats, int32_t userId); 182 183 /* 184 * function: QueryNotificationEventStats, query all app notification number in specific time span for calling user. 185 * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, 186 * if other SAs call this API, they should explicit define userId. 187 * return: errorcode. 188 */ 189 ErrCode QueryNotificationEventStats(int64_t beginTime, int64_t endTime, 190 std::vector<BundleActiveEventStats>& eventStats, int32_t userId); 191 192 /* 193 * function: QueryHighFrequencyPeriodBundle, query the high-frequency usage period of the app in the past week. 194 * parameters: appFreqHours, userId, default userId is -1 for JS API, 195 * if other SAs call this API, they should explicit define userId. 196 * return: errorcode. 197 */ 198 ErrCode QueryHighFrequencyPeriodBundle( 199 std::vector<BundleActiveHighFrequencyPeriod>& appFreqHours, int32_t userId); 200 201 // get the wall time and check if the wall time is changed. 202 int64_t CheckTimeChangeAndGetWallTime(int32_t userId = 0); 203 204 // convert event timestamp from boot based time to wall time. 205 void ConvertToSystemTimeLocked(BundleActiveEvent& event); 206 207 // get or create BundleActiveUserService object for specifice user. 208 std::shared_ptr<BundleActiveUserService> GetUserDataAndInitializeIfNeeded(const int32_t userId, 209 const int64_t timeStamp, const bool debug); 210 211 // when received a USER_REMOVED commen event, call it to remove data. 212 void OnUserRemoved(const int32_t userId); 213 214 // when user switched, restore old userdata. 215 void OnUserSwitched(const int32_t userId); 216 217 /* 218 * function: SetAppGroup, change bundleGroup to the newGroup. 219 * parameters: bundleName, newGroup, userId, isFlush, 220 * return: errorcode. 221 */ 222 ErrCode SetAppGroup( 223 const std::string& bundleName, const int32_t newGroup, const int32_t userId, const bool isFlush); 224 225 // get all user in device. 226 void GetAllActiveUser(std::vector<int32_t>& activatedOsAccountIds); 227 228 // when service stop, call it to unregister commen event and shutdown call back. 229 void UnRegisterSubscriber(); 230 231 /* 232 * function: RegisterAppGroupCallBack, register the observer to groupObservers. 233 * parameters: observer 234 * return: errCode. 235 */ 236 ErrCode RegisterAppGroupCallBack(const AccessToken::AccessTokenID& tokenId, 237 const sptr<IAppGroupCallback> &observer); 238 239 /* 240 * function: UnRegisterAppGroupCallBack, remove the observer from groupObservers. 241 * parameters: observer 242 * return: errCode. 243 */ 244 ErrCode UnRegisterAppGroupCallBack(const AccessToken::AccessTokenID& tokenId, 245 const sptr<IAppGroupCallback> &observer); 246 247 int32_t currentUsedUser_; 248 void OnAppGroupChanged(const AppGroupCallbackInfo& callbackInfo); 249 bool isUninstalledApp(const int32_t uid); 250 void OnBundleInstalled(const int32_t userId, const std::string& bundleName, const int32_t uid, 251 const int32_t appIndex); 252 void DeInit(); 253 254 private: 255 // 用于应用使用时段信息统计 256 struct AppUsage { 257 int32_t dayUsage[NUM_DAY_ONE_WEEK] = {}; 258 int32_t hourUsage[NUM_DAY_ONE_WEEK][NUM_HOUR_ONE_DAY] = {}; 259 int32_t hourTotalUse[NUM_HOUR_ONE_DAY] = {}; 260 int64_t startTime = DEFAULT_INVALID_VALUE; 261 }; 262 263 void NotifOberserverGroupChanged(const AppGroupCallbackInfo& callbackInfo, AccessToken::HapTokenInfo tokenInfo); 264 void AddObserverDeathRecipient(const sptr<IAppGroupCallback> &observer); 265 void RemoveObserverDeathRecipient(const sptr<IAppGroupCallback> &observer); 266 void OnObserverDied(const wptr<IRemoteObject> &remote); 267 void OnObserverDiedInner(const wptr<IRemoteObject> &remote); 268 void AddbundleUninstalledUid(const int32_t uid); 269 void DelayRemoveBundleUninstalledUid(const int32_t uid); 270 bool IsUserSpaceMemoryLimit(); 271 void ProcessDataSize(); 272 bool IsFolderSizeLimit(); 273 void DeleteExcessiveTableData(); 274 void ProcessEvents(std::unordered_map<std::string, AppUsage>& appUsages, std::vector<BundleActiveEvent>& events); 275 void GetFreqBundleHours(std::vector<BundleActiveHighFrequencyPeriod>& appFreqHours, 276 std::unordered_map<std::string, AppUsage>& appUsages); 277 void GetTopHourUsage( 278 std::vector<std::vector<int32_t>>& topHoursUsage, AppUsage& usage); 279 int64_t flushInterval_; 280 static const int64_t TIME_CHANGE_THRESHOLD_MILLIS = TEN_MINUTES; 281 const int32_t DEFAULT_USER_ID = -1; 282 std::map<int32_t, std::string> visibleActivities_; 283 double percentUserSpaceLimit_ = 0; 284 int64_t systemTimeShot_; 285 int64_t realTimeShot_; 286 ffrt::mutex mutex_; 287 ffrt::recursive_mutex callbackMutex_; 288 std::map<int32_t, std::shared_ptr<BundleActiveUserService>> userStatServices_; 289 std::map<int32_t, ffrt::task_handle> taskMap_; 290 void RegisterSubscriber(); 291 void SubscriberLockScreenCommonEvent(); 292 std::shared_ptr<BundleActiveCommonEventSubscriber> commonEventSubscriber_; 293 std::shared_ptr<BundleActiveCommonEventSubscriber> lockScreenSubscriber_; 294 void RestoreAllData(); 295 std::map<AccessToken::AccessTokenID, sptr<IAppGroupCallback>> groupChangeObservers_; 296 std::map<sptr<IRemoteObject>, sptr<RemoteDeathRecipient>> recipientMap_; 297 void ObtainSystemEventName(BundleActiveEvent& event); 298 bool debugCore_; 299 ffrt::mutex bundleUninstalledMutex_; 300 std::set<int32_t> bundleUninstalledSet_; 301 std::shared_ptr<BundleActiveConfigReader> bundleActiveConfigReader_; 302 }; 303 } // namespace DeviceUsageStats 304 } // namespace OHOS 305 #endif // BUNDLE_ACTIVE_CORE_H 306 307