diff --git a/frameworks/ans/BUILD.gn b/frameworks/ans/BUILD.gn index 72c27ac5d7dfb793a60734e41259a91c1c6d18dd..5ed1b1abc042237dc5d9e0fafa9684c2c67bae36 100644 --- a/frameworks/ans/BUILD.gn +++ b/frameworks/ans/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2023 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -87,6 +87,7 @@ ohos_shared_library("ans_innerkits") { "${frameworks_module_ans_path}/src/notification_conversational_message.cpp", "${frameworks_module_ans_path}/src/notification_distributed_options.cpp", "${frameworks_module_ans_path}/src/notification_do_not_disturb_date.cpp", + "${frameworks_module_ans_path}/src/notification_do_not_disturb_profile.cpp", "${frameworks_module_ans_path}/src/notification_flags.cpp", "${frameworks_module_ans_path}/src/notification_helper.cpp", "${frameworks_module_ans_path}/src/notification_live_view_content.cpp", diff --git a/frameworks/ans/src/notification_do_not_disturb_profile.cpp b/frameworks/ans/src/notification_do_not_disturb_profile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..de3fede4e0910f453402eb1b2ba86e354a0ab14c --- /dev/null +++ b/frameworks/ans/src/notification_do_not_disturb_profile.cpp @@ -0,0 +1,163 @@ +/* + * 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 "notification_do_not_disturb_profile.h" + +#include "ans_const_define.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace Notification { +namespace { +constexpr const char *DO_NOT_DISTURB_PROFILE_ID = "id"; +constexpr const char *DO_NOT_DISTURB_PROFILE_NAME = "name"; +constexpr const char *DO_NOT_DISTURB_PROFILE_TRUSTLIST = "trustlist"; +} // namespace +NotificationDoNotDisturbProfile::NotificationDoNotDisturbProfile( + int32_t id, const std::string &name, const std::vector &trustList) + : id_(id), name_(name), trustList_(trustList) +{} + +void NotificationDoNotDisturbProfile::SetProfileId(int32_t id) +{ + id_ = id; +} + +void NotificationDoNotDisturbProfile::SetProfileName(const std::string &name) +{ + name_ = name; +} + +void NotificationDoNotDisturbProfile::SetProfileTrustList(const std::vector &trustList) +{ + trustList_ = trustList; +} + +int32_t NotificationDoNotDisturbProfile::GetProfileId() const +{ + return id_; +} + +std::string NotificationDoNotDisturbProfile::GetProfileName() const +{ + return name_; +} + +std::vector NotificationDoNotDisturbProfile::GetProfileTrustlist() const +{ + return trustList_; +} + +bool NotificationDoNotDisturbProfile::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(id_)) { + ANS_LOGE("Failed to write do not disturb id."); + return false; + } + if (!parcel.WriteString(name_)) { + ANS_LOGE("Failed to write do not disturb name."); + return false; + } + auto size = trustList_.size(); + if (size > MAX_PARCELABLE_VECTOR_NUM) { + ANS_LOGE("Size exceeds the range."); + return false; + } + if (!parcel.WriteInt32(size)) { + ANS_LOGE("Failed to write do not disturb trust list size."); + return false; + } + for (uint32_t index = 0; index < size; ++index) { + if (!parcel.WriteParcelable(&trustList_[index])) { + ANS_LOGE("Failed to write do not disturb trust list."); + return false; + } + } + return true; +} + +NotificationDoNotDisturbProfile *NotificationDoNotDisturbProfile::Unmarshalling(Parcel &parcel) +{ + auto objptr = new (std::nothrow) NotificationDoNotDisturbProfile(); + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + return objptr; +} + +bool NotificationDoNotDisturbProfile::ReadFromParcel(Parcel &parcel) +{ + id_ = parcel.ReadInt32(); + name_ = parcel.ReadString(); + auto size = parcel.ReadUint32(); + if (size > MAX_PARCELABLE_VECTOR_NUM) { + ANS_LOGE("Size exceeds the range."); + return false; + } + for (uint32_t index = 0; index < size; ++index) { + sptr bundleOption = parcel.ReadParcelable(); + if (bundleOption == nullptr) { + ANS_LOGE("Failed to read bundle option."); + return false; + } + trustList_.emplace_back(*bundleOption); + } + return true; +} + +std::string NotificationDoNotDisturbProfile::ToJson() +{ + nlohmann::json jsonNodes = nlohmann::json::array(); + for (size_t index = 0; index < trustList_.size(); index++) { + nlohmann::json jsonNode; + if (trustList_[index].ToJson(jsonNode)) { + jsonNodes.emplace_back(jsonNode); + } + } + nlohmann::json jsonObject { + {DO_NOT_DISTURB_PROFILE_ID, id_}, + {DO_NOT_DISTURB_PROFILE_NAME, name_}, + {DO_NOT_DISTURB_PROFILE_TRUSTLIST, jsonNodes} + }; + return jsonObject.dump(); +} + +void NotificationDoNotDisturbProfile::FromJson(const std::string &jsonObj) +{ + nlohmann::json jsonObject = nlohmann::json::parse(jsonObj, nullptr, false); + if (jsonObject.is_discarded()) { + ANS_LOGE("Failed to parse json string."); + return; + } + if (jsonObject.contains(DO_NOT_DISTURB_PROFILE_ID) && jsonObject[DO_NOT_DISTURB_PROFILE_ID].is_number()) { + id_ = jsonObject.at(DO_NOT_DISTURB_PROFILE_ID).get(); + } + if (jsonObject.contains(DO_NOT_DISTURB_PROFILE_NAME) && jsonObject[DO_NOT_DISTURB_PROFILE_NAME].is_string()) { + name_ = jsonObject.at(DO_NOT_DISTURB_PROFILE_NAME).get(); + } + if (jsonObject.contains(DO_NOT_DISTURB_PROFILE_TRUSTLIST) && + jsonObject[DO_NOT_DISTURB_PROFILE_TRUSTLIST].is_array()) { + for (auto &trust : jsonObject.at(DO_NOT_DISTURB_PROFILE_TRUSTLIST)) { + auto bundleOption = NotificationBundleOption::FromJson(trust); + if (bundleOption == nullptr) { + continue; + } + trustList_.emplace_back(*bundleOption); + } + } +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 1ee5203b37a611ac91b773d854f16e36c18f32e0..d73aafa363151c0c34f9c3099611365bd95420fc 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -345,6 +345,17 @@ ErrCode NotificationHelper::GetDoNotDisturbDate(NotificationDoNotDisturbDate &do return DelayedSingleton::GetInstance()->GetDoNotDisturbDate(doNotDisturbDate); } +ErrCode NotificationHelper::AddDoNotDisturbProfiles(const std::vector> &profiles) +{ + return DelayedSingleton::GetInstance()->AddDoNotDisturbProfiles(profiles); +} + +ErrCode NotificationHelper::RemoveDoNotDisturbProfiles( + const std::vector> &profiles) +{ + return DelayedSingleton::GetInstance()->RemoveDoNotDisturbProfiles(profiles); +} + ErrCode NotificationHelper::DoesSupportDoNotDisturbMode(bool &doesSupport) { return DelayedSingleton::GetInstance()->DoesSupportDoNotDisturbMode(doesSupport); diff --git a/frameworks/core/common/include/ans_const_define.h b/frameworks/core/common/include/ans_const_define.h index 7df4a2322a4ecec3e465c0bd3060147ef4bf6c2c..2ca4ce9a7f341eb26c39eb44fa3d13d89ef30ee1 100644 --- a/frameworks/core/common/include/ans_const_define.h +++ b/frameworks/core/common/include/ans_const_define.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -50,6 +50,8 @@ constexpr int32_t SUBSCRIBE_USER_SYSTEM_BEGIN = 0; constexpr int32_t SUBSCRIBE_USER_SYSTEM_END = 99; constexpr int32_t NOTIFICATION_MIN_COUNT = 0; constexpr int32_t NOTIFICATION_MAX_COUNT = 1024; +constexpr int32_t FOCUS_MODE_PROFILE_MIN_ID = 1; +constexpr int32_t FOCUS_MODE_PROFILE_MAX_ID = 10; // Default sound for notification const static Uri DEFAULT_NOTIFICATION_SOUND("file://system/etc/Light.ogg"); diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 2da82c9eb96837df8e76fa440bc44c34a4f4f63b..445893b2a6747d83370d04688220724ac9c8c773 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -26,6 +26,7 @@ #include "notification_bundle_option.h" #include "notification_constant.h" #include "notification_do_not_disturb_date.h" +#include "notification_do_not_disturb_profile.h" #include "notification_request.h" #include "notification_slot.h" #include "notification_subscribe_info.h" @@ -520,6 +521,22 @@ public: */ virtual ErrCode GetDoNotDisturbDate(sptr &date) = 0; + /** + * @brief Add do not disturb profiles. + * + * @param profiles Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + virtual ErrCode AddDoNotDisturbProfiles(const std::vector> &profiles) = 0; + + /** + * @brief Remove do not disturb profiles. + * + * @param profiles Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + virtual ErrCode RemoveDoNotDisturbProfiles(const std::vector> &profiles) = 0; + /** * @brief Get whether Do Not Disturb mode is supported. * diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 9f9665b58dd56706393e3775c044c474f9b9da68..888949f565bf1230effc9346779dfb481da89f96 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -510,6 +510,22 @@ public: */ ErrCode GetDoNotDisturbDate(sptr &date) override; + /** + * @brief Add do not disturb Profiles. + * + * @param profiles Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddDoNotDisturbProfiles(const std::vector> &profiles) override; + + /** + * @brief Remove do not disturb Profiles. + * + * @param profiles Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode RemoveDoNotDisturbProfiles(const std::vector> &profiles) override; + /** * @brief Get whether Do Not Disturb mode is supported. * diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 69896a37d95c3bed1ad35501e43b62e3e8661f84..c051099ea274ef6f69438a822aa3cad639ff4882 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -510,6 +510,22 @@ public: */ virtual ErrCode GetDoNotDisturbDate(sptr &date) override; + /** + * @brief Add do not disturb profiles. + * + * @param profiles Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddDoNotDisturbProfiles(const std::vector> &profiles) override; + + /** + * @brief Remove do not disturb profiles. + * + * @param profiles Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode RemoveDoNotDisturbProfiles(const std::vector> &profiles) override; + /** * @brief Get whether Do Not Disturb mode is supported. * @@ -953,6 +969,8 @@ private: ErrCode HandleSetSmartReminderEnabled(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSmartReminderEnabled(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelAsBundleWithAgent(MessageParcel &data, MessageParcel &reply); + ErrCode HandleAddDoNotDisturbProfiles(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveDoNotDisturbProfiles(MessageParcel &data, MessageParcel &reply); template bool WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result) { diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index 055171e0790458869c7da92bd5485556d2378795..a2971b80b08388db9f8c8ec81be55487691d9b18 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -646,6 +646,24 @@ public: */ ErrCode GetDoNotDisturbDate(NotificationDoNotDisturbDate &doNotDisturbDate); + /** + * @brief Add the do not disturb profiles. + * @note Your application must have system signature to call this method. + * + * @param doNotDisturbProfiles Indicates the do not disturb profiles to add. + * @return Returns add do not disturb profiles result. + */ + ErrCode AddDoNotDisturbProfiles(const std::vector> &profiles); + + /** + * @brief Remove the do not disturb profiles. + * @note Your application must have system signature to call this method. + * + * @param doNotDisturbProfiles Indicates the do not disturb profiles to remove. + * @return Returns remove do not disturb profiles result. + */ + ErrCode RemoveDoNotDisturbProfiles(const std::vector> &profiles); + /** * @brief Obtains the flag that whether to support do not disturb mode. * diff --git a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h index e2c335a9a59340571cd3ce61bc644e9989e8ac59..8a3ca48633fedb090fecfd8a0a65d6016bb4bcf9 100644 --- a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h +++ b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h @@ -138,6 +138,8 @@ namespace Notification { GET_SMART_REMINDER_ENABLED, GET_SLOT_BY_BUNDLE, CANCEL_AS_BUNDLE_WITH_AGENT, + ADD_DO_NOTDISTURB_PROFILES, + REMOVE_DO_NOT_DISTURB_PROFILES, }; } } diff --git a/frameworks/core/src/ans_manager_proxy_disturb.cpp b/frameworks/core/src/ans_manager_proxy_disturb.cpp index 5cd75da8262501299f2db935d6f8638a9106754b..16e141ade908590f3e5bf08c1fe5df1cffd8d790 100644 --- a/frameworks/core/src/ans_manager_proxy_disturb.cpp +++ b/frameworks/core/src/ans_manager_proxy_disturb.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2023 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -93,6 +93,73 @@ ErrCode AnsManagerProxy::GetDoNotDisturbDate(sptr return result; } +ErrCode AnsManagerProxy::AddDoNotDisturbProfiles(const std::vector> &profiles) +{ + if (profiles.empty()) { + ANS_LOGW("The profiles is empty."); + return ERR_ANS_INVALID_PARAM; + } + if (profiles.size() > MAX_STATUS_VECTOR_NUM) { + ANS_LOGE("The profiles is exceeds limit."); + return ERR_ANS_INVALID_PARAM; + } + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("Write interface token error."); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!WriteParcelableVector(profiles, data)) { + ANS_LOGE("Write profiles vector error."); + return ERR_ANS_PARCELABLE_FAILED; + } + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::ADD_DO_NOTDISTURB_PROFILES, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("Transact ErrCode is %{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("Read result error."); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} + +ErrCode AnsManagerProxy::RemoveDoNotDisturbProfiles(const std::vector> &profiles) +{ + if (profiles.empty()) { + ANS_LOGW("The profiles is empty."); + return ERR_ANS_INVALID_PARAM; + } + if (profiles.size() > MAX_STATUS_VECTOR_NUM) { + ANS_LOGE("The profiles is exceeds limit."); + return ERR_ANS_INVALID_PARAM; + } + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("Write interface token error."); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!WriteParcelableVector(profiles, data)) { + ANS_LOGE("Write profiles vector error."); + return ERR_ANS_PARCELABLE_FAILED; + } + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::REMOVE_DO_NOT_DISTURB_PROFILES, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("Transact ErrCode is %{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + if (!reply.ReadInt32(result)) { + ANS_LOGE("Read result error."); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} + ErrCode AnsManagerProxy::DoesSupportDoNotDisturbMode(bool &doesSupport) { MessageParcel data; diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index 09731e50a55e02a5babdac4621c396fd33b7a90c..3954b077f50b8e252e0d73906ca0cdeb09e8c16e 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -310,6 +310,12 @@ const std::map> profiles; + if (!ReadParcelableVector(profiles, data)) { + ANS_LOGE("Read profiles failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (profiles.size() > MAX_STATUS_VECTOR_NUM) { + ANS_LOGE("The profiles is exceeds limit."); + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = AddDoNotDisturbProfiles(profiles); + if (!reply.WriteInt32(result)) { + ANS_LOGE("Write result failed, ErrCode is %{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleSetDistributedEnabledByBundle(MessageParcel &data, MessageParcel &reply) { ANS_LOGD("enter"); @@ -2165,6 +2192,27 @@ ErrCode AnsManagerStub::HandleSetDistributedEnabledByBundle(MessageParcel &data, return ERR_OK; } +ErrCode AnsManagerStub::HandleRemoveDoNotDisturbProfiles(MessageParcel &data, MessageParcel &reply) +{ + std::vector> profiles; + if (!ReadParcelableVector(profiles, data)) { + ANS_LOGE("Read profiles failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (profiles.size() > MAX_STATUS_VECTOR_NUM) { + ANS_LOGE("The profiles is exceeds limit."); + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = RemoveDoNotDisturbProfiles(profiles); + if (!reply.WriteInt32(result)) { + ANS_LOGE("Write result failed, ErrCode is %{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleIsDistributedEnabledByBundle(MessageParcel &data, MessageParcel &reply) { ANS_LOGD("enter"); diff --git a/frameworks/core/src/ans_manager_stub_invalid.cpp b/frameworks/core/src/ans_manager_stub_invalid.cpp index cd246d93fce5c48adc8f6405d5c0d4e67fbb4ec7..66b621fb9908373cf7e6d894457660d365a20916 100644 --- a/frameworks/core/src/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/ans_manager_stub_invalid.cpp @@ -374,6 +374,18 @@ ErrCode AnsManagerStub::GetDoNotDisturbDate(sptr & return ERR_INVALID_OPERATION; } +ErrCode AnsManagerStub::AddDoNotDisturbProfiles(const std::vector> &profiles) +{ + ANS_LOGD("Called."); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::RemoveDoNotDisturbProfiles(const std::vector> &profiles) +{ + ANS_LOGD("Called."); + return ERR_INVALID_OPERATION; +} + ErrCode AnsManagerStub::DoesSupportDoNotDisturbMode(bool &doesSupport) { ANS_LOGE("AnsManagerStub::DoesSupportDoNotDisturbMode called!"); diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index da76381d458b3be5db9ed8cc6a4c0f8ef29e1d57..f6945e655a0dec433181f2779a0e56efa7aa1e23 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -904,6 +904,32 @@ ErrCode AnsNotification::GetDoNotDisturbDate(NotificationDoNotDisturbDate &doNot return ret; } +ErrCode AnsNotification::AddDoNotDisturbProfiles(const std::vector> &profiles) +{ + if (profiles.empty()) { + ANS_LOGW("The profiles is empty."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { + ANS_LOGW("Get ans manager proxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->AddDoNotDisturbProfiles(profiles); +} + +ErrCode AnsNotification::RemoveDoNotDisturbProfiles(const std::vector> &profiles) +{ + if (profiles.empty()) { + ANS_LOGW("The profiles is empty."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { + ANS_LOGW("Get ans manager proxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->RemoveDoNotDisturbProfiles(profiles); +} + ErrCode AnsNotification::DoesSupportDoNotDisturbMode(bool &doesSupport) { if (!GetAnsManagerProxy()) { diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index 86aa99b45fa42bc62f3dd97fdbce9a4a703ce723..30cc6e0663beca3187af159f59b91a0ed803d2f1 100755 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -316,6 +316,16 @@ public: return ERR_ANS_INVALID_PARAM; } + ErrCode AddDoNotDisturbProfiles(const std::vector> &profiles) override + { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode RemoveDoNotDisturbProfiles(const std::vector> &profiles) override + { + return ERR_ANS_INVALID_PARAM; + } + ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override { return ERR_ANS_INVALID_PARAM; diff --git a/frameworks/js/napi/include/disturb_mode.h b/frameworks/js/napi/include/disturb_mode.h index a0309b909345b478462b2c8f2bb74a6284c4892c..31b784e560b592848b430701fbab25973ca68ea9 100644 --- a/frameworks/js/napi/include/disturb_mode.h +++ b/frameworks/js/napi/include/disturb_mode.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -41,6 +41,13 @@ struct AsyncCallbackInfoSetDoNotDisturb { CallbackPromiseInfo info; }; +struct AsyncCallbackInfoDoNotDisturbProfile { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + std::vector> profiles; + CallbackPromiseInfo info; +}; + struct AsyncCallbackInfoGetDoNotDisturb { napi_env env = nullptr; napi_async_work asyncWork = nullptr; @@ -63,6 +70,9 @@ napi_value SupportDoNotDisturbMode(napi_env env, napi_callback_info info); napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, SetDoNotDisturbDateParams ¶ms); napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetDoNotDisturbDateParams ¶ms); +bool ParseProfilesParameters( + const napi_env &env, const napi_callback_info &info, std::vector> &profiles); +bool AnalyseTrustlist(const napi_env &env, const napi_value &value, sptr &profile); } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_INCLUDE_DISTURB_MODE_H \ No newline at end of file diff --git a/frameworks/js/napi/include/manager/napi_disturb_mode.h b/frameworks/js/napi/include/manager/napi_disturb_mode.h index 4cbf88d3ef34d91de8ac136f4106bc44afa3a542..4bf0af5b21e2008513bbb044c527f6dd11f8f7c4 100644 --- a/frameworks/js/napi/include/manager/napi_disturb_mode.h +++ b/frameworks/js/napi/include/manager/napi_disturb_mode.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -24,6 +24,8 @@ using namespace OHOS::Notification; napi_value NapiSetDoNotDisturbDate(napi_env env, napi_callback_info info); napi_value NapiGetDoNotDisturbDate(napi_env env, napi_callback_info info); napi_value NapiSupportDoNotDisturbMode(napi_env env, napi_callback_info info); +napi_value NapiAddDoNotDisturbProfiles(napi_env env, napi_callback_info info); +napi_value NapiRemoveDoNotDisturbProfiles(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_DISTURB_MODE_H \ No newline at end of file diff --git a/frameworks/js/napi/src/disturb_mode.cpp b/frameworks/js/napi/src/disturb_mode.cpp index e1938e4ef8632bf418364fcce410467de0091fa4..36568f2628b8a5914c16dc4c1c65103cc7cb2670 100644 --- a/frameworks/js/napi/src/disturb_mode.cpp +++ b/frameworks/js/napi/src/disturb_mode.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2023 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -20,6 +20,7 @@ namespace NotificationNapi { const int SET_DISTURB_MAX_PARA = 3; const int SET_DISTURB_MIN_PARA = 1; const int GET_DISTURB_MAX_PARA = 2; +const int DISTURB_PROFILES_PARA = 1; napi_value GetDoNotDisturbDate(const napi_env &env, const napi_value &argv, SetDoNotDisturbDateParams ¶ms) { @@ -85,6 +86,90 @@ napi_value GetDoNotDisturbDate(const napi_env &env, const napi_value &argv, SetD return Common::NapiGetNull(env); } +bool GetDoNotDisturbProfile( + const napi_env &env, const napi_value &value, sptr &profile) +{ + ANS_LOGD("Called."); + bool hasProperty = false; + NAPI_CALL_BASE(env, napi_has_named_property(env, value, "id", &hasProperty), false); + if (!hasProperty) { + ANS_LOGE("Wrong argument type. Property type expected."); + return false; + } + int profileId = 0; + napi_value obj = nullptr; + napi_get_named_property(env, value, "id", &obj); + napi_valuetype valuetype = napi_undefined; + NAPI_CALL_BASE(env, napi_typeof(env, obj, &valuetype), false); + if (valuetype != napi_number) { + ANS_LOGE("Wrong argument type. Number expected."); + return false; + } + napi_get_value_int32(env, obj, &profileId); + ANS_LOGE("ProfileId is: %{public}d", profileId); + profile->SetProfileId(profileId); + + NAPI_CALL_BASE(env, napi_has_named_property(env, value, "name", &hasProperty), false); + if (!hasProperty) { + ANS_LOGE("Wrong argument type. Property type expected."); + return false; + } + char name[STR_MAX_SIZE] = {0}; + napi_get_named_property(env, value, "name", &obj); + NAPI_CALL_BASE(env, napi_typeof(env, obj, &valuetype), false); + if (valuetype != napi_string) { + ANS_LOGE("Wrong argument type. String expected."); + return false; + } + size_t strLen = 0; + NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, obj, name, STR_MAX_SIZE - 1, &strLen), false); + ANS_LOGD("The do not disturb profile name is: %{public}s", name); + profile->SetProfileName(name); + + return AnalyseTrustlist(env, value, profile); +} + +bool AnalyseTrustlist(const napi_env &env, const napi_value &value, sptr &profile) +{ + bool hasProperty = false; + NAPI_CALL_BASE(env, napi_has_named_property(env, value, "trustlist", &hasProperty), false); + if (!hasProperty) { + return true; + } + napi_value obj = nullptr; + napi_get_named_property(env, value, "trustlist", &obj); + bool isArray = false; + NAPI_CALL_BASE(env, napi_is_array(env, obj, &isArray), false); + if (!isArray) { + ANS_LOGE("Value is not an array."); + return false; + } + uint32_t length = 0; + napi_get_array_length(env, obj, &length); + if (length == 0) { + ANS_LOGD("The array is empty."); + return true; + } + std::vector options; + for (size_t index = 0; index < length; index++) { + napi_value nOption = nullptr; + napi_get_element(env, obj, index, &nOption); + napi_valuetype valuetype = napi_undefined; + NAPI_CALL_BASE(env, napi_typeof(env, nOption, &valuetype), false); + if (valuetype != napi_object) { + ANS_LOGE("Wrong argument type. Object expected."); + return false; + } + NotificationBundleOption option; + if (!Common::GetBundleOption(env, nOption, option)) { + return false; + } + options.emplace_back(option); + } + profile->SetProfileTrustList(options); + return true; +} + napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, SetDoNotDisturbDateParams ¶ms) { ANS_LOGD("enter"); @@ -138,6 +223,48 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, return Common::NapiGetNull(env); } +bool ParseProfilesParameters( + const napi_env &env, const napi_callback_info &info, std::vector> &profiles) +{ + ANS_LOGD("Called."); + size_t argc = DISTURB_PROFILES_PARA; + napi_value argv[DISTURB_PROFILES_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL_BASE(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL), false); + if (argc != DISTURB_PROFILES_PARA) { + ANS_LOGE("Wrong number of arguments."); + return false; + } + napi_valuetype valuetype = napi_undefined; + bool isArray = false; + napi_is_array(env, argv[PARAM0], &isArray); + if (!isArray) { + ANS_LOGE("Wrong argument type. Array expected."); + return false; + } + uint32_t length = 0; + napi_get_array_length(env, argv[PARAM0], &length); + if (length == 0) { + ANS_LOGD("The array is empty."); + return false; + } + for (size_t index = 0; index < length; index++) { + napi_value nProfile = nullptr; + napi_get_element(env, argv[PARAM0], index, &nProfile); + NAPI_CALL_BASE(env, napi_typeof(env, nProfile, &valuetype), false); + if (valuetype != napi_object) { + ANS_LOGE("Wrong argument type. Object expected."); + return false; + } + sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); + if (!GetDoNotDisturbProfile(env, nProfile, profile)) { + return false; + } + profiles.emplace_back(profile); + } + return true; +} + napi_value SetDoNotDisturbDate(napi_env env, napi_callback_info info) { ANS_LOGD("enter"); diff --git a/frameworks/js/napi/src/manager/init_module.cpp b/frameworks/js/napi/src/manager/init_module.cpp index fb3d48756d2d35fbfea4f69605eda92bad60d3f8..4e35fb40f389c4038c06c91fca0f470bc03057f6 100644 --- a/frameworks/js/napi/src/manager/init_module.cpp +++ b/frameworks/js/napi/src/manager/init_module.cpp @@ -97,6 +97,8 @@ napi_value NotificationManagerInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("isSupportTemplate", NapiIsSupportTemplate), DECLARE_NAPI_FUNCTION("setDoNotDisturbDate", NapiSetDoNotDisturbDate), DECLARE_NAPI_FUNCTION("getDoNotDisturbDate", NapiGetDoNotDisturbDate), + DECLARE_NAPI_FUNCTION("addDoNotDisturbProfile", NapiAddDoNotDisturbProfiles), + DECLARE_NAPI_FUNCTION("removeDoNotDisturbProfile", NapiRemoveDoNotDisturbProfiles), DECLARE_NAPI_FUNCTION("supportDoNotDisturbMode", NapiSupportDoNotDisturbMode), DECLARE_NAPI_FUNCTION("isSupportDoNotDisturbMode", NapiSupportDoNotDisturbMode), DECLARE_NAPI_FUNCTION("isDistributedEnabled", NapiIsDistributedEnabled), diff --git a/frameworks/js/napi/src/manager/napi_disturb_mode.cpp b/frameworks/js/napi/src/manager/napi_disturb_mode.cpp index 1adeac1262d97775796f5ca746449883735bc177..aabd91167e63f36dc7b2808c356e03c9f13362af 100644 --- a/frameworks/js/napi/src/manager/napi_disturb_mode.cpp +++ b/frameworks/js/napi/src/manager/napi_disturb_mode.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -85,6 +85,96 @@ napi_value NapiSetDoNotDisturbDate(napi_env env, napi_callback_info info) } } +napi_value NapiAddDoNotDisturbProfiles(napi_env env, napi_callback_info info) +{ + ANS_LOGD("Called."); + std::vector> profiles; + if (!ParseProfilesParameters(env, info, profiles)) { + Common::NapiThrow(env, ERROR_PARAM_INVALID); + return Common::NapiGetUndefined(env); + } + AsyncCallbackInfoDoNotDisturbProfile *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoDoNotDisturbProfile{.env = env, .asyncWork = nullptr, .profiles = profiles}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, nullptr); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, nullptr, asynccallbackinfo->info, promise); + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "AddDoNotDisturbProfiles", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, resourceName, [](napi_env env, void *data) { + ANS_LOGE("Napi add do not disturb profiles work excute."); + AsyncCallbackInfoDoNotDisturbProfile *asynccallbackinfo = + static_cast(data); + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = + NotificationHelper::AddDoNotDisturbProfiles(asynccallbackinfo->profiles); + } + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGE("Napi add do not disturb profiles work complete."); + AsyncCallbackInfoDoNotDisturbProfile *asynccallbackinfo = + static_cast(data); + if (asynccallbackinfo) { + Common::CreateReturnValue(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + napi_queue_async_work_with_qos(env, asynccallbackinfo->asyncWork, napi_qos_user_initiated); + return promise; +} + +napi_value NapiRemoveDoNotDisturbProfiles(napi_env env, napi_callback_info info) +{ + ANS_LOGD("Called."); + std::vector> profiles; + if (!ParseProfilesParameters(env, info, profiles)) { + Common::NapiThrow(env, ERROR_PARAM_INVALID); + return Common::NapiGetUndefined(env); + } + AsyncCallbackInfoDoNotDisturbProfile *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoDoNotDisturbProfile{.env = env, .asyncWork = nullptr, .profiles = profiles}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, nullptr); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, nullptr, asynccallbackinfo->info, promise); + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "RemoveDoNotDisturbProfiles", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, resourceName, [](napi_env env, void *data) { + ANS_LOGE("Napi remove do not disturb profiles work excute."); + AsyncCallbackInfoDoNotDisturbProfile *asynccallbackinfo = + static_cast(data); + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = + NotificationHelper::RemoveDoNotDisturbProfiles(asynccallbackinfo->profiles); + } + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGE("Napi remove do not disturb profiles work complete."); + AsyncCallbackInfoDoNotDisturbProfile *asynccallbackinfo = + static_cast(data); + if (asynccallbackinfo) { + Common::CreateReturnValue(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + napi_queue_async_work_with_qos(env, asynccallbackinfo->asyncWork, napi_qos_user_initiated); + return promise; +} + void AsyncCompleteCallbackNapiGetDoNotDisturbDate(napi_env env, napi_status status, void *data) { ANS_LOGD("enter"); diff --git a/interfaces/inner_api/notification_do_not_disturb_profile.h b/interfaces/inner_api/notification_do_not_disturb_profile.h new file mode 100644 index 0000000000000000000000000000000000000000..72bdfe1911d42dfbf415b61c3c4893082b546d0d --- /dev/null +++ b/interfaces/inner_api/notification_do_not_disturb_profile.h @@ -0,0 +1,115 @@ +/* + * 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_DO_NOT_DISTURB_PROFILE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_DO_NOT_DISTURB_PROFILE_H + +#include "notification_bundle_option.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationDoNotDisturbProfile : public Parcelable { +public: + /** + * Default constructor used to create a NotificationDoNotDisturbProfile instance. + */ + NotificationDoNotDisturbProfile() = default; + + /** + * A constructor used to create a NotificationDoNotDisturbProfile instance with the input parameters passed. + * + * @param id Indicates the profile id to add. + * @param name Indicates the profile name to add. + * @param trustlist Indicates the profile trustlist to add. + */ + NotificationDoNotDisturbProfile( + int32_t id, const std::string &name, const std::vector &trustList); + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationDoNotDisturbProfile() = default; + + /** + * Sets profile id for this NotificationDoNotDisturbProfile. + * + * @param profileId Indicates the profile id to add. + */ + void SetProfileId(int32_t id); + + /** + * Sets profile name for this NotificationDoNotDisturbProfile. + * + * @param profileName Indicates the profile name to add. + */ + void SetProfileName(const std::string &name); + + /** + * Sets profile trustlist for this NotificationDoNotDisturbProfile. + * + * @param profileTrustlist Indicates the profile trustlist to add. + * For available values, see NotificationBundleOption. + */ + void SetProfileTrustList(const std::vector &trustList); + + /** + * Obtains the profile id of this NotificationDoNotDisturbProfile. + * + * @return the profile id of this NotificationDoNotDisturbProfile. + */ + int32_t GetProfileId() const; + + /** + * Obtains the profile name of this NotificationDoNotDisturbProfile. + * + * @return the profile name of this NotificationDoNotDisturbProfile. + */ + std::string GetProfileName() const; + + /** + * Obtains the profile trustlist of this NotificationDoNotDisturbProfile. + * + * @return the profile trustlist of this NotificationDoNotDisturbProfile, + * For available values, see NotificationBundleOption. + */ + std::vector GetProfileTrustlist() const; + + /** + * Marshal a object into a Parcel. + * + * @param parcel the object into the parcel + */ + bool Marshalling(Parcel &parcel) const override; + + /** + * Read a NotificationDoNotDisturbProfile object from a Parcel. + * + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel); + + static NotificationDoNotDisturbProfile *Unmarshalling(Parcel &parcel); + std::string ToJson(); + void FromJson(const std::string &value); + +private: + int32_t id_; + std::string name_; + std::vector trustList_; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_DO_NOT_DISTURB_PROFILE_H \ No newline at end of file diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index 879e34f44a6988afaf06e9c8b1e11567aea964fb..5f506d20dd6808226ba78d5e4fa5ffcdcec50d5c 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -20,6 +20,7 @@ #include "notification_bundle_option.h" #include "notification_button_option.h" #include "notification_do_not_disturb_date.h" +#include "notification_do_not_disturb_profile.h" #include "enabled_notification_callback_data.h" #include "notification_request.h" #include "notification_slot.h" @@ -790,6 +791,24 @@ public: */ static ErrCode GetDoNotDisturbDate(const int32_t &userId, NotificationDoNotDisturbDate &doNotDisturbDate); + /** + * @brief Obtains the do not disturb on a specified user. + * @note Your application must have system signature to call this method. + * + * @param profiles Indicates the do not disturb time to add. + * @return Returns set do not disturb time result. + */ + static ErrCode AddDoNotDisturbProfiles(const std::vector> &profiles); + + /** + * @brief Obtains the do not disturb on a specified user. + * @note Your application must have system signature to call this method. + * + * @param profiles Indicates the do not disturb time to remove. + * @return Returns set do not disturb time result. + */ + static ErrCode RemoveDoNotDisturbProfiles(const std::vector> &profiles); + /** * Set whether the application slot is enabled. * diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index f6b83c08dab9e7e2ca6f6816fe8c364e83f55896..80ca3338727bb9b53574996c54604841e1c7631f 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2023 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -45,6 +45,7 @@ ohos_shared_library("libans") { sources = [ "src/access_token_helper.cpp", + "src/advanced_datashare_helper.cpp", "src/advanced_notification_event_service.cpp", "src/advanced_notification_inline.cpp", "src/advanced_notification_live_view_service.cpp", diff --git a/services/ans/include/advanced_datashare_helper.h b/services/ans/include/advanced_datashare_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..b86d666edab25d0b6a1c6faf17988e0a5983949c --- /dev/null +++ b/services/ans/include/advanced_datashare_helper.h @@ -0,0 +1,46 @@ +/* + * 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 NOTIFICATION_ADVANCED_DATASHAER_HELPER_H +#define NOTIFICATION_ADVANCED_DATASHAER_HELPER_H + +#include "datashare_helper.h" +#include "iremote_broker.h" +#include "singleton.h" +#include "system_ability_definition.h" +#include "uri.h" + +namespace OHOS { +namespace Notification { +namespace { +constexpr const char *KEY_FOCUS_MODE_ENABLE = "focus_mode_enable"; +constexpr const char *KEY_FOCUS_MODE_PROFILE = "focus_mode_profile"; +} // namespace + +class AdvancedDatashareHelper : DelayedSingleton { +public: + AdvancedDatashareHelper(); + ~AdvancedDatashareHelper() = default; + bool Query(Uri &uri, const std::string &key, std::string &value); + std::string GetFocusModeEnableUri() const; + std::string GetFocusModeProfileUri() const; + +private: + void CreateDataShareHelper(); + std::shared_ptr dataShareHelper_ = nullptr; +}; +} // namespace Notification +} // namespace OHOS +#endif // NOTIFICATION_ADVANCED_DATASHAER_HELPER_H \ No newline at end of file diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 06e18d018fa3b9d067f5df4df3d876bc38f270a0..285ce9f80ee9684cf33d91c02272fbe733d51702 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -35,6 +35,7 @@ #include "notification.h" #include "notification_bundle_option.h" #include "notification_dialog_manager.h" +#include "notification_do_not_disturb_profile.h" #include "notification_record.h" #include "notification_slot_filter.h" #include "notification_sorting_map.h" @@ -555,6 +556,22 @@ public: */ ErrCode GetDoNotDisturbDate(sptr &date) override; + /** + * @brief Add Do Not Disturb profiles. + * + * @param profiles Indicates the list of NotificationDoNotDisturbProfile objects to add. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddDoNotDisturbProfiles(const std::vector> &profiles) override; + + /** + * @brief Remove Do Not Disturb profiles. + * + * @param profiles Indicates the list of NotificationDoNotDisturbProfile objects to remove. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode RemoveDoNotDisturbProfiles(const std::vector> &profiles) override; + /** * @brief Get whether Do Not Disturb mode is supported. * @@ -1175,6 +1192,9 @@ private: void StartArchiveTimer(const std::shared_ptr &record); void CancelArchiveTimer(const std::shared_ptr &record); void ProcForDeleteLiveView(const std::shared_ptr &record); + void QueryDoNotDisturbProfile(std::string &enable, std::string &profileId); + void CheckDoNotDisturbProfile(const std::shared_ptr &record); + void DoNotDisturbUpdataReminderFlags(const std::shared_ptr &record); ErrCode CheckCommonParams(); std::shared_ptr GetRecordFromNotificationList( int32_t notificationId, int32_t uid, const std::string &label, const std::string &bundleName); diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 736b224c7846ff480031aae8c09784274a7099ed..8b1529e7a6d4229ea17bfefe5ee5ea73dfd59ad5 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -249,6 +249,25 @@ public: ErrCode SetDoNotDisturbDate(const int32_t &userId, const sptr date); ErrCode GetTemplateSupported(const std::string &templateName, bool &support); + /** + * @brief Add do not disturb profiles from DB. + * + * @param userId Indicates user. + * @param profiles Indicates to add do not disturb profiles. + * @return Return ERR_OK on success, others on failure. + */ + ErrCode AddDoNotDisturbProfiles(int32_t userId, const std::vector> profiles); + + /** + * @brief Remove do not disturb profiles from DB. + * + * @param userId Indicates user. + * @param profiles Indicates to remove do not disturb profiles. + * @return Return ERR_OK on success, others on failure. + */ + ErrCode RemoveDoNotDisturbProfiles( + int32_t userId, const std::vector> profiles); + /** * @brief Obtains allow notification application list. * @@ -331,6 +350,9 @@ public: int32_t GetKvFromDb(const std::string &key, std::string &value); int32_t GetBatchKvsFromDb(const std::string &key, std::unordered_map &values); int32_t DeleteKvFromDb(const std::string &key); + ErrCode GetDonotDisturbProfile(int32_t profileId, int32_t userId, sptr &profile); + bool CheckDoNotDisturbProfileID(int32_t profileId); + private: ErrCode CheckSlotForCreateSlot(const sptr &bundleOption, const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const; diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index d07c5c8c9257c028d4b4a456d0af3679200bcf21..6bd5ff5496c62aef673895a8496e37f497d89b04 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -207,6 +207,10 @@ public: bool RemoveNotificationEnable(const int32_t userId); bool RemoveDoNotDisturbDate(const int32_t userId); bool RemoveAnsBundleDbInfo(std::string bundleName, int32_t uid); + bool AddDoNotDisturbProfiles(int32_t userId, const std::vector> &profiles); + bool RemoveDoNotDisturbProfiles( + int32_t userId, const std::vector> &profiles); + bool GetDoNotDisturbProfiles(const std::string &key, sptr &profile); bool RemoveEnabledDbByBundleName(std::string bundleName); int32_t SetKvToDb(const std::string &key, const std::string &value); int32_t GetKvFromDb(const std::string &key, std::string &value); @@ -259,6 +263,7 @@ private: void ParseDoNotDisturbBeginDate(NotificationPreferencesInfo &info); void ParseDoNotDisturbEndDate(NotificationPreferencesInfo &info); void ParseEnableAllNotification(NotificationPreferencesInfo &info); + void ParseGetDoNotDisturbProfile(NotificationPreferencesInfo &info); void ParseBundleName(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; void ParseBundleImportance(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; void ParseBundleSlotFlags(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; @@ -294,6 +299,7 @@ private: void GetDoNotDisturbBeginDate(NotificationPreferencesInfo &info, int32_t userId); void GetDoNotDisturbEndDate(NotificationPreferencesInfo &info, int32_t userId); void GetEnableAllNotification(NotificationPreferencesInfo &info, int32_t userId); + void GetDoNotDisturbProfile(NotificationPreferencesInfo &info, int32_t userId); static const std::map &, std::string &)>> diff --git a/services/ans/include/notification_preferences_info.h b/services/ans/include/notification_preferences_info.h index a6fb9c35356ac4d52c2d93c5a3548472695332df..4d8ae19d642f239b0d0a5b0e4a6740d9e1c87abf 100644 --- a/services/ans/include/notification_preferences_info.h +++ b/services/ans/include/notification_preferences_info.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -310,9 +310,15 @@ public: void RemoveNotificationEnable(const int32_t userId); void RemoveDoNotDisturbDate(const int32_t userId); void SetBundleInfoFromDb(const BundleInfo &info, std::string bundleKey); + std::string MakeDoNotDisturbProfileKey(int32_t userId, int32_t profileId); + void AddDoNotDisturbProfiles(int32_t userId, const std::vector> &profiles); + void RemoveDoNotDisturbProfiles(int32_t userId, const std::vector> &profiles); + bool GetDoNotDisturbProfiles(int32_t profileId, int32_t userId, sptr &profiles); + private: std::map isEnabledAllNotification_; std::map> doNotDisturbDate_; + std::map> doNotDisturbProfiles_; std::map infos_; }; } // namespace Notification diff --git a/services/ans/src/advanced_datashare_helper.cpp b/services/ans/src/advanced_datashare_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9fa8b56a85f31cfb3db78ff306194c734685747a --- /dev/null +++ b/services/ans/src/advanced_datashare_helper.cpp @@ -0,0 +1,106 @@ +/* + * 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 "advanced_datashare_helper.h" + +#include "ans_log_wrapper.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "message_parcel.h" +#include "os_account_manager.h" +#include "singleton.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { +namespace { +constexpr const char *SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility"; +constexpr const char *USER_SETTINGS_DATA_URI = + "datashare:///com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_"; +constexpr const char *FOCUS_MODE_ENABLE_URI = "?Proxy=true&key=focus_mode_enable"; +constexpr const char *FOCUS_MODE_PROFILE_URI = "?Proxy=true&key=focus_mode_profile"; +constexpr const char *ADVANCED_DATA_COLUMN_KEYWORD = "KEYWORD"; +constexpr const char *ADVANCED_DATA_COLUMN_VALUE = "VALUE"; +} // namespace +AdvancedDatashareHelper::AdvancedDatashareHelper() +{ + CreateDataShareHelper(); +} + +void AdvancedDatashareHelper::CreateDataShareHelper() +{ + sptr saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (saManager == nullptr) { + ANS_LOGE("The sa manager is nullptr."); + return; + } + sptr remoteObj = saManager->GetSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID); + if (remoteObj == nullptr) { + ANS_LOGE("The remoteObj is nullptr."); + return; + } + dataShareHelper_ = DataShare::DataShareHelper::Creator(remoteObj, SETTINGS_DATA_EXT_URI); +} + +bool AdvancedDatashareHelper::Query(Uri &uri, const std::string &key, std::string &value) +{ + if (dataShareHelper_ == nullptr) { + ANS_LOGE("The data share helper is nullptr."); + return false; + } + DataShare::DataSharePredicates predicates; + std::vector columns; + predicates.EqualTo(ADVANCED_DATA_COLUMN_KEYWORD, key); + auto result = dataShareHelper_->Query(uri, predicates, columns); + if (result == nullptr) { + ANS_LOGE("Query error, result is null."); + return false; + } + if (result->GoToFirstRow() != DataShare::E_OK) { + ANS_LOGE("Query failed, go to first row error."); + result->Close(); + return false; + } + int32_t columnIndex; + result->GetColumnIndex(ADVANCED_DATA_COLUMN_VALUE, columnIndex); + result->GetString(columnIndex, value); + result->Close(); + ANS_LOGD("Query success, value[%{public}s]", value.c_str()); + return true; +} + +std::string AdvancedDatashareHelper::GetFocusModeEnableUri() const +{ + std::vector accountIds; + OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountIds); + std::string userId = "100"; + if (!accountIds.empty()) { + userId = std::to_string(accountIds[0]); + } + return USER_SETTINGS_DATA_URI + userId + FOCUS_MODE_ENABLE_URI; +} + +std::string AdvancedDatashareHelper::GetFocusModeProfileUri() const +{ + std::vector accountIds; + OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountIds); + std::string userId = "100"; + if (!accountIds.empty()) { + userId = std::to_string(accountIds[0]); + } + return USER_SETTINGS_DATA_URI + userId + FOCUS_MODE_PROFILE_URI; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 7cf666d409796111a1c573b81e6c8775e1cef0ea..1400e75c6cacd1e961c4b259f0b871b0057eba87 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -23,6 +23,7 @@ #include "ability_info.h" #include "access_token_helper.h" #include "accesstoken_kit.h" +#include "advanced_datashare_helper.h" #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" @@ -81,7 +82,9 @@ constexpr int32_t UI_HALF = 2; constexpr int32_t MAX_LIVEVIEW_HINT_COUNT = 3; const std::string NOTIFICATION_ANS_CHECK_SA_PERMISSION = "notification.ans.check.sa.permission"; - +const std::string MMS_BUNDLE_NAME = "com.ohos.mms"; +const std::string CONTACTS_BUNDLE_NAME = "com.ohos.contacts"; +const std::string DO_NOT_DISTURB_MODE = "1"; } // namespace sptr AdvancedNotificationService::instance_; @@ -588,6 +591,94 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification( return result; } +void AdvancedNotificationService::QueryDoNotDisturbProfile(std::string &enable, std::string &profileId) +{ + auto datashareHelper = DelayedSingleton::GetInstance(); + if (datashareHelper == nullptr) { + ANS_LOGE("The data share helper is nullptr."); + return; + } + Uri enableUri(datashareHelper->GetFocusModeEnableUri()); + bool ret = datashareHelper->Query(enableUri, KEY_FOCUS_MODE_ENABLE, enable); + if (!ret) { + ANS_LOGE("Query focus mode enable fail."); + return; + } + if (enable != DO_NOT_DISTURB_MODE) { + ANS_LOGI("Currently not is do not disturb mode."); + return; + } + Uri idUri(datashareHelper->GetFocusModeProfileUri()); + ret = datashareHelper->Query(idUri, KEY_FOCUS_MODE_PROFILE, profileId); + if (!ret) { + ANS_LOGE("Query focus mode id fail."); + return; + } +} + +void AdvancedNotificationService::CheckDoNotDisturbProfile(const std::shared_ptr &record) +{ + ANS_LOGD("Called."); + if (record == nullptr && record->notification == nullptr) { + ANS_LOGE("Make notification record failed."); + return; + } + std::string enable; + std::string profileId; + QueryDoNotDisturbProfile(enable, profileId); + if (enable != DO_NOT_DISTURB_MODE) { + ANS_LOGI("Currently not is do not disturb mode."); + return; + } + std::string bundleName = GetClientBundleName(); + if (bundleName == MMS_BUNDLE_NAME || bundleName == CONTACTS_BUNDLE_NAME) { + ANS_LOGI("Currently in do not disturb mode, the bundle name is mms or contacts, keep reminder method."); + return; + } + sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); + int32_t userId = record->notification->GetUserId(); + if (NotificationPreferences::GetInstance().GetDonotDisturbProfile(atoi(profileId.c_str()), userId, profile) != + ERR_OK) { + ANS_LOGE("Get do not disturb profile failed."); + return; + } + if (profile == nullptr) { + ANS_LOGE("The do not disturb profile is nullptr."); + return; + } + std::vector trustlist = profile->GetProfileTrustlist(); + for (auto &trust : trustlist) { + if (bundleName == trust.GetBundleName()) { + ANS_LOGW("Do not disturb profile bundle name is in trust."); + return; + } + } + DoNotDisturbUpdataReminderFlags(record); +} + +void AdvancedNotificationService::DoNotDisturbUpdataReminderFlags(const std::shared_ptr &record) +{ + ANS_LOGD("Called."); + if (record == nullptr && record->request == nullptr && record->notification == nullptr) { + ANS_LOGE("Make notification record failed."); + return; + } + auto flags = record->request->GetFlags(); + if (flags == nullptr) { + ANS_LOGE("The flags is nullptr."); + return; + } + flags->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE); + record->notification->SetEnableSound(false); + flags->SetLockScreenVisblenessEnabled(false); + record->request->SetVisibleness(NotificationConstant::VisiblenessType::SECRET); + flags->SetBannerEnabled(false); + flags->SetLightScreenEnabled(false); + flags->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE); + record->notification->SetEnableVibration(false); + flags->SetStatusIconEnabled(false); +} + ErrCode AdvancedNotificationService::UpdateSlotAuthInfo(const std::shared_ptr &record) { ErrCode result = ERR_OK; @@ -1804,6 +1895,7 @@ ErrCode AdvancedNotificationService::AddRecordToMemory( if (isSystemApp) { ChangeNotificationByControlFlags(record); + CheckDoNotDisturbProfile(record); } result = AssignToNotificationList(record); diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 5844273db8170d558a44537889d2887898eb8d13..c24a5086e61455aea9907d0d8d2904993031f2e7 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -779,6 +779,64 @@ ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr> &profiles) +{ + ANS_LOGD("Called."); + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); + if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + return ERR_ANS_PERMISSION_DENIED; + } + if (notificationSvrQueue_ == nullptr) { + ANS_LOGE("Serial queue is invalid."); + return ERR_ANS_INVALID_PARAM; + } + int32_t userId = SUBSCRIBE_USER_INIT; + if (!GetActiveUserId(userId)) { + ANS_LOGW("No active user found."); + return ERR_ANS_GET_ACTIVE_USER_FAILED; + } + ffrt::task_handle handler = + notificationSvrQueue_->submit_h(std::bind([copyUserId = userId, copyProfiles = profiles]() { + ANS_LOGD("The ffrt enter."); + NotificationPreferences::GetInstance().AddDoNotDisturbProfiles(copyUserId, copyProfiles); + })); + notificationSvrQueue_->wait(handler); + return ERR_OK; +} + +ErrCode AdvancedNotificationService::RemoveDoNotDisturbProfiles( + const std::vector> &profiles) +{ + ANS_LOGD("Called."); + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); + if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + return ERR_ANS_PERMISSION_DENIED; + } + if (notificationSvrQueue_ == nullptr) { + ANS_LOGE("Serial queue is invalid."); + return ERR_ANS_INVALID_PARAM; + } + int32_t userId = SUBSCRIBE_USER_INIT; + if (!GetActiveUserId(userId)) { + ANS_LOGW("No active user found."); + return ERR_ANS_GET_ACTIVE_USER_FAILED; + } + ffrt::task_handle handler = + notificationSvrQueue_->submit_h(std::bind([copyUserId = userId, copyProfiles = profiles]() { + ANS_LOGD("The ffrt enter."); + NotificationPreferences::GetInstance().RemoveDoNotDisturbProfiles(copyUserId, copyProfiles); + })); + notificationSvrQueue_->wait(handler); + return ERR_OK; +} + ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSupport) { ANS_LOGD("%{public}s", __FUNCTION__); diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 06a6fa6f349106272a1924be857d40a92d704e67..5aa62462d96add5eed8b3549429b2a92ac4757ef 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -473,6 +473,67 @@ ErrCode NotificationPreferences::SetDoNotDisturbDate(const int32_t &userId, return result; } +bool NotificationPreferences::CheckDoNotDisturbProfileID(int32_t profileId) +{ + if (profileId < FOCUS_MODE_PROFILE_MIN_ID || profileId > FOCUS_MODE_PROFILE_MAX_ID) { + ANS_LOGE("The profile id is out of range."); + return false; + } + return true; +} + +ErrCode NotificationPreferences::AddDoNotDisturbProfiles( + int32_t userId, std::vector> profiles) +{ + ANS_LOGE("Called."); + for (auto profile : profiles) { + if (profile == nullptr) { + ANS_LOGE("The profile is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + if (!CheckDoNotDisturbProfileID(profile->GetProfileId())) { + return ERR_ANS_INVALID_PARAM; + } + } + std::lock_guard lock(preferenceMutex_); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + preferencesInfo.AddDoNotDisturbProfiles(userId, profiles); + if (preferncesDB_ == nullptr) { + return ERR_ANS_SERVICE_NOT_READY; + } + if (!preferncesDB_->AddDoNotDisturbProfiles(userId, profiles)) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + preferencesInfo_ = preferencesInfo; + return ERR_OK; +} + +ErrCode NotificationPreferences::RemoveDoNotDisturbProfiles( + int32_t userId, const std::vector> profiles) +{ + ANS_LOGE("Called."); + for (auto profile : profiles) { + if (profile == nullptr) { + ANS_LOGE("The profile is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + if (!CheckDoNotDisturbProfileID(profile->GetProfileId())) { + return ERR_ANS_INVALID_PARAM; + } + } + std::lock_guard lock(preferenceMutex_); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + preferencesInfo.RemoveDoNotDisturbProfiles(userId, profiles); + if (preferncesDB_ == nullptr) { + return ERR_ANS_SERVICE_NOT_READY; + } + if (!preferncesDB_->RemoveDoNotDisturbProfiles(userId, profiles)) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + preferencesInfo_ = preferencesInfo; + return ERR_OK; +} + ErrCode NotificationPreferences::GetAllNotificationEnabledBundles(std::vector &bundleOption) { ANS_LOGD("Called."); @@ -504,6 +565,20 @@ ErrCode NotificationPreferences::ClearNotificationInRestoreFactorySettings() return result; } +ErrCode NotificationPreferences::GetDonotDisturbProfile( + int32_t profileId, int32_t userId, sptr &profile) +{ + if (!CheckDoNotDisturbProfileID(profileId)) { + return ERR_ANS_INVALID_PARAM; + } + std::lock_guard lock(preferenceMutex_); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + if (!preferencesInfo.GetDoNotDisturbProfiles(profileId, userId, profile)) { + return ERR_ANS_INVALID_PARAM; + } + return ERR_OK; +} + ErrCode NotificationPreferences::CheckSlotForCreateSlot(const sptr &bundleOption, const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const { diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 5bcd4fcb7bd8ef5ee9e490c4235c305063a4c4a7..bf50f6acc96dc70ca30c580e45fcc2157fec201b 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -42,6 +42,11 @@ const static std::string KEY_DO_NOT_DISTURB_BEGIN_DATE = "ans_doNotDisturbBeginD */ const static std::string KEY_DO_NOT_DISTURB_END_DATE = "ans_doNotDisturbEndDate"; +/** + * Indicates that disturbe key which do not disturbe id. + */ +const static std::string KEY_DO_NOT_DISTURB_ID = "ans_doNotDisturbId"; + /** * Indicates that disturbe key which enable all notification. */ @@ -575,6 +580,86 @@ bool NotificationPreferencesDatabase::PutDoNotDisturbDate( return true; } +bool NotificationPreferencesDatabase::AddDoNotDisturbProfiles( + int32_t userId, const std::vector> &profiles) +{ + if (profiles.empty()) { + ANS_LOGE("Invalid dates."); + return false; + } + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + std::unordered_map values; + for (auto profile : profiles) { + if (profile == nullptr) { + ANS_LOGE("The profile is null."); + return false; + } + std::string key = std::string().append(KEY_DO_NOT_DISTURB_ID).append(KEY_UNDER_LINE).append( + std::to_string(userId)).append(KEY_UNDER_LINE).append(std::to_string((int32_t)profile->GetProfileId())); + values[key] = profile->ToJson(); + } + int32_t result = rdbDataManager_->InsertBatchData(values); + if (result != NativeRdb::E_OK) { + ANS_LOGE("Add do not disturb profiles failed."); + return false; + } + return true; +} + +bool NotificationPreferencesDatabase::RemoveDoNotDisturbProfiles( + int32_t userId, const std::vector> &profiles) +{ + if (profiles.empty()) { + ANS_LOGW("Invalid dates."); + return false; + } + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + std::vector keys; + for (auto profile : profiles) { + if (profile == nullptr) { + ANS_LOGE("The profile is null."); + return false; + } + std::string key = std::string().append(KEY_DO_NOT_DISTURB_ID).append(KEY_UNDER_LINE).append( + std::to_string(userId)).append(KEY_UNDER_LINE).append(std::to_string((int32_t)profile->GetProfileId())); + keys.push_back(key); + } + int32_t result = rdbDataManager_->DeleteBathchData(keys); + if (result != NativeRdb::E_OK) { + ANS_LOGE("Delete do not disturb profiles failed."); + return false; + } + return true; +} + +bool NotificationPreferencesDatabase::GetDoNotDisturbProfiles( + const std::string &key, sptr &profile) +{ + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + std::string values; + int32_t result = rdbDataManager_->QueryData(key, values); + if (result != NativeRdb::E_OK) { + ANS_LOGE("Use default value. error code is %{public}d", result); + return false; + } + profile = new (std::nothrow) NotificationDoNotDisturbProfile(); + if (profile == nullptr) { + ANS_LOGE("The profile is null."); + return false; + } + profile->FromJson(values); + return true; +} + void NotificationPreferencesDatabase::GetValueFromDisturbeDB( const std::string &key, std::function callback) { @@ -668,6 +753,7 @@ bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreference ParseDoNotDisturbBeginDate(info); ParseDoNotDisturbEndDate(info); ParseEnableAllNotification(info); + ParseGetDoNotDisturbProfile(info); if (!CheckRdbStore()) { ANS_LOGE("RdbStore is nullptr."); @@ -1211,6 +1297,16 @@ void NotificationPreferencesDatabase::ParseEnableAllNotification(NotificationPre } } +void NotificationPreferencesDatabase::ParseGetDoNotDisturbProfile(NotificationPreferencesInfo &info) +{ + std::vector activeUserId; + OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); + + for (auto iter : activeUserId) { + NotificationPreferencesDatabase::GetDoNotDisturbProfile(info, iter); + } +} + void NotificationPreferencesDatabase::ParseBundleName( NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const { @@ -1491,6 +1587,31 @@ void NotificationPreferencesDatabase::GetEnableAllNotification(NotificationPrefe }); } +void NotificationPreferencesDatabase::GetDoNotDisturbProfile(NotificationPreferencesInfo &info, int32_t userId) +{ + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return; + } + std::unordered_map datas; + int32_t result = rdbDataManager_->QueryAllData(datas); + if (result != NativeRdb::E_OK) { + ANS_LOGE("Query all data failed."); + return; + } + std::vector> profiles; + for (const auto &data : datas) { + std::string key = data.first; + auto result = key.find(KEY_DO_NOT_DISTURB_ID); + if (result != std::string::npos) { + sptr profile; + GetDoNotDisturbProfiles(data.first, profile); + profiles.emplace_back(profile); + } + } + info.AddDoNotDisturbProfiles(userId, profiles); +} + bool NotificationPreferencesDatabase::RemoveNotificationEnable(const int32_t userId) { ANS_LOGD("%{public}s", __FUNCTION__); diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index 60590e9e570b808f2c48e74863cf1a4dc14feae2..07996ccc142f5e543c734d0b122bfee20f69bd32 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace Notification { +const static std::string KEY_UNDER_LINE = "_"; NotificationPreferencesInfo::BundleInfo::BundleInfo() { } @@ -266,6 +267,42 @@ void NotificationPreferencesInfo::SetDoNotDisturbDate(const int32_t &userId, doNotDisturbDate_.insert_or_assign(userId, doNotDisturbDate); } +std::string NotificationPreferencesInfo::MakeDoNotDisturbProfileKey(int32_t userId, int32_t profileId) +{ + std::string key = std::to_string(userId).append(KEY_UNDER_LINE).append(std::to_string(profileId)); + return key; +} + +void NotificationPreferencesInfo::AddDoNotDisturbProfiles( + int32_t userId, const std::vector> &profiles) +{ + for (auto profile : profiles) { + std::string key = MakeDoNotDisturbProfileKey(userId, profile->GetProfileId()); + doNotDisturbProfiles_.insert_or_assign(key, profile); + } +} + +void NotificationPreferencesInfo::RemoveDoNotDisturbProfiles( + int32_t userId, const std::vector> &profiles) +{ + for (auto profile : profiles) { + std::string key = MakeDoNotDisturbProfileKey(userId, profile->GetProfileId()); + doNotDisturbProfiles_.erase(key); + } +} + +bool NotificationPreferencesInfo::GetDoNotDisturbProfiles( + int32_t profileId, int32_t userId, sptr &profile) +{ + std::string key = MakeDoNotDisturbProfileKey(userId, profileId); + auto iter = doNotDisturbProfiles_.find(key); + if (iter != doNotDisturbProfiles_.end()) { + profile = iter->second; + return true; + } + return false; +} + bool NotificationPreferencesInfo::GetDoNotDisturbDate(const int32_t &userId, sptr &doNotDisturbDate) const { diff --git a/services/ans/test/unittest/notification_preferences_database_branch_test/mock_notification_rdb_data_mgr.cpp b/services/ans/test/unittest/notification_preferences_database_branch_test/mock_notification_rdb_data_mgr.cpp index e26ed128aec6aac036be94df1678ca521684d014..0768bcce59a5a70567c3774b252352a7a576a6a2 100755 --- a/services/ans/test/unittest/notification_preferences_database_branch_test/mock_notification_rdb_data_mgr.cpp +++ b/services/ans/test/unittest/notification_preferences_database_branch_test/mock_notification_rdb_data_mgr.cpp @@ -22,6 +22,7 @@ namespace { bool g_mockQueryDataBeginWithKeyRet = true; bool g_mockDeleteBathchDataRet = true; bool g_mockDeleteDataRet = true; + bool g_mockQueryAllData = true; } void MockInit(bool mockRet) @@ -59,6 +60,11 @@ void MockDeleteData(bool mockRet) g_mockDeleteDataRet = mockRet; } +void MockQueryAllData(bool mockRet) +{ + g_mockQueryAllData = mockRet; +} + namespace OHOS { namespace Notification { NotificationDataMgr::NotificationDataMgr(const NotificationRdbConfig ¬ificationRdbConfig) @@ -130,5 +136,13 @@ int32_t NotificationDataMgr::DeleteData(const std::string &key) } return NativeRdb::E_OK; } + +int32_t NotificationDataMgr::QueryAllData(std::unordered_map &values) +{ + if (g_mockQueryAllData == false) { + return NativeRdb::E_ERROR; + } + return NativeRdb::E_OK; +} } }