diff --git a/BUILD.gn b/BUILD.gn index 88c0693732abbb3272c0d7fcb19f34a8a92020c6..4e5b76c41ba7efe879edae9183e33490fe1937a1 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -175,6 +175,7 @@ ohos_shared_library("usagestatservice") { "services/common/src/bundle_active_shutdown_callback_service.cpp", "services/common/src/bundle_active_stub.cpp", "services/common/src/bundle_active_usage_database.cpp", + "services/common/src/device_usage_oobe_manager.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", @@ -185,6 +186,7 @@ ohos_shared_library("usagestatservice") { "services/packageusage/src/bundle_active_report_handler.cpp", "services/packageusage/src/bundle_active_stats_combiner.cpp", "services/packageusage/src/bundle_active_user_service.cpp", + "utils/src/device_usage_data_share_utils.cpp", ] public_configs = [ ":usagestats_public_config" ] @@ -195,7 +197,9 @@ ohos_shared_library("usagestatservice") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:app_manager", + "ability_runtime:dataobs_manager", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", @@ -203,6 +207,7 @@ ohos_shared_library("usagestatservice") { "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "data_share:datashare_consumer", "eventhandler:libeventhandler", "hilog:libhilog", "init:libbegetutil", @@ -257,6 +262,7 @@ ohos_static_library("usagestatservice_static") { "services/common/src/bundle_active_shutdown_callback_service.cpp", "services/common/src/bundle_active_stub.cpp", "services/common/src/bundle_active_usage_database.cpp", + "services/common/src/device_usage_oobe_manager.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", @@ -267,6 +273,7 @@ ohos_static_library("usagestatservice_static") { "services/packageusage/src/bundle_active_report_handler.cpp", "services/packageusage/src/bundle_active_stats_combiner.cpp", "services/packageusage/src/bundle_active_user_service.cpp", + "utils/src/device_usage_data_share_utils.cpp", ] public_configs = [ ":usagestats_public_config" ] @@ -277,7 +284,9 @@ ohos_static_library("usagestatservice_static") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:app_manager", + "ability_runtime:dataobs_manager", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", @@ -285,6 +294,7 @@ ohos_static_library("usagestatservice_static") { "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "data_share:datashare_consumer", "eventhandler:libeventhandler", "hilog:libhilog", "init:libbegetutil", diff --git a/bundle.json b/bundle.json index 60166dd787b42b3b88745abee8c92cb54b036169..e7b71059b19845e342b78e5efbe286d36cfc6d79 100644 --- a/bundle.json +++ b/bundle.json @@ -24,6 +24,7 @@ "deps": { "components": [ "bundle_framework", + "data_share", "relational_store", "safwk", "common_event_service", diff --git a/services/common/include/bundle_active_bundle_mgr_helper.h b/services/common/include/bundle_active_bundle_mgr_helper.h index fcebdd715cac6e1d1b6314b2a3188c5fcc9acdeb..731f75dafc29d2c53eb00d046a98ba12473868d9 100644 --- a/services/common/include/bundle_active_bundle_mgr_helper.h +++ b/services/common/include/bundle_active_bundle_mgr_helper.h @@ -57,14 +57,19 @@ public: */ bool GetApplicationInfo(const std::string &appName, const AppExecFwk::ApplicationFlag flag, const int userId, AppExecFwk::ApplicationInfo &appInfo); + + bool GetApplicationInfos(const AppExecFwk::ApplicationFlag flag, + const int userId, std::vector &appInfos); bool IsLauncherApp(const std::string &bundleName, const int32_t userId); + void InitLauncherAppMap(); + private: bool Connect(); private: - std::unordered_set launcherAppSet_; + std::map launcherAppMap_; sptr bundleMgr_ = nullptr; std::mutex connectionMutex_; DECLARE_DELAYED_SINGLETON(BundleActiveBundleMgrHelper); diff --git a/services/common/include/device_usage_oobe_manager.h b/services/common/include/device_usage_oobe_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..639220cbc7d8b889aed73a21346b668da0aec531 --- /dev/null +++ b/services/common/include/device_usage_oobe_manager.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DEVICE_USAGE_OOBE_MANAGER_H +#define DEVICE_USAGE_OOBE_MANAGER_H + +#include "data_ability_observer_stub.h" +#include "errors.h" +#include "mutex" +#include + +namespace OHOS { +namespace DeviceUsageStats { +class DeviceUsageOOBEManager { +public: + static DeviceUsageOOBEManager& GetInstance(); + ErrCode UnregisterObserver(); + bool GetOOBEValue(); + void Init(); + +private: + class BundleActiveDataShareObserver : public AAFwk::DataAbilityObserverStub { + public: + BundleActiveDataShareObserver() = default; + ~BundleActiveDataShareObserver() = default; + void OnChange() override; + }; + + bool g_oobeValue = false; + static std::mutex mutex_; + static sptr observer_; + DeviceUsageOOBEManager(); + ~DeviceUsageOOBEManager(); + ErrCode RegisterObserver(); +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // DEVICE_USAGE_OOBE_MANAGER \ No newline at end of file diff --git a/services/common/src/bundle_active_bundle_mgr_helper.cpp b/services/common/src/bundle_active_bundle_mgr_helper.cpp index 4ec9f9a14ba4223ca00c67d3220591a77b815abe..624f0b22f47afda07950f9e51700f98ab6e653d5 100644 --- a/services/common/src/bundle_active_bundle_mgr_helper.cpp +++ b/services/common/src/bundle_active_bundle_mgr_helper.cpp @@ -15,6 +15,8 @@ #include "bundle_active_bundle_mgr_helper.h" +#include "device_usage_oobe_manager.h" +#include "device_usage_data_share_utils.h" #include "bundle_active_log.h" #include "accesstoken_kit.h" #include "application_info.h" @@ -32,6 +34,7 @@ BundleActiveBundleMgrHelper::BundleActiveBundleMgrHelper() BundleActiveBundleMgrHelper::~BundleActiveBundleMgrHelper() { + launcherAppMap_.clear(); } void BundleActiveBundleMgrHelper::GetNameForUid(int32_t uid, std::string& bundleName) @@ -63,6 +66,22 @@ bool BundleActiveBundleMgrHelper::GetApplicationInfo(const std::string &appName, return false; } +bool BundleActiveBundleMgrHelper::GetApplicationInfos(const AppExecFwk::ApplicationFlag flag, + const int userId, std::vector &appInfos) +{ + BUNDLE_ACTIVE_LOGD("start get application infos"); + std::lock_guard lock(connectionMutex_); + + if (!Connect()) { + return false; + } + BUNDLE_ACTIVE_LOGD("bundleMgr is null: %{public}d ", bundleMgr_ == nullptr); + if (bundleMgr_ != nullptr && bundleMgr_->GetApplicationInfos(flag, userId, appInfos)) { + return true; + } + return false; +} + bool BundleActiveBundleMgrHelper::GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, AppExecFwk::BundleInfo &bundleInfo, int32_t userId) { @@ -102,8 +121,14 @@ bool BundleActiveBundleMgrHelper::Connect() bool BundleActiveBundleMgrHelper::IsLauncherApp(const std::string &bundleName, const int32_t userId) { - if (launcherAppSet_.find(bundleName) != launcherAppSet_.end()) { - return true; + if (!DeviceUsageOOBEManager::GetInstance().GetOOBEValue()) { + BUNDLE_ACTIVE_LOGD("not agree obtain app list"); + return false; + } + if (launcherAppMap_.find(bundleName) != launcherAppMap_.end()) { + BUNDLE_ACTIVE_LOGD("launcherAppMap cache, bundleName:%{public}s isLauncherApp:%{public}d", + bundleName.c_str(), launcherAppMap_[bundleName]); + return launcherAppMap_[bundleName]; } AppExecFwk::ApplicationInfo appInfo; if (GetApplicationInfo(bundleName, @@ -111,11 +136,21 @@ bool BundleActiveBundleMgrHelper::IsLauncherApp(const std::string &bundleName, c BUNDLE_ACTIVE_LOGE("get applicationInfo failed."); return false; } - if (appInfo.isLauncherApp) { - launcherAppSet_.insert(bundleName); - return true; + launcherAppMap_[bundleName] = appInfo.isLauncherApp; + BUNDLE_ACTIVE_LOGD("insert launcherAppMap, bundleName:%{public}s isLauncherApp:%{public}d", + bundleName.c_str(), launcherAppMap_[bundleName]); + return appInfo.isLauncherApp; +} + +void BundleActiveBundleMgrHelper::InitLauncherAppMap() +{ + BUNDLE_ACTIVE_LOGI("agree obtain app list, init laucherAppMap"); + std::vector appInfos; + GetApplicationInfos(AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, + AppExecFwk::Constants::ALL_USERID, appInfos); + for (auto appInfo : appInfos) { + launcherAppMap_[appInfo.bundleName] = appInfo.isLauncherApp; } - return false; } } // namespace DeviceUsageStats } // namespace OHOS \ No newline at end of file diff --git a/services/common/src/device_usage_oobe_manager.cpp b/services/common/src/device_usage_oobe_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..545266d174d6eb46f78e427e86ce0370c3689fbc --- /dev/null +++ b/services/common/src/device_usage_oobe_manager.cpp @@ -0,0 +1,120 @@ +/* + * 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 "device_usage_data_share_utils.h" +#include "bundle_active_bundle_mgr_helper.h" +#include "bundle_active_log.h" +#include "device_usage_oobe_manager.h" +#include +#include "ipc_skeleton.h" + +namespace OHOS { +namespace DeviceUsageStats { +std::mutex DeviceUsageOOBEManager::mutex_; +sptr DeviceUsageOOBEManager::observer_ = nullptr; +namespace { +const std::string KEYWORD = "basic_statement_agreed"; +} // namespace + +DeviceUsageOOBEManager::DeviceUsageOOBEManager() +{ + Init(); +} + +DeviceUsageOOBEManager::~DeviceUsageOOBEManager() +{ + BUNDLE_ACTIVE_LOGI("DeviceUsageOOBEManager has been deconstructed"); +} + +DeviceUsageOOBEManager& DeviceUsageOOBEManager::GetInstance() +{ + static DeviceUsageOOBEManager instance; + return instance; +} + +bool DeviceUsageOOBEManager::GetOOBEValue() +{ + std::lock_guard lock(mutex_); + return g_oobeValue; +} + +ErrCode DeviceUsageOOBEManager::RegisterObserver() +{ + std::lock_guard lock(mutex_); + std::string callingIdentity = IPCSkeleton::ResetCallingIdentity(); + auto uri = DeviceUsageDataShareUtils::GetInstance().AssembleUri(KEYWORD); + auto helper = DeviceUsageDataShareUtils::GetInstance().CreateDataShareHelper(); + if (helper == nullptr) { + IPCSkeleton::SetCallingIdentity(callingIdentity); + BUNDLE_ACTIVE_LOGE("RegisterObserver: helper does not created!"); + return ERR_NO_INIT; + } + if (observer_ != nullptr) { + BUNDLE_ACTIVE_LOGE("Secondary RegisterObserver!"); + UnregisterObserver(); + } + observer_ = new (std::nothrow)BundleActiveDataShareObserver(); + if (observer_ == nullptr) { + IPCSkeleton::SetCallingIdentity(callingIdentity); + return ERR_INVALID_OPERATION; + } + helper->RegisterObserver(uri, observer_); + DeviceUsageDataShareUtils::GetInstance().ReleaseDataShareHelper(helper); + IPCSkeleton::SetCallingIdentity(callingIdentity); + BUNDLE_ACTIVE_LOGI("succeed to register observer of uri=%{public}s", uri.ToString().c_str()); + return ERR_OK; +} + +ErrCode DeviceUsageOOBEManager::UnregisterObserver() +{ + std::string callingIdentity = IPCSkeleton::ResetCallingIdentity(); + auto uri = DeviceUsageDataShareUtils::GetInstance().AssembleUri(KEYWORD); + auto helper = DeviceUsageDataShareUtils::GetInstance().CreateDataShareHelper(); + if (helper == nullptr) { + IPCSkeleton::SetCallingIdentity(callingIdentity); + BUNDLE_ACTIVE_LOGE("UnregisterObserver: helper does not created!"); + return ERR_NO_INIT; + } + helper->UnregisterObserver(uri, observer_); + DeviceUsageDataShareUtils::GetInstance().ReleaseDataShareHelper(helper); + observer_ = nullptr; + IPCSkeleton::SetCallingIdentity(callingIdentity); + BUNDLE_ACTIVE_LOGI("succeed to register observer of uri=%{public}s", uri.ToString().c_str()); + return ERR_OK; +} + +void DeviceUsageOOBEManager::BundleActiveDataShareObserver::OnChange() +{ + BundleActiveBundleMgrHelper::GetInstance()->InitLauncherAppMap(); + DeviceUsageOOBEManager::GetInstance().g_oobeValue = true; +} + + +void DeviceUsageOOBEManager::Init() +{ + int resultValue = 0; + auto DeviceUsageDataShareUtils = DeviceUsageDataShareUtils::GetInstance(); + DeviceUsageDataShareUtils.GetValue(KEYWORD, resultValue); + if (resultValue != 0) { + BundleActiveBundleMgrHelper::GetInstance()->InitLauncherAppMap(); + g_oobeValue = true; + return; + } + RegisterObserver(); +} + +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index b97698266aca7183dd2aa50a9911e25d6448beef..ef097d7e75b454287a8025a7bddcc86c4c523c2c 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -48,7 +48,9 @@ ohos_unittest("BundleActiveTotalTest") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:app_manager", + "ability_runtime:dataobs_manager", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", @@ -56,6 +58,7 @@ ohos_unittest("BundleActiveTotalTest") { "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "data_share:datashare_consumer", "eventhandler:libeventhandler", "hilog:libhilog", "init:libbegetutil", diff --git a/test/unittest/bundle_active_total_test.cpp b/test/unittest/bundle_active_total_test.cpp index d6f1efc4c2220567288efadb4e7e88760a34869a..b4864560ee875a93383e6e4add356e687089c19e 100644 --- a/test/unittest/bundle_active_total_test.cpp +++ b/test/unittest/bundle_active_total_test.cpp @@ -32,6 +32,8 @@ #include "bundle_active_shutdown_callback_service.h" #include "bundle_active_binary_search.h" #include "bundle_active_debug_mode.h" +#include "device_usage_data_share_utils.h" +#include "device_usage_oobe_manager.h" using namespace testing::ext; @@ -134,6 +136,104 @@ HWTEST_F(BundleActiveTotalTest, BundleActiveBundleMgrHelperTest_001, Function | test.GetBundleInfo(string, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo, 0); } +/* + * @tc.name: BundleActiveBundleMgrHelperTest_002 + * @tc.desc: test GetApplicationInfos + * @tc.type: FUNC + * @tc.require: issuesI9SQ6G + */ +HWTEST_F(BundleActiveTotalTest, BundleActiveBundleMgrHelperTest_002, Function | MediumTest | Level0) +{ + AppExecFwk::ApplicationFlag flag = AppExecFwk::GET_BASIC_APPLICATION_INFO; + std::vector appInfos; + BundleActiveBundleMgrHelper::GetInstance()->GetApplicationInfos(flag, 0, appInfos); + SUCCEED(); +} + +/* + * @tc.name: BundleActiveBundleMgrHelperTest_003 + * @tc.desc: test is launcherApp + * @tc.type: FUNC + * @tc.require: issuesI9SQ6G + */ +HWTEST_F(BundleActiveTotalTest, BundleActiveBundleMgrHelperTest_003, Function | MediumTest | Level0) +{ + BundleActiveBundleMgrHelper::GetInstance()->InitLauncherAppMap(); + DeviceUsageOOBEManager::GetInstance().g_oobeValue = true; + BundleActiveBundleMgrHelper::GetInstance()->IsLauncherApp("test", 0); + BundleActiveBundleMgrHelper::GetInstance()->launcherAppMap_["test"] = false; + BundleActiveBundleMgrHelper::GetInstance()->IsLauncherApp("test", 0); + SUCCEED(); +} + +/* + * @tc.name: DeviceUsageOOBEManager_001 + * @tc.desc: test RegisterObserver + * @tc.type: FUNC + * @tc.require: issuesI9SQ6G + */ +HWTEST_F(BundleActiveTotalTest, DeviceUsageOOBEManager_001, Function | MediumTest | Level0) +{ + DeviceUsageOOBEManager::GetInstance().Init(); + DeviceUsageOOBEManager::GetInstance().RegisterObserver(); + SUCCEED(); +} + +/* + * @tc.name: DeviceUsageOOBEManager_001 + * @tc.desc: test UnregisterObserver + * @tc.type: FUNC + * @tc.require: issuesI9SQ6G + */ +HWTEST_F(BundleActiveTotalTest, DeviceUsageOOBEManager_002, Function | MediumTest | Level0) +{ + DeviceUsageOOBEManager::GetInstance().Init(); + DeviceUsageOOBEManager::GetInstance().UnregisterObserver(); + SUCCEED(); +} + +/* + * @tc.name: DeviceUsageOOBEManager_001 + * @tc.desc: test observer onChange + * @tc.type: FUNC + * @tc.require: issuesI9SQ6G + */ +HWTEST_F(BundleActiveTotalTest, DeviceUsageOOBEManager_003, Function | MediumTest | Level0) +{ + DeviceUsageOOBEManager::GetInstance().observer_ = new DeviceUsageOOBEManager::BundleActiveDataShareObserver(); + DeviceUsageOOBEManager::GetInstance().observer_->OnChange(); + SUCCEED(); +} + +/* + * @tc.name: DeviceUsageDataShareUtils_001 + * @tc.desc: test observer onChange + * @tc.type: FUNC + * @tc.require: issuesI9SQ6G + */ +HWTEST_F(BundleActiveTotalTest, DeviceUsageDataShareUtils_001, Function | MediumTest | Level0) +{ + string key = "basic_statement_agreed"; + int value = 0; + DeviceUsageDataShareUtils::GetInstance().InitSystemAbilityManager(); + DeviceUsageDataShareUtils::GetInstance().CreateDataShareHelper(); + DeviceUsageDataShareUtils::GetInstance().GetValue(key, value); + SUCCEED(); +} + +/* + * @tc.name: DeviceUsageDataShareUtils_001 + * @tc.desc: test observer onChange + * @tc.type: FUNC + * @tc.require: issuesI9SQ6G + */ +HWTEST_F(BundleActiveTotalTest, DeviceUsageDataShareUtils_002, Function | MediumTest | Level0) +{ + string key = "basic_statement_agreed"; + DeviceUsageDataShareUtils::GetInstance().AssembleUri(key); + SUCCEED(); +} + /* * @tc.name: BundleActiveAppStateObserverTest_001 * @tc.desc: test the interface of bundle_active_app_state_observer diff --git a/utils/include/device_usage_data_share_utils.h b/utils/include/device_usage_data_share_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..ec6c61ce90448d8d8ee621ee655429148750c15a --- /dev/null +++ b/utils/include/device_usage_data_share_utils.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DEVICE_USAGE_DATA_SHARE_UTILS_H +#define DEVICE_USAGE_DATA_SHARE_UTILS_H + +#include "datashare_helper.h" +#include "errors.h" +#include "ipc_skeleton.h" +#include +#include "mutex" + +namespace OHOS { +namespace DeviceUsageStats { +class DeviceUsageDataShareUtils { +public: + ~DeviceUsageDataShareUtils (); + static DeviceUsageDataShareUtils& GetInstance(); + ErrCode GetValue(const std::string& key, int& value); + Uri AssembleUri(const std::string& key); + bool ReleaseDataShareHelper(std::shared_ptr& helper); + std::shared_ptr CreateDataShareHelper(); + +private: + DeviceUsageDataShareUtils (); + static sptr remoteObj_; + static std::mutex mutex_; + ErrCode GetStringValue(const std::string& key, std::string& value); + void InitSystemAbilityManager(); +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // DEVICE_USAGE_DATA_SHARE_UTILS_H + diff --git a/utils/src/device_usage_data_share_utils.cpp b/utils/src/device_usage_data_share_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..754b8835ac6815aa2ee6922d3fc85701aba06cf0 --- /dev/null +++ b/utils/src/device_usage_data_share_utils.cpp @@ -0,0 +1,154 @@ +/* + * 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 "datashare_errno.h" +#include "datashare_predicates.h" +#include "datashare_result_set.h" +#include "datashare_values_bucket.h" +#include "iservice_registry.h" +#include "device_usage_data_share_utils.h" +#include "bundle_active_log.h" +#include "system_ability_definition.h" +#include "uri.h" + +namespace OHOS { +namespace DeviceUsageStats { + +sptr DeviceUsageDataShareUtils::remoteObj_; +std::mutex DeviceUsageDataShareUtils::mutex_; +namespace { +const int32_t PARAM_NUM_TEN = 10; +const std::string SETTING_COLUMN_KEYWORD = "KEYWORD"; +const std::string SETTING_COLUMN_VALUE = "VALUE"; +const std::string SETTING_URI_PROXY = "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true"; +} // namespace + +DeviceUsageDataShareUtils::DeviceUsageDataShareUtils() = default; +DeviceUsageDataShareUtils::~DeviceUsageDataShareUtils() = default; + +DeviceUsageDataShareUtils& DeviceUsageDataShareUtils::GetInstance() +{ + static DeviceUsageDataShareUtils instance; + instance.InitSystemAbilityManager(); + return instance; +} + +ErrCode DeviceUsageDataShareUtils::GetStringValue(const std::string& key, std::string& value) +{ + auto helper = CreateDataShareHelper(); + if (helper == nullptr) { + BUNDLE_ACTIVE_LOGE("DeviceUsageDataShareUtils: helper does not created!"); + return ERR_NO_INIT; + } + std::vector columns = {SETTING_COLUMN_VALUE}; + DataShare::DataSharePredicates predicates; + predicates.EqualTo(SETTING_COLUMN_KEYWORD, key); + BUNDLE_ACTIVE_LOGD("keyWord=%{public}s", key.c_str()); + Uri uri(AssembleUri(key)); + auto resultSet = helper->Query(uri, predicates, columns); + ReleaseDataShareHelper(helper); + if (resultSet == nullptr) { + BUNDLE_ACTIVE_LOGE("helper->Query return nullptr"); + return ERR_INVALID_OPERATION; + } + int32_t count; + resultSet->GetRowCount(count); + if (count == 0) { + BUNDLE_ACTIVE_LOGW("not found value, keyWord=%{public}s, count=%{public}d", key.c_str(), count); + return ERR_NAME_NOT_FOUND; + } + const int32_t INDEX = 0; + resultSet->GoToRow(INDEX); + int32_t ret = resultSet->GetString(INDEX, value); + if (ret != DataShare::E_OK) { + BUNDLE_ACTIVE_LOGW("resultSet->GetString return not ok, ret=%{public}d", ret); + return ERR_INVALID_VALUE; + } + resultSet->Close(); + return ERR_OK; +} + +ErrCode DeviceUsageDataShareUtils::GetValue(const std::string& key, int& value) +{ + std::string result; + std::string callingIdentity = IPCSkeleton::ResetCallingIdentity(); + int32_t ret = GetStringValue(key, result); + IPCSkeleton::SetCallingIdentity(callingIdentity); + if (ret != ERR_OK) { + BUNDLE_ACTIVE_LOGW("resultSet->GetStringValue return not ok, ret=%{public}d", ret); + return ret; + } + char* pEnd = nullptr; + int64_t intResult = std::strtol(result.c_str(), &pEnd, PARAM_NUM_TEN); + if (pEnd == result.c_str() || *pEnd != '\0' || (intResult < INT_MIN || intResult > INT_MAX)) { + BUNDLE_ACTIVE_LOGW("getValue string to int fail"); + return ret; + } + value = intResult; + return ERR_OK; +} + +std::shared_ptr DeviceUsageDataShareUtils::CreateDataShareHelper() +{ + if (remoteObj_ == nullptr) { + BUNDLE_ACTIVE_LOGE("Get remoteObj return nullptr!"); + return nullptr; + } + auto helper = DataShare::DataShareHelper::Creator(remoteObj_, SETTING_URI_PROXY); + if (helper == nullptr) { + BUNDLE_ACTIVE_LOGW("helper is nullptr, uri=%{public}s, remoteObj_=%{public}p", SETTING_URI_PROXY.c_str(), + remoteObj_.GetRefPtr()); + return nullptr; + } + return helper; +} + +bool DeviceUsageDataShareUtils::ReleaseDataShareHelper(std::shared_ptr& helper) +{ + if (helper == nullptr) { + BUNDLE_ACTIVE_LOGW("release helper fail, helper is null!"); + return false; + } + if (!helper->Release()) { + BUNDLE_ACTIVE_LOGW("release helper fail, remoteObj_%{public}p", remoteObj_.GetRefPtr()); + return false; + } + return true; +} + +void DeviceUsageDataShareUtils::InitSystemAbilityManager() +{ + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + BUNDLE_ACTIVE_LOGE("get sam return nullptr"); + return; + } + auto remoteObj = sam->GetSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID); + if (remoteObj == nullptr) { + BUNDLE_ACTIVE_LOGE("Get remoteObj return nullptr, systemAbilityId=%{public}d", + BACKGROUND_TASK_MANAGER_SERVICE_ID); + return; + } + remoteObj_ = remoteObj; +} + +Uri DeviceUsageDataShareUtils::AssembleUri(const std::string& key) +{ + Uri uri(SETTING_URI_PROXY + "&key=" + key); + return uri; +} +} // namespace DeviceUsageStats +} // namespace OHOS +