diff --git a/OAT.xml b/OAT.xml index aa01ceabe357535c840cb743727fb16106185a8e..40b888b56532e719775f2237f805ea8182088e8f 100644 --- a/OAT.xml +++ b/OAT.xml @@ -1,5 +1,5 @@ - + +
{{ requestNotification }}
-
- - +
+
+ +
+
+
+ +
diff --git a/frameworks/ans/dialog/dialog_ui/js/pages/index/index.js b/frameworks/ans/dialog/dialog_ui/js/pages/index/index.js index 928dc3b8b789e0fdcf0c8a6239d2dfde8a806ec1..9c9463b90b63bc234247f02fa3a5982b471defb7 100644 --- a/frameworks/ans/dialog/dialog_ui/js/pages/index/index.js +++ b/frameworks/ans/dialog/dialog_ui/js/pages/index/index.js @@ -1,3 +1,18 @@ +/* + * 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. + */ + import router from '@ohos.router' export default { @@ -10,6 +25,9 @@ export default { }, onInit() { console.info('getParams: ' + JSON.stringify(router.getParams())); + this.requestNotification = this.$t('message.requestNotification'); + this.allowButton = this.$t('message.allowButton'); + this.cancelButton = this.$t('message.cancelButton'); }, onAllow() { console.info('clicked allow'); diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn index a0aa9d6ccf3c7a5039278afb806ca60395040791..17e50e5b8e5a48e16dae2b00f58967adca561472 100644 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -29,7 +29,10 @@ config("ans_innerkits_public_config") { "//third_party/jsoncpp/include", "//utils/system/safwk/native/include", ] - configs = [ "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits_public_config" ] + configs = [ + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits_public_config", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_external_config", + ] } ohos_shared_library("ans_innerkits") { @@ -85,11 +88,12 @@ ohos_shared_library("ans_innerkits") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:wantagent_innerkits", - "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", "samgr_standard:samgr_proxy", ] diff --git a/frameworks/ans/native/src/enabled_notification_callback_data.cpp b/frameworks/ans/native/src/enabled_notification_callback_data.cpp index 32d678a67126baa5d56c2cd8e04de5dbcd2288ff..4346035d4da050139f0e29e10286e1bc4581294c 100644 --- a/frameworks/ans/native/src/enabled_notification_callback_data.cpp +++ b/frameworks/ans/native/src/enabled_notification_callback_data.cpp @@ -96,7 +96,7 @@ EnabledNotificationCallbackData *EnabledNotificationCallbackData::Unmarshalling( bool EnabledNotificationCallbackData::ReadFromParcel(Parcel &parcel) { bundle_ = Str16ToStr8(parcel.ReadString16()); - uid_ = parcel.ReadInt32(); + uid_ = static_cast(parcel.ReadInt32()); enable_ = parcel.ReadBool(); return true; diff --git a/frameworks/ans/native/src/message_user.cpp b/frameworks/ans/native/src/message_user.cpp index 385eafd0f6eee5a71a2cc4740d29038c64047202..ce57886a26dd1ce2414b686951aa4453a88ef670 100644 --- a/frameworks/ans/native/src/message_user.cpp +++ b/frameworks/ans/native/src/message_user.cpp @@ -212,7 +212,7 @@ bool MessageUser::ReadFromParcel(Parcel &parcel) isMachine_ = parcel.ReadBool(); isUserImportant_ = parcel.ReadBool(); - int empty = VALUE_NULL; + int32_t empty = VALUE_NULL; if (!parcel.ReadInt32(empty)) { ANS_LOGE("Failed to read VALUE"); return false; diff --git a/frameworks/ans/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp index 613c42646030dd35bc5e0fceaaac6a6e29f23e53..7723258b80e2da49c025bb80cfe43d1747543a60 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -40,7 +40,7 @@ Notification::Notification(const Notification &other) { enableSound_ = other.enableSound_; enableLight_ = other.enableLight_; - enableViration_ = other.enableViration_; + enableVibration_ = other.enableVibration_; key_ = other.key_; ledLightColor_ = other.ledLightColor_; lockscreenVisibleness_ = other.lockscreenVisibleness_; @@ -69,7 +69,7 @@ bool Notification::EnableSound() const bool Notification::EnableVibrate() const { - return enableViration_; + return enableVibration_; } std::string Notification::GetBundleName() const @@ -145,7 +145,7 @@ Uri Notification::GetSound() const return Uri(""); } -pid_t Notification::GetUid() const +int32_t Notification::GetUid() const { if (request_ == nullptr) { return 0; @@ -230,8 +230,8 @@ bool Notification::MarshallingBool(Parcel &parcel) const return false; } - if (!parcel.WriteBool(enableViration_)) { - ANS_LOGE("Can't write enableViration_"); + if (!parcel.WriteBool(enableVibration_)) { + ANS_LOGE("Can't write enableVibration_"); return false; } @@ -246,7 +246,7 @@ bool Notification::MarshallingBool(Parcel &parcel) const bool Notification::MarshallingString(Parcel &parcel) const { if (!parcel.WriteString(key_)) { - ANS_LOGE("Can't wirte key"); + ANS_LOGE("Can't write key"); return false; } @@ -258,7 +258,7 @@ bool Notification::MarshallingString(Parcel &parcel) const } if (!parcel.WriteString(deviceId_)) { - ANS_LOGE("Can't wirte deviceId"); + ANS_LOGE("Can't write deviceId"); return false; } @@ -344,8 +344,8 @@ void Notification::ReadFromParcelBool(Parcel &parcel) // Read enableSound_ enableSound_ = parcel.ReadBool(); - // Read enableViration_ - enableViration_ = parcel.ReadBool(); + // Read enableVibration_ + enableVibration_ = parcel.ReadBool(); // Read isRemoveAllowed_ isRemoveAllowed_ = parcel.ReadBool(); @@ -427,9 +427,9 @@ void Notification::SetEnableLight(const bool &enable) enableLight_ = enable; } -void Notification::SetEnableViration(const bool &enable) +void Notification::SetEnableVibration(const bool &enable) { - enableViration_ = enable; + enableVibration_ = enable; } void Notification::SetLedLightColor(const int32_t &color) diff --git a/frameworks/ans/native/src/notification_action_button.cpp b/frameworks/ans/native/src/notification_action_button.cpp index cc3ba9f0c52089569b25aeb4d137b040fba6ded2..ea87da8274ec1c68dc4ba6eef8393bb9802d2521 100644 --- a/frameworks/ans/native/src/notification_action_button.cpp +++ b/frameworks/ans/native/src/notification_action_button.cpp @@ -17,8 +17,8 @@ #include "ans_image_util.h" #include "ans_log_wrapper.h" -#include "ohos/aafwk/content/want_params_wrapper.h" #include "want_agent_helper.h" +#include "want_params_wrapper.h" namespace OHOS { namespace Notification { @@ -26,7 +26,7 @@ std::shared_ptr NotificationActionButton::Create(const const std::string &title, const std::shared_ptr &wantAgent, const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, const std::vector> &mimeTypeOnlyInputs, - const std::vector> &userInputs, bool isContextual) + const std::shared_ptr &userInput, bool isContextual) { if (isContextual && (!icon || !wantAgent)) { ANS_LOGE("icon or wantAgent can not be null when isContextual is true"); @@ -42,18 +42,10 @@ std::shared_ptr NotificationActionButton::Create(const } } + std::shared_ptr textInput = userInput; std::vector> onlyInputs = mimeTypeOnlyInputs; - std::vector> textInputs {}; - for (auto &userInput : userInputs) { - if (!userInput) { - continue; - } - - if (userInput->IsMimeTypeOnly()) { - onlyInputs.push_back(userInput); - } else { - textInputs.push_back(userInput); - } + if (userInput && (userInput->IsMimeTypeOnly())) { + onlyInputs.push_back(userInput); } auto pActionButton = new (std::nothrow) NotificationActionButton(icon, @@ -63,7 +55,7 @@ std::shared_ptr NotificationActionButton::Create(const semanticActionButton, autoCreatedReplies, onlyInputs, - textInputs, + textInput, isContextual); if (pActionButton == nullptr) { ANS_LOGE("create NotificationActionButton object failed"); @@ -88,7 +80,7 @@ std::shared_ptr NotificationActionButton::Create( actionButton->GetSemanticActionButton(), actionButton->IsAutoCreatedReplies(), actionButton->GetMimeTypeOnlyUserInputs(), - actionButton->GetUserInputs(), + actionButton->GetUserInput(), actionButton->IsContextDependent()); } @@ -96,7 +88,7 @@ NotificationActionButton::NotificationActionButton(const std::shared_ptr &wantAgent, const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, const std::vector> &mimeTypeOnlyInputs, - const std::vector> &userInputs, bool isContextual) + const std::shared_ptr &userInput, bool isContextual) : icon_(icon), title_(title), wantAgent_(wantAgent), @@ -104,7 +96,7 @@ NotificationActionButton::NotificationActionButton(const std::shared_ptr> NotificationActionButton::Ge void NotificationActionButton::AddNotificationUserInput(const std::shared_ptr &userInput) { - if (!userInput) { - ANS_LOGE("The userInput is invalid."); - return; - } - - userInputs_.emplace_back(userInput); + userInput_ = userInput; } -std::vector> NotificationActionButton::GetUserInputs() const +const std::shared_ptr NotificationActionButton::GetUserInput() const { - return userInputs_; + return userInput_; } void NotificationActionButton::SetAutoCreatedReplies(bool autoCreatedReplies) @@ -212,14 +199,12 @@ std::string NotificationActionButton::Dump() mimeTypeOnlyUserInputs += ", "; } - std::string userInputs = ""; - for (auto &item : userInputs_) { - if (!item) { - userInputs += "nullptr, "; - continue; - } - userInputs += item->Dump(); - userInputs += ", "; + std::string userInput = ""; + if (userInput_ == nullptr) { + userInput += "nullptr, "; + } else { + userInput += userInput_->Dump(); + userInput += ", "; } return "NotificationActionButton{ " @@ -228,7 +213,7 @@ std::string NotificationActionButton::Dump() ", autoCreatedReplies = " + (autoCreatedReplies_ ? "true" : "false") + ", isContextual = " + (isContextual_ ? "true" : "false") + ", mimeTypeOnlyUserInputs = [" + mimeTypeOnlyUserInputs + "]" + - ", userInputs = [" + userInputs + "]" + + ", userInputs = [" + userInput + "]" + " }"; } @@ -350,24 +335,17 @@ bool NotificationActionButton::Marshalling(Parcel &parcel) const } } - if (!parcel.WriteInt32(static_cast(userInputs_.size()))) { - ANS_LOGE("Failed to write the size of userInputs"); + valid = userInput_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether userInput is null"); return false; } - for (auto it = userInputs_.begin(); it != userInputs_.end(); ++it) { - valid = (*it) ? true : false; - if (!parcel.WriteBool(valid)) { - ANS_LOGE("Failed to write the flag which indicate whether userInput is null"); + if (valid) { + if (!parcel.WriteParcelable(userInput_.get())) { + ANS_LOGE("Failed to write userInput"); return false; } - - if (valid) { - if (!parcel.WriteParcelable(it->get())) { - ANS_LOGE("Failed to write userInput"); - return false; - } - } } return true; @@ -427,19 +405,13 @@ bool NotificationActionButton::ReadFromParcel(Parcel &parcel) } } - auto vsize = parcel.ReadInt32(); - for (auto it = 0; it < vsize; ++it) { - valid = parcel.ReadBool(); - NotificationUserInput *member {nullptr}; - if (valid) { - member = parcel.ReadParcelable(); - if (member == nullptr) { - ANS_LOGE("Failed to read userInput"); - return false; - } + valid = parcel.ReadBool(); + if (valid) { + userInput_ = std::shared_ptr(parcel.ReadParcelable()); + if (!userInput_) { + ANS_LOGE("Failed to read userInput"); + return false; } - - userInputs_.emplace_back(member); } return true; diff --git a/frameworks/ans/native/src/notification_content.cpp b/frameworks/ans/native/src/notification_content.cpp index dbd39018996bea0abbe673bbffd8aaecac360848..44a866ba1a5c802e527411d57c1a509d7fb0f0a0 100644 --- a/frameworks/ans/native/src/notification_content.cpp +++ b/frameworks/ans/native/src/notification_content.cpp @@ -122,7 +122,7 @@ bool NotificationContent::ToJson(nlohmann::json &jsonObject) const } nlohmann::json contentObj; - if (!NotificationJsonConverter::ConvertToJosn(content_.get(), contentObj)) { + if (!NotificationJsonConverter::ConvertToJson(content_.get(), contentObj)) { ANS_LOGE("Cannot convert content to JSON"); return false; } @@ -258,19 +258,19 @@ bool NotificationContent::ConvertJsonToContent(NotificationContent *target, cons NotificationBasicContent *pBasicContent {nullptr}; switch (target->contentType_) { case NotificationContent::Type::BASIC_TEXT: - pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + pBasicContent = NotificationJsonConverter::ConvertFromJson(contentObj); break; case NotificationContent::Type::CONVERSATION: - pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + pBasicContent = NotificationJsonConverter::ConvertFromJson(contentObj); break; case NotificationContent::Type::LONG_TEXT: - pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + pBasicContent = NotificationJsonConverter::ConvertFromJson(contentObj); break; case NotificationContent::Type::MULTILINE: - pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + pBasicContent = NotificationJsonConverter::ConvertFromJson(contentObj); break; case NotificationContent::Type::PICTURE: - pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + pBasicContent = NotificationJsonConverter::ConvertFromJson(contentObj); break; default: ANS_LOGE("Invalid contentType"); diff --git a/frameworks/ans/native/src/notification_conversational_content.cpp b/frameworks/ans/native/src/notification_conversational_content.cpp index 08f3599b71af42ee59cf801cb61c56a16dc69216..f63c5300d34eff731e67f8e70cc973101e8e589c 100644 --- a/frameworks/ans/native/src/notification_conversational_content.cpp +++ b/frameworks/ans/native/src/notification_conversational_content.cpp @@ -101,7 +101,7 @@ bool NotificationConversationalContent::ToJson(nlohmann::json &jsonObject) const } nlohmann::json userObj; - if (!NotificationJsonConverter::ConvertToJosn(&messageUser_, userObj)) { + if (!NotificationJsonConverter::ConvertToJson(&messageUser_, userObj)) { ANS_LOGE("Cannot convert messageUser to JSON"); return false; } @@ -117,7 +117,7 @@ bool NotificationConversationalContent::ToJson(nlohmann::json &jsonObject) const } nlohmann::json msgObj; - if (!NotificationJsonConverter::ConvertToJosn(msg.get(), msgObj)) { + if (!NotificationJsonConverter::ConvertToJson(msg.get(), msgObj)) { ANS_LOGE("Cannot convert conversationalMessage to JSON"); return false; } @@ -146,7 +146,7 @@ NotificationConversationalContent *NotificationConversationalContent::FromJson(c const auto &jsonEnd = jsonObject.cend(); if (jsonObject.find("messageUser") != jsonEnd) { auto userObj = jsonObject.at("messageUser"); - auto pUser = NotificationJsonConverter::ConvertFromJosn(userObj); + auto pUser = NotificationJsonConverter::ConvertFromJson(userObj); if (pUser != nullptr) { pContent->messageUser_ = *pUser; @@ -158,7 +158,7 @@ NotificationConversationalContent *NotificationConversationalContent::FromJson(c if (jsonObject.find("messages") != jsonEnd) { nlohmann::json msgsArr = jsonObject.at("messages"); for (auto &msgObj : msgsArr) { - auto pMsg = NotificationJsonConverter::ConvertFromJosn(msgObj); + auto pMsg = NotificationJsonConverter::ConvertFromJson(msgObj); if (pMsg == nullptr) { ANS_LOGE("Failed to parse message "); @@ -196,7 +196,7 @@ bool NotificationConversationalContent::Marshalling(Parcel &parcel) const return false; } - if (!parcel.WriteInt32(static_cast(messages_.size()))) { + if (!parcel.WriteUint64(messages_.size())) { ANS_LOGE("Failed to write the size of messages"); return false; } @@ -254,8 +254,8 @@ bool NotificationConversationalContent::ReadFromParcel(Parcel &parcel) } messageUser_ = *pUser; - auto vsize = parcel.ReadInt32(); - for (auto it = 0; it < vsize; ++it) { + auto vsize = parcel.ReadUint64(); + for (uint64_t it = 0; it < vsize; ++it) { auto valid = parcel.ReadBool(); if (!valid) { ANS_LOGE("Invalid message, read from parcel failed"); diff --git a/frameworks/ans/native/src/notification_conversational_message.cpp b/frameworks/ans/native/src/notification_conversational_message.cpp index 520a5fbfca36af631ac6a78b337c3edc8a2b25e2..51d33ed265991280e1fbb6fbebfb278e28c2b6f1 100644 --- a/frameworks/ans/native/src/notification_conversational_message.cpp +++ b/frameworks/ans/native/src/notification_conversational_message.cpp @@ -71,7 +71,7 @@ bool NotificationConversationalMessage::ToJson(nlohmann::json &jsonObject) const jsonObject["text"] = text_; nlohmann::json userObj; - if (!NotificationJsonConverter::ConvertToJosn(&sender_, userObj)) { + if (!NotificationJsonConverter::ConvertToJson(&sender_, userObj)) { ANS_LOGE("Cannot convert sender to JSON"); return false; } @@ -107,7 +107,7 @@ NotificationConversationalMessage *NotificationConversationalMessage::FromJson(c if (jsonObject.find("sender") != jsonEnd) { auto userObj = jsonObject.at("sender"); - auto pUser = NotificationJsonConverter::ConvertFromJosn(userObj); + auto pUser = NotificationJsonConverter::ConvertFromJson(userObj); if (pUser != nullptr) { pMessage->sender_ = *pUser; diff --git a/frameworks/ans/native/src/notification_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp index 532ab1ed3871d59638d71ba432b6b2bbda0d9652..294d93a01fd9b31c82b1b5f55031f057481d592b 100644 --- a/frameworks/ans/native/src/notification_helper.cpp +++ b/frameworks/ans/native/src/notification_helper.cpp @@ -80,7 +80,7 @@ ErrCode NotificationHelper::GetNotificationSlotGroups(std::vector::GetInstance()->GetNotificationSlotGroups(groups); } -ErrCode NotificationHelper::GetNotificationSlotNumAsBundle(const NotificationBundleOption &bundleOption, int &num) +ErrCode NotificationHelper::GetNotificationSlotNumAsBundle(const NotificationBundleOption &bundleOption, uint64_t &num) { return DelayedSingleton::GetInstance()->GetNotificationSlotNumAsBundle(bundleOption, num); } @@ -115,7 +115,14 @@ ErrCode NotificationHelper::CancelAllNotifications() return DelayedSingleton::GetInstance()->CancelAllNotifications(); } -ErrCode NotificationHelper::GetActiveNotificationNums(int32_t &num) +ErrCode NotificationHelper::CancelAsBundle( + int32_t notificationId, const std::string &representativeBundle, int32_t userId) +{ + return DelayedSingleton::GetInstance()->CancelAsBundle( + notificationId, representativeBundle, userId); +} + +ErrCode NotificationHelper::GetActiveNotificationNums(uint64_t &num) { return DelayedSingleton::GetInstance()->GetActiveNotificationNums(num); } @@ -403,5 +410,17 @@ ErrCode NotificationHelper::GetDoNotDisturbDate(const int32_t &userId, Notificat { return DelayedSingleton::GetInstance()->GetDoNotDisturbDate(userId, doNotDisturbDate); } + +ErrCode NotificationHelper::SetEnabledForBundleSlot( + const NotificationBundleOption &bundleOption, const NotificationConstant::SlotType &slotType, bool enabled) +{ + return DelayedSingleton::GetInstance()->SetEnabledForBundleSlot(bundleOption, slotType, enabled); +} + +ErrCode NotificationHelper::GetEnabledForBundleSlot( + const NotificationBundleOption &bundleOption, const NotificationConstant::SlotType &slotType, bool &enabled) +{ + return DelayedSingleton::GetInstance()->GetEnabledForBundleSlot(bundleOption, slotType, enabled); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index beba5fa04ed5db1bbd15280f74d9fc8ba2fc30a7..0efbdbe6b3bc9f755fc1cf4e1d8d6fa69d8c8471 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -17,8 +17,8 @@ #include "ans_image_util.h" #include "ans_log_wrapper.h" -#include "ohos/aafwk/content/want_params_wrapper.h" #include "want_agent_helper.h" +#include "want_params_wrapper.h" namespace OHOS { namespace Notification { @@ -203,6 +203,16 @@ void NotificationRequest::SetPermitSystemGeneratedContextualActionButtons(bool p permitted_ = permitted; } +bool NotificationRequest::IsAgentNotification() const +{ + return isAgent_; +} + +void NotificationRequest::SetIsAgentNotification(bool isAgent) +{ + isAgent_ = isAgent; +} + void NotificationRequest::AddMessageUser(const std::shared_ptr &messageUser) { if (!messageUser) { @@ -585,16 +595,26 @@ pid_t NotificationRequest::GetCreatorPid() const return creatorPid_; } -void NotificationRequest::SetCreatorUid(pid_t uid) +void NotificationRequest::SetCreatorUid(int32_t uid) { creatorUid_ = uid; } -pid_t NotificationRequest::GetCreatorUid() const +int32_t NotificationRequest::GetCreatorUid() const { return creatorUid_; } +void NotificationRequest::SetOwnerUid(int32_t uid) +{ + ownerUid_ = uid; +} + +int32_t NotificationRequest::GetOwnerUid() const +{ + return ownerUid_; +} + void NotificationRequest::SetLabel(const std::string &label) { label_ = label; @@ -635,6 +655,16 @@ int32_t NotificationRequest::GetCreatorUserId() const return creatorUserId_; } +void NotificationRequest::SetOwnerUserId(int32_t userId) +{ + ownerUserId_ = userId; +} + +int32_t NotificationRequest::GetOwnerUserId() const +{ + return ownerUserId_; +} + std::string NotificationRequest::Dump() { return "NotificationRequest{ " @@ -645,7 +675,9 @@ std::string NotificationRequest::Dump() ", creatorBundleName = " + creatorBundleName_ + ", creatorPid = " + std::to_string(static_cast(creatorPid_)) + ", creatorUid = " + std::to_string(static_cast(creatorUid_)) + - ", ownerBundleName = " + ownerBundleName_ + ", groupName = " + groupName_ + + ", ownerBundleName = " + ownerBundleName_ + + ", ownerUid = " + std::to_string(static_cast(ownerUid_)) + + ", groupName = " + groupName_ + ", statusBarText = " + statusBarText_ + ", label = " + label_ + ", shortcutId = " + shortcutId_ + ", sortingKey = " + sortingKey_ + ", groupAlertType = " + std::to_string(static_cast(groupAlertType_)) + @@ -667,6 +699,7 @@ std::string NotificationRequest::Dump() ", unremovable = " + (unremovable_ ? "true" : "false") + ", floatingIcon = " + (floatingIcon_ ? "true" : "false") + ", onlyLocal = " + (onlyLocal_ ? "true" : "false") + ", permitted = " + (permitted_ ? "true" : "false") + + ", isAgent = " + (isAgent_ ? "true" : "false") + ", removalWantAgent = " + (removalWantAgent_ ? "not null" : "null") + ", maxScreenWantAgent = " + (maxScreenWantAgent_ ? "not null" : "null") + ", additionalParams = " + (additionalParams_ ? "not null" : "null") + @@ -681,6 +714,7 @@ std::string NotificationRequest::Dump() ", distributedOptions = " + distributedOptions_.Dump() + ", notificationFlags = " + (notificationFlags_ ? "not null" : "null") + ", creatorUserId = " + std::to_string(creatorUserId_) + + ", ownerUserId = " + std::to_string(ownerUserId_) + ", receiverUserId = " + std::to_string(receiverUserId_) + " }"; } @@ -848,11 +882,21 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const return false; } + if (!parcel.WriteInt32(static_cast(ownerUid_))) { + ANS_LOGE("Failed to write owner uid"); + return false; + } + if (!parcel.WriteInt32(static_cast(creatorUserId_))) { ANS_LOGE("Failed to write creator userId"); return false; } + if (!parcel.WriteInt32(static_cast(ownerUserId_))) { + ANS_LOGE("Failed to write owner userId"); + return false; + } + if (!parcel.WriteInt32(static_cast(receiverUserId_))) { ANS_LOGE("Failed to write receiver userId"); return false; @@ -997,6 +1041,11 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const return false; } + if (!parcel.WriteBool(isAgent_)) { + ANS_LOGE("Failed to write flag indicating whether an agent notification"); + return false; + } + // write objects which managed by std::shared_ptr bool valid {false}; @@ -1105,7 +1154,7 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const } // write std::vector - if (!parcel.WriteInt32(static_cast(actionButtons_.size()))) { + if (!parcel.WriteUint64(actionButtons_.size())) { ANS_LOGE("Failed to write the size of actionButtons"); return false; } @@ -1117,7 +1166,7 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const } } - if (!parcel.WriteInt32(static_cast(messageUsers_.size()))) { + if (!parcel.WriteUint64(messageUsers_.size())) { ANS_LOGE("Failed to write the size of messageUsers"); return false; } @@ -1191,8 +1240,10 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) autoDeletedTime_ = parcel.ReadInt64(); creatorPid_ = static_cast(parcel.ReadInt32()); - creatorUid_ = static_cast(parcel.ReadInt32()); + creatorUid_ = parcel.ReadInt32(); + ownerUid_ = parcel.ReadInt32(); creatorUserId_ = parcel.ReadInt32(); + ownerUserId_ = parcel.ReadInt32(); receiverUserId_ = parcel.ReadInt32(); if (!parcel.ReadString(settingsText_)) { @@ -1259,6 +1310,7 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) floatingIcon_ = parcel.ReadBool(); onlyLocal_ = parcel.ReadBool(); permitted_ = parcel.ReadBool(); + isAgent_ = parcel.ReadBool(); bool valid {false}; @@ -1337,8 +1389,8 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) } } - auto vsize = parcel.ReadInt32(); - for (auto it = 0; it < vsize; ++it) { + auto vsize = parcel.ReadUint64(); + for (uint64_t it = 0; it < vsize; ++it) { auto member = parcel.ReadParcelable(); if (member == nullptr) { ANS_LOGE("Failed to read actionButton"); @@ -1348,8 +1400,8 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) actionButtons_.emplace_back(member); } - vsize = parcel.ReadInt32(); - for (auto it = 0; it < vsize; ++it) { + vsize = parcel.ReadUint64(); + for (uint64_t it = 0; it < vsize; ++it) { auto member = parcel.ReadParcelable(); if (member == nullptr) { ANS_LOGE("Failed to read messageUser"); @@ -1444,8 +1496,11 @@ void NotificationRequest::CopyBase(const NotificationRequest &other) this->creatorPid_ = other.creatorPid_; this->creatorUid_ = other.creatorUid_; + this->ownerUid_ = other.ownerUid_; this->creatorUserId_ = other.creatorUserId_; + this->ownerUserId_ = other.ownerUserId_; this->receiverUserId_ = other.receiverUserId_; + this->isAgent_ = other.isAgent_; this->slotType_ = other.slotType_; this->settingsText_ = other.settingsText_; @@ -1505,7 +1560,7 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const nlohmann::json contentObj; if (notificationContent_) { - if (!NotificationJsonConverter::ConvertToJosn(notificationContent_.get(), contentObj)) { + if (!NotificationJsonConverter::ConvertToJson(notificationContent_.get(), contentObj)) { ANS_LOGE("Cannot convert notificationContent to JSON"); return false; } @@ -1519,7 +1574,7 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const } nlohmann::json btnObj; - if (!NotificationJsonConverter::ConvertToJosn(btn.get(), btnObj)) { + if (!NotificationJsonConverter::ConvertToJson(btn.get(), btnObj)) { ANS_LOGE("Cannot convert actionButton to JSON"); return false; } @@ -1539,7 +1594,7 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const jsonObject["largeIcon"] = AnsImageUtil::PackImage(bigIcon_); nlohmann::json optObj; - if (!NotificationJsonConverter::ConvertToJosn(&distributedOptions_, optObj)) { + if (!NotificationJsonConverter::ConvertToJson(&distributedOptions_, optObj)) { ANS_LOGE("Cannot convert distributedOptions to JSON"); return false; } @@ -1547,7 +1602,7 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const if (notificationFlags_) { nlohmann::json flagsObj; - if (!NotificationJsonConverter::ConvertToJosn(notificationFlags_.get(), flagsObj)) { + if (!NotificationJsonConverter::ConvertToJson(notificationFlags_.get(), flagsObj)) { ANS_LOGE("Cannot convert notificationFlags to JSON"); return false; } @@ -1587,15 +1642,15 @@ void NotificationRequest::ConvertJsonToNum(NotificationRequest *target, const nl } if (jsonObject.find("creatorPid") != jsonEnd) { - target->creatorPid_ = jsonObject.at("creatorPid").get(); + target->creatorPid_ = jsonObject.at("creatorPid").get(); } if (jsonObject.find("creatorUserId") != jsonEnd) { - target->creatorUserId_ = jsonObject.at("creatorUserId").get(); + target->creatorUserId_ = jsonObject.at("creatorUserId").get(); } if (jsonObject.find("receiverUserId") != jsonEnd) { - target->receiverUserId_ = jsonObject.at("receiverUserId").get(); + target->receiverUserId_ = jsonObject.at("receiverUserId").get(); } } @@ -1732,7 +1787,7 @@ bool NotificationRequest::ConvertJsonToNotificationContent( if (jsonObject.find("content") != jsonEnd) { auto contentObj = jsonObject.at("content"); if (!contentObj.is_null()) { - auto pContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + auto pContent = NotificationJsonConverter::ConvertFromJson(contentObj); if (pContent == nullptr) { ANS_LOGE("Failed to parse notification content!"); return false; @@ -1758,7 +1813,7 @@ bool NotificationRequest::ConvertJsonToNotificationActionButton( if (jsonObject.find("actionButtons") != jsonEnd) { auto buttonArr = jsonObject.at("actionButtons"); for (auto &btnObj : buttonArr) { - auto pBtn = NotificationJsonConverter::ConvertFromJosn(btnObj); + auto pBtn = NotificationJsonConverter::ConvertFromJson(btnObj); if (pBtn == nullptr) { ANS_LOGE("Failed to parse actionButton!"); return false; @@ -1784,7 +1839,7 @@ bool NotificationRequest::ConvertJsonToNotificationDistributedOptions( if (jsonObject.find("distributedOptions") != jsonEnd) { auto optObj = jsonObject.at("distributedOptions"); if (!optObj.is_null()) { - auto pOpt = NotificationJsonConverter::ConvertFromJosn(optObj); + auto pOpt = NotificationJsonConverter::ConvertFromJson(optObj); if (pOpt == nullptr) { ANS_LOGE("Failed to parse distributedOptions!"); return false; @@ -1810,7 +1865,7 @@ bool NotificationRequest::ConvertJsonToNotificationFlags( if (jsonObject.find("notificationFlags") != jsonEnd) { auto flagsObj = jsonObject.at("notificationFlags"); if (!flagsObj.is_null()) { - auto pFlags = NotificationJsonConverter::ConvertFromJosn(flagsObj); + auto pFlags = NotificationJsonConverter::ConvertFromJson(flagsObj); if (pFlags == nullptr) { ANS_LOGE("Failed to parse notificationFlags!"); return false; diff --git a/frameworks/ans/native/src/notification_slot.cpp b/frameworks/ans/native/src/notification_slot.cpp index 04f4c9c5afac95d7e420395ab9bdedc368888549..e41616918dab38dd063bc087708795b546c508fd 100644 --- a/frameworks/ans/native/src/notification_slot.cpp +++ b/frameworks/ans/native/src/notification_slot.cpp @@ -19,7 +19,7 @@ namespace OHOS { namespace Notification { -const int MAX_TEXT_LENGTH = 1000; +const int32_t MAX_TEXT_LENGTH = 1000; NotificationSlot::NotificationSlot(NotificationConstant::SlotType type) : sound_("") { @@ -200,6 +200,16 @@ void NotificationSlot::EnableBadge(bool isShowBadge) isShowBadge_ = isShowBadge; } +void NotificationSlot::SetEnable(bool enabled) +{ + enabled_ = enabled; +} + +bool NotificationSlot::GetEnable() const +{ + return enabled_; +} + std::string NotificationSlot::Dump() const { return "NotificationSlot{ " @@ -217,6 +227,7 @@ std::string NotificationSlot::Dump() const ", vibration = " + MergeVectorToString(vibrationValues_) + ", isShowBadge = " + (isShowBadge_ ? "true" : "false") + ", groupId = " + groupId_ + + ", enabled = " + (enabled_ ? "true" : "false") + " }"; } @@ -303,6 +314,11 @@ bool NotificationSlot::Marshalling(Parcel &parcel) const return false; } + if (!parcel.WriteBool(enabled_)) { + ANS_LOGE("Failed to write isShowBadge"); + return false; + } + return true; } @@ -321,7 +337,7 @@ bool NotificationSlot::ReadFromParcel(Parcel &parcel) lockScreenVisibleness_ = static_cast(parcel.ReadInt32()); groupId_ = parcel.ReadString(); - int empty = VALUE_NULL; + int32_t empty = VALUE_NULL; if (!parcel.ReadInt32(empty)) { ANS_LOGE("Failed to read int"); return false; @@ -332,6 +348,7 @@ bool NotificationSlot::ReadFromParcel(Parcel &parcel) } parcel.ReadInt64Vector(&vibrationValues_); + enabled_ = parcel.ReadBool(); return true; } diff --git a/frameworks/ans/native/src/notification_slot_group.cpp b/frameworks/ans/native/src/notification_slot_group.cpp index c870357e0e3b10edaddb281a343787f1a265e243..cb63278eb9264c8c00cafcb4dd51d63219cfe44b 100644 --- a/frameworks/ans/native/src/notification_slot_group.cpp +++ b/frameworks/ans/native/src/notification_slot_group.cpp @@ -19,7 +19,7 @@ namespace OHOS { namespace Notification { -const int MAX_TEXT_LENGTH = 1000; +const int32_t MAX_TEXT_LENGTH = 1000; const std::string LINE_SEPARATOR = "\n"; NotificationSlotGroup::NotificationSlotGroup() @@ -104,13 +104,13 @@ bool NotificationSlotGroup::Marshalling(Parcel &parcel) const return false; } - if (slots_.size() == 0) { - if (!parcel.WriteInt32(0)) { + if (slots_.empty()) { + if (!parcel.WriteUint64(0)) { ANS_LOGE("Failed to write the size of slots"); return false; } } else { - if (!parcel.WriteInt32(slots_.size())) { + if (!parcel.WriteUint64(slots_.size())) { ANS_LOGE("Failed to write the size of slots"); return false; } @@ -135,9 +135,9 @@ bool NotificationSlotGroup::ReadFromParcel(Parcel &parcel) id_ = parcel.ReadString(); name_ = parcel.ReadString(); description_ = parcel.ReadString(); - int32_t size = parcel.ReadInt32(); + uint64_t size = parcel.ReadUint64(); if (size) { - for (int32_t i = 0; i < size; ++i) { + for (uint64_t i = 0; i < size; ++i) { auto slot = parcel.ReadParcelable(); if (slot == nullptr) { ANS_LOGE("Failed to read slot"); diff --git a/frameworks/ans/native/src/notification_sorting.cpp b/frameworks/ans/native/src/notification_sorting.cpp index 575141dbfcc0bb35b50f9c2811763e30f8cbcfef..78699b112ca9c87693d2e2f91cccbc54013cd354 100644 --- a/frameworks/ans/native/src/notification_sorting.cpp +++ b/frameworks/ans/native/src/notification_sorting.cpp @@ -72,7 +72,7 @@ bool NotificationSorting::Marshalling(Parcel &parcel) const return false; } - if (!parcel.WriteInt32(ranking_)) { + if (!parcel.WriteUint64(ranking_)) { ANS_LOGE("Can't write ranking"); return false; } @@ -116,7 +116,7 @@ bool NotificationSorting::ReadFromParcel(Parcel &parcel) key_ = parcel.ReadString(); // read ranking_ - ranking_ = parcel.ReadInt32(); + ranking_ = parcel.ReadUint64(); // read importance_ importance_ = parcel.ReadInt32(); @@ -159,7 +159,7 @@ void NotificationSorting::SetImportance(const int32_t &importance) importance_ = importance; } -void NotificationSorting::SetRanking(const int32_t &ranking) +void NotificationSorting::SetRanking(const uint64_t &ranking) { ranking_ = ranking; } diff --git a/frameworks/ans/native/src/notification_sorting_map.cpp b/frameworks/ans/native/src/notification_sorting_map.cpp index 2bd73d2f504f4b270616547b4da9d50490ba497a..1263637ca33c0023a2a478ce02ae3ba2558afbc7 100644 --- a/frameworks/ans/native/src/notification_sorting_map.cpp +++ b/frameworks/ans/native/src/notification_sorting_map.cpp @@ -64,16 +64,23 @@ void NotificationSortingMap::SetNotificationSorting(const std::vector sorting) { + + size_t count = 0; + for (auto &sorting : sortings_) { if (!parcel.WriteParcelable(&sorting.second)) { ANS_LOGE("Can't write sorting"); ret = false; } - }); + count++; + + if (count == MAX_ACTIVE_NUM) { + break; + } + } return ret; } @@ -82,10 +89,11 @@ NotificationSortingMap *NotificationSortingMap::Unmarshalling(Parcel &parcel) { std::vector sortings; // read sorting num - int32_t size = 0; - parcel.ReadInt32(size); + uint64_t size = 0; + parcel.ReadUint64(size); + size = (size <= MAX_ACTIVE_NUM) ? size : MAX_ACTIVE_NUM; - for (int i = 0; i < size; i++) { + for (uint64_t i = 0; i < size; i++) { // read sorting NotificationSorting *sorting = parcel.ReadParcelable(); if (sorting != nullptr) { diff --git a/frameworks/ans/native/src/notification_subscribe_info.cpp b/frameworks/ans/native/src/notification_subscribe_info.cpp index 50cd3a934de9c142bb65bd57214775326a1263d9..ae092ab08736b1b1f9f6e483281159a2709e2100 100644 --- a/frameworks/ans/native/src/notification_subscribe_info.cpp +++ b/frameworks/ans/native/src/notification_subscribe_info.cpp @@ -45,7 +45,7 @@ std::vector NotificationSubscribeInfo::GetAppNames() const return appNames_; } -void NotificationSubscribeInfo::AddAppUserId(const int userId) +void NotificationSubscribeInfo::AddAppUserId(const int32_t userId) { userId_ = userId; } diff --git a/frameworks/ans/native/src/notification_subscriber.cpp b/frameworks/ans/native/src/notification_subscriber.cpp index e3a9a3c334858baa5391f370ed84d6b87a2a8676..e77d7addba5c6541f5909051cb0e1a333b3c4d19 100644 --- a/frameworks/ans/native/src/notification_subscriber.cpp +++ b/frameworks/ans/native/src/notification_subscriber.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -74,7 +74,7 @@ void NotificationSubscriber::SubscriberImpl::OnCanceled(const sptr } void NotificationSubscriber::SubscriberImpl::OnCanceled( - const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) + const sptr ¬ification, const sptr ¬ificationMap, int32_t deleteReason) { subscriber_.OnCanceled(std::make_shared(*notification), std::make_shared(*notificationMap), @@ -99,9 +99,9 @@ void NotificationSubscriber::SubscriberImpl::OnEnabledNotificationChanged( bool NotificationSubscriber::SubscriberImpl::GetAnsManagerProxy() { - if (nullptr == proxy_) { + if (proxy_ == nullptr) { std::lock_guard lock(mutex_); - if (nullptr == proxy_) { + if (proxy_ == nullptr) { sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (!systemAbilityManager) { diff --git a/frameworks/ans/native/src/notification_user_input.cpp b/frameworks/ans/native/src/notification_user_input.cpp index 337eeb50cdd3e8f5d4c2cf6057604474984a85ca..84d928dd73fad84f20cf994413462f92ed12337b 100644 --- a/frameworks/ans/native/src/notification_user_input.cpp +++ b/frameworks/ans/native/src/notification_user_input.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -16,7 +16,7 @@ #include "notification_user_input.h" #include "ans_log_wrapper.h" -#include "ohos/aafwk/content/want_params_wrapper.h" +#include "want_params_wrapper.h" namespace OHOS { namespace Notification { @@ -248,7 +248,7 @@ bool NotificationUserInput::ToJson(nlohmann::json &jsonObject) const NotificationUserInput *NotificationUserInput::FromJson(const nlohmann::json &jsonObject) { - if (jsonObject.is_null() or !jsonObject.is_object()) { + if (jsonObject.is_null() || !jsonObject.is_object()) { ANS_LOGE("Invalid JSON object"); return nullptr; } @@ -336,7 +336,7 @@ bool NotificationUserInput::Marshalling(Parcel &parcel) const return false; } - if (!parcel.WriteInt32(static_cast(permitMimeTypes_.size()))) { + if (!parcel.WriteUint64(static_cast(permitMimeTypes_.size()))) { ANS_LOGE("Failed to write the size of permitMimeTypes"); return false; } @@ -392,8 +392,8 @@ bool NotificationUserInput::ReadFromParcel(Parcel &parcel) return false; } - auto ssize = parcel.ReadInt32(); - for (auto it = 0; it < ssize; ++it) { + auto ssize = parcel.ReadUint64(); + for (uint64_t it = 0; it < ssize; ++it) { std::string member {}; if (!parcel.ReadString(member)) { ANS_LOGE("Failed to read permitMimeTypes"); diff --git a/frameworks/ans/native/src/reminder_helper.cpp b/frameworks/ans/native/src/reminder_helper.cpp index 5e518b7714e744a67d37dcf9a3c7414c6dff13d8..524d479dcf6be3889181f0fa0cc5ca4f6842aa4f 100644 --- a/frameworks/ans/native/src/reminder_helper.cpp +++ b/frameworks/ans/native/src/reminder_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -13,13 +13,13 @@ * limitations under the License. */ +#include "reminder_helper.h" + #include "ans_log_wrapper.h" #include "ans_notification.h" #include "notification_helper.h" #include "singleton.h" -#include "reminder_helper.h" - namespace OHOS { namespace Notification { ErrCode ReminderHelper::PublishReminder(ReminderRequest &reminder) diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp index 8c71b7f82560abea9e70fe49f1820d167f11aa48..db70e2f78d42dcfa746a1c5bad79d1e727f6ea7a 100644 --- a/frameworks/ans/native/src/reminder_request.cpp +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -13,18 +13,24 @@ * limitations under the License. */ +#include "reminder_request.h" + #include "ans_log_wrapper.h" #include "bundle_mgr_interface.h" #include "if_system_ability_manager.h" +#include "ipc_skeleton.h" #include "iservice_registry.h" #include "os_account_manager.h" +#include "reminder_store.h" #include "system_ability_definition.h" #include "want_agent_helper.h" -#include "reminder_request.h" - namespace OHOS { namespace Notification { +namespace { +const int32_t BASE_YEAR = 1900; +} + int32_t ReminderRequest::GLOBAL_ID = 0; const uint64_t ReminderRequest::INVALID_LONG_LONG_VALUE = 0; const uint16_t ReminderRequest::INVALID_U16_VALUE = 0; @@ -45,13 +51,45 @@ const std::string ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT = "ohos.event.no const std::string ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION = "ohos.event.notification.reminder.REMOVE_NOTIFICATION"; const std::string ReminderRequest::PARAM_REMINDER_ID = "REMINDER_ID"; -const int ReminderRequest::BASE_YEAR = 1900; +const std::string ReminderRequest::SEP_BUTTON_SINGLE = ""; +const std::string ReminderRequest::SEP_BUTTON_MULTI = ""; +const std::string ReminderRequest::SEP_WANT_AGENT = ""; + +// For database recovery. +const std::string ReminderRequest::REMINDER_ID = "reminder_id"; +const std::string ReminderRequest::PKG_NAME = "package_name"; +const std::string ReminderRequest::USER_ID = "user_id"; +const std::string ReminderRequest::UID = "uid"; +const std::string ReminderRequest::APP_LABEL = "app_label"; +const std::string ReminderRequest::REMINDER_TYPE = "reminder_type"; +const std::string ReminderRequest::REMINDER_TIME = "reminder_time"; +const std::string ReminderRequest::TRIGGER_TIME = "trigger_time"; +const std::string ReminderRequest::RTC_TRIGGER_TIME = "rtc_trigger_time"; +const std::string ReminderRequest::TIME_INTERVAL = "time_interval"; +const std::string ReminderRequest::SNOOZE_TIMES = "snooze_times"; +const std::string ReminderRequest::DYNAMIC_SNOOZE_TIMES = "dynamic_snooze_times"; +const std::string ReminderRequest::RING_DURATION = "ring_duration"; +const std::string ReminderRequest::IS_EXPIRED = "is_expired"; +const std::string ReminderRequest::IS_ACTIVE = "is_active"; +const std::string ReminderRequest::STATE = "state"; +const std::string ReminderRequest::ZONE_ID = "zone_id"; +const std::string ReminderRequest::HAS_SCHEDULED_TIMEOUT = "has_ScheduledTimeout"; +const std::string ReminderRequest::ACTION_BUTTON_INFO = "button_info"; +const std::string ReminderRequest::SLOT_ID = "slot_id"; +const std::string ReminderRequest::NOTIFICATION_ID = "notification_id"; +const std::string ReminderRequest::TITLE = "title"; +const std::string ReminderRequest::CONTENT = "content"; +const std::string ReminderRequest::SNOOZE_CONTENT = "snooze_content"; +const std::string ReminderRequest::EXPIRED_CONTENT = "expired_content"; +const std::string ReminderRequest::AGENT = "agent"; +const std::string ReminderRequest::MAX_SCREEN_AGENT = "maxScreen_agent"; + +std::string ReminderRequest::sqlOfAddColumns = ""; +std::vector ReminderRequest::columns; ReminderRequest::ReminderRequest() { - wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared() : wantAgentInfo_; - maxScreenWantAgentInfo_ = - maxScreenWantAgentInfo_ == nullptr ? std::make_shared() : maxScreenWantAgentInfo_; + InitServerObj(); } ReminderRequest::ReminderRequest(const ReminderRequest &other) @@ -79,12 +117,16 @@ ReminderRequest::ReminderRequest(const ReminderRequest &other) this->actionButtonMap_ = other.actionButtonMap_; } +ReminderRequest::ReminderRequest(int32_t reminderId) +{ + reminderId_ = reminderId; + InitServerObj(); +} + ReminderRequest::ReminderRequest(ReminderType reminderType) { reminderType_ = reminderType; - wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared() : wantAgentInfo_; - maxScreenWantAgentInfo_ = - maxScreenWantAgentInfo_ == nullptr ? std::make_shared() : maxScreenWantAgentInfo_; + InitServerObj(); } bool ReminderRequest::CanRemove() const @@ -124,7 +166,7 @@ std::string ReminderRequest::Dump() const ReminderRequest& ReminderRequest::SetActionButton(const std::string &title, const ActionButtonType &type) { - if (type != ActionButtonType::CLOSE && type != ActionButtonType::SNOOZE) { + if ((type != ActionButtonType::CLOSE) && (type != ActionButtonType::SNOOZE)) { ANSR_LOGI("Button type only support: %{public}d or %{public}d", static_cast(ActionButtonType::CLOSE), static_cast(ActionButtonType::SNOOZE)); return *this; @@ -164,11 +206,16 @@ void ReminderRequest::InitReminderId() ANSR_LOGI("reminderId_=%{public}d", reminderId_); } -void ReminderRequest::InitUserId(const int &userId) +void ReminderRequest::InitUserId(const int32_t &userId) { userId_ = userId; } +void ReminderRequest::InitUid(const int32_t &uid) +{ + uid_ = uid; +} + bool ReminderRequest::IsExpired() const { return isExpired_; @@ -243,8 +290,8 @@ bool ReminderRequest::HandleTimeZoneChange( if (isExpired_) { return false; } - ANSR_LOGD("Handle timezone change, oldZoneTriggerTime:%{public}llu, newZoneTriggerTime:%{public}llu", - (unsigned long long)oldZoneTriggerTime, (unsigned long long)newZoneTriggerTime); + ANSR_LOGD("Handle timezone change, oldZoneTriggerTime:%{public}" PRIu64 "\ + , newZoneTriggerTime:%{public}" PRIu64 "", oldZoneTriggerTime, newZoneTriggerTime); if (oldZoneTriggerTime == newZoneTriggerTime) { return false; } @@ -372,6 +419,192 @@ bool ReminderRequest::OnTimeZoneChange() triggerTimeInMilli_, GetDurationSinceEpochInMilli(newZoneTriggerTime), nextTriggerTime); } +int64_t ReminderRequest::RecoverInt64FromDb(const std::shared_ptr &resultSet, + const std::string &columnName, const DbRecoveryType &columnType) +{ + if (resultSet == nullptr) { + ANSR_LOGE("ResultSet is null"); + return 0; + } + switch (columnType) { + case (DbRecoveryType::INT): { + int32_t value; + resultSet->GetInt(ReminderStore::GetColumnIndex(columnName), value); + return static_cast(value); + } + case (DbRecoveryType::LONG): { + int64_t value; + resultSet->GetLong(ReminderStore::GetColumnIndex(columnName), value); + return value; + } + default: { + ANSR_LOGD("ColumnType not support."); + break; + } + } + ANSR_LOGE("Recover data error"); + return 0; +} + +void ReminderRequest::RecoverFromDb(const std::shared_ptr &resultSet) +{ + if (resultSet == nullptr) { + ANSR_LOGE("ResultSet is null"); + return; + } + + // reminderId + resultSet->GetInt(ReminderStore::GetColumnIndex(REMINDER_ID), reminderId_); + + // userId + resultSet->GetInt(ReminderStore::GetColumnIndex(USER_ID), userId_); + + // bundleName + resultSet->GetString(ReminderStore::GetColumnIndex(PKG_NAME), bundleName_); + + // uid + resultSet->GetInt(ReminderStore::GetColumnIndex(UID), uid_); + + // reminderType + int32_t reminderType; + resultSet->GetInt(ReminderStore::GetColumnIndex(REMINDER_TYPE), reminderType); + reminderType_ = ReminderType(reminderType); + + // reminderTime + reminderTimeInMilli_ = + static_cast(RecoverInt64FromDb(resultSet, REMINDER_TIME, DbRecoveryType::LONG)); + + // triggerTime + triggerTimeInMilli_ = + static_cast(RecoverInt64FromDb(resultSet, TRIGGER_TIME, DbRecoveryType::LONG)); + + // timeInterval + uint64_t timeIntervalInSecond = + static_cast(RecoverInt64FromDb(resultSet, TIME_INTERVAL, DbRecoveryType::LONG)); + SetTimeInterval(timeIntervalInSecond); + + // snoozeTimes + snoozeTimes_ = static_cast(RecoverInt64FromDb(resultSet, SNOOZE_TIMES, DbRecoveryType::INT)); + + // dynamicSnoozeTimes + snoozeTimesDynamic_ = + static_cast(RecoverInt64FromDb(resultSet, DYNAMIC_SNOOZE_TIMES, DbRecoveryType::INT)); + + // ringDuration + uint64_t ringDurationInSecond = + static_cast(RecoverInt64FromDb(resultSet, RING_DURATION, DbRecoveryType::LONG)); + SetRingDuration(ringDurationInSecond); + + // isExpired + std::string isExpired; + resultSet->GetString(ReminderStore::GetColumnIndex(IS_EXPIRED), isExpired); + isExpired_ = isExpired == "true" ? true : false; + + // state + state_ = static_cast(RecoverInt64FromDb(resultSet, STATE, DbRecoveryType::INT)); + + // action buttons + RecoverActionButton(resultSet); + + // slotType + int32_t slotType; + resultSet->GetInt(ReminderStore::GetColumnIndex(SLOT_ID), slotType); + slotType_ = NotificationConstant::SlotType(slotType); + + // notification id + resultSet->GetInt(ReminderStore::GetColumnIndex(NOTIFICATION_ID), notificationId_); + + // title + resultSet->GetString(ReminderStore::GetColumnIndex(TITLE), title_); + + // content + resultSet->GetString(ReminderStore::GetColumnIndex(CONTENT), content_); + + // snoozeContent + resultSet->GetString(ReminderStore::GetColumnIndex(SNOOZE_CONTENT), snoozeContent_); + + // expiredContent + resultSet->GetString(ReminderStore::GetColumnIndex(EXPIRED_CONTENT), expiredContent_); + + InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent + + // wantAgent + std::string wantAgent; + resultSet->GetString(ReminderStore::GetColumnIndex(AGENT), wantAgent); + RecoverWantAgent(wantAgent, 0); + + // maxScreenWantAgent + std::string maxScreenWantAgent; + resultSet->GetString(ReminderStore::GetColumnIndex(MAX_SCREEN_AGENT), maxScreenWantAgent); + RecoverWantAgent(wantAgent, 1); +} + +void ReminderRequest::RecoverActionButton(const std::shared_ptr &resultSet) +{ + if (resultSet == nullptr) { + ANSR_LOGE("ResultSet is null"); + return; + } + std::string actionButtonInfo; + resultSet->GetString(ReminderStore::GetColumnIndex(ACTION_BUTTON_INFO), actionButtonInfo); + std::vector multiButton = StringSplit(actionButtonInfo, SEP_BUTTON_MULTI); + for (auto button : multiButton) { + std::vector singleButton = StringSplit(button, SEP_BUTTON_SINGLE); + SetActionButton(singleButton.at(1), ActionButtonType(std::stoi(singleButton.at(0), nullptr))); + } +} + +std::vector ReminderRequest::StringSplit(std::string source, const std::string &split) const +{ + std::vector result; + if (source.empty()) { + return result; + } + size_t pos = 0; + while ((pos = source.find(split)) != std::string::npos) { + std::string token = source.substr(0, pos); + if (!token.empty()) { + result.push_back(token); + } + source.erase(0, pos + split.length()); + } + if (!source.empty()) { + result.push_back(source); + } + return result; +} + +void ReminderRequest::RecoverWantAgent(const std::string &wantAgentInfo, const uint8_t &type) +{ + std::vector info = StringSplit(wantAgentInfo, ReminderRequest::SEP_WANT_AGENT); + uint8_t minLen = 2; + if (info.size() < minLen) { + ANSR_LOGW("RecoverWantAgent fail"); + return; + } + ANSR_LOGD("pkg=%{public}s, ability=%{public}s", info.at(0).c_str(), info.at(1).c_str()); + switch (type) { + case 0: { + auto wai = std::make_shared(); + wai->pkgName = info.at(0); + wai->abilityName = info.at(1); + SetWantAgentInfo(wai); + break; + } + case 1: { + auto maxScreenWantAgentInfo = std::make_shared(); + maxScreenWantAgentInfo->pkgName = info.at(0); + maxScreenWantAgentInfo->abilityName = info.at(1); + SetMaxScreenWantAgentInfo(maxScreenWantAgentInfo); + break; + } + default: { + ANSR_LOGW("RecoverWantAgent type not support"); + break; + } + } +} + ReminderRequest& ReminderRequest::SetMaxScreenWantAgentInfo( const std::shared_ptr &maxScreenWantAgentInfo) { @@ -412,14 +645,14 @@ ReminderRequest& ReminderRequest::SetSnoozeTimesDynamic(const uint8_t snooziTime ReminderRequest& ReminderRequest::SetTimeInterval(const uint64_t timeIntervalInSeconds) { - if (timeIntervalInSeconds < 0 || timeIntervalInSeconds > (UINT64_MAX / MILLI_SECONDS)) { + if (timeIntervalInSeconds > (UINT64_MAX / MILLI_SECONDS)) { ANSR_LOGW("SetTimeInterval, replace to set (0s), for the given is out of legal range"); timeIntervalInMilli_ = 0; } else { uint64_t timeIntervalInMilli = timeIntervalInSeconds * MILLI_SECONDS; if (timeIntervalInMilli > 0 && timeIntervalInMilli < MIN_TIME_INTERVAL_IN_MILLI) { - ANSR_LOGW("SetTimeInterval, replace to set %{public}u, for the given is 0<%{public}llu<%{public}u", - MIN_TIME_INTERVAL_IN_MILLI / MILLI_SECONDS, (unsigned long long)timeIntervalInSeconds, + ANSR_LOGW("SetTimeInterval, replace to set %{public}u, for the given is 0<%{public}" PRIu64 "<%{public}u", + MIN_TIME_INTERVAL_IN_MILLI / MILLI_SECONDS, timeIntervalInSeconds, MIN_TIME_INTERVAL_IN_MILLI / MILLI_SECONDS); timeIntervalInMilli_ = MIN_TIME_INTERVAL_IN_MILLI; } else { @@ -511,7 +744,7 @@ void ReminderRequest::SetReminderTimeInMilli(const uint64_t reminderTimeInMilli) ReminderRequest& ReminderRequest::SetRingDuration(const uint64_t ringDurationInSeconds) { - if (ringDurationInSeconds <= 0 || ringDurationInSeconds > (UINT64_MAX / MILLI_SECONDS)) { + if ((ringDurationInSeconds == 0) || (ringDurationInSeconds > (UINT64_MAX / MILLI_SECONDS))) { ANSR_LOGW("setRingDuration, replace to set (1s), for the given is out of legal range"); ringDurationInMilli_ = MILLI_SECONDS; } else { @@ -560,6 +793,16 @@ uint64_t ReminderRequest::GetTriggerTimeInMilli() const return triggerTimeInMilli_; } +int32_t ReminderRequest::GetUserId() const +{ + return userId_; +} + +int32_t ReminderRequest::GetUid() const +{ + return uid_; +} + std::shared_ptr ReminderRequest::GetWantAgentInfo() const { return wantAgentInfo_; @@ -606,6 +849,11 @@ void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std SetMaxScreenWantAgent(maxScreenWantAgent); break; } + case UpdateNotificationType::BUNDLE_INFO: { + ANSR_LOGI("UpdateNotification hap information"); + UpdateNotificationBundleInfo(); + break; + } case UpdateNotificationType::CONTENT: { break; } @@ -705,17 +953,16 @@ bool ReminderRequest::Marshalling(Parcel &parcel) const } // write map - int32_t buttonMapSize = static_cast(actionButtonMap_.size()); - if (!parcel.WriteInt32(buttonMapSize)) { + if (!parcel.WriteUint64(static_cast(actionButtonMap_.size()))) { ANSR_LOGE("Failed to write action button size"); return false; } - for (auto it = actionButtonMap_.begin(); it != actionButtonMap_.end(); ++it) { - if (!parcel.WriteUint8(static_cast(it->first))) { + for (auto button : actionButtonMap_) { + if (!parcel.WriteUint8(static_cast(button.first))) { ANSR_LOGE("Failed to write action button type"); return false; } - if (!parcel.WriteString(static_cast(it->second.title))) { + if (!parcel.WriteString(static_cast(button.second.title))) { ANSR_LOGE("Failed to write action button title"); return false; } @@ -725,12 +972,15 @@ bool ReminderRequest::Marshalling(Parcel &parcel) const ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel) { - auto objptr = new ReminderRequest(); - if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + auto objptr = new (std::nothrow) ReminderRequest(); + if (objptr == nullptr) { + ANSR_LOGE("Failed to create reminder due to no memory."); + return objptr; + } + if (!objptr->ReadFromParcel(parcel)) { delete objptr; objptr = nullptr; } - return objptr; } @@ -782,7 +1032,7 @@ bool ReminderRequest::ReadFromParcel(Parcel &parcel) ANSR_LOGE("Failed to read tempReminderId"); return false; } - reminderId_ = tempReminderId == -1 ? reminderId_ : tempReminderId; + reminderId_ = (tempReminderId == -1) ? reminderId_ : tempReminderId; if (!parcel.ReadInt32(notificationId_)) { ANSR_LOGE("Failed to read notificationId"); @@ -833,12 +1083,12 @@ bool ReminderRequest::ReadFromParcel(Parcel &parcel) slotType_ = static_cast(slotType); // read map - int32_t buttonMapSize = 0; - if (!parcel.ReadInt32(buttonMapSize)) { + uint64_t buttonMapSize = 0; + if (!parcel.ReadUint64(buttonMapSize)) { ANSR_LOGE("Failed to read buttonMapSize"); return false; } - for (int i = 0; i < buttonMapSize; i++) { + for (uint64_t i = 0; i < buttonMapSize; i++) { uint8_t buttonType = static_cast(ActionButtonType::INVALID); if (!parcel.ReadUint8(buttonType)) { ANSR_LOGE("Failed to read buttonType"); @@ -870,6 +1120,13 @@ bool ReminderRequest::InitNotificationRequest() return true; } +void ReminderRequest::InitServerObj() +{ + wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared() : wantAgentInfo_; + maxScreenWantAgentInfo_ = + maxScreenWantAgentInfo_ == nullptr ? std::make_shared() : maxScreenWantAgentInfo_; +} + bool ReminderRequest::IsAlerting() const { return (state_ & REMINDER_STATUS_ALERTING) != 0; @@ -892,6 +1149,21 @@ std::string ReminderRequest::GetDateTimeInfo(const time_t &timeInSecond) const return GetTimeInfoInner(timeInSecond, TimeFormat::YMDHMS); } +std::string ReminderRequest::GetButtonInfo() const +{ + std::string info = ""; + bool isFirst = true; + for (auto button : actionButtonMap_) { + if (!isFirst) { + info += SEP_BUTTON_MULTI; + } + ActionButtonInfo buttonInfo = button.second; + info += std::to_string(static_cast(button.first)) + SEP_BUTTON_SINGLE + buttonInfo.title; + isFirst = false; + } + return info; +} + uint64_t ReminderRequest::GetNowInstantMilli() const { time_t now; @@ -907,15 +1179,13 @@ std::string ReminderRequest::GetShowTime(const uint64_t showTime) const { if (reminderType_ == ReminderType::TIMER) { return ""; - } else { - const time_t showTimeInSecond = static_cast(showTime / MILLI_SECONDS); - return GetTimeInfoInner(showTimeInSecond, TimeFormat::HM); } + return GetTimeInfoInner(static_cast(showTime / MILLI_SECONDS), TimeFormat::HM); } std::string ReminderRequest::GetTimeInfoInner(const time_t &timeInSecond, const TimeFormat &format) const { - uint8_t dateTimeLen = 80; + const uint8_t dateTimeLen = 80; char dateTimeBuffer[dateTimeLen]; struct tm timeInfo; (void)localtime_r(&timeInSecond, &timeInfo); @@ -975,12 +1245,12 @@ std::string ReminderRequest::GetState(const uint8_t state) const void ReminderRequest::AddActionButtons(const bool includeSnooze) { - int requestCode = 10; + int32_t requestCode = 10; std::vector flags; flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); - for (auto it = actionButtonMap_.begin(); it != actionButtonMap_.end(); ++it) { + for (auto button : actionButtonMap_) { auto want = std::make_shared(); - auto type = it->first; + auto type = button.first; if (type == ActionButtonType::CLOSE) { want->SetAction(REMINDER_EVENT_CLOSE_ALERT); ANSR_LOGD("Add action button, type is close"); @@ -997,7 +1267,7 @@ void ReminderRequest::AddActionButtons(const bool includeSnooze) want->SetParam(PARAM_REMINDER_ID, reminderId_); std::vector> wants; wants.push_back(want); - auto title = static_cast(it->second.title); + auto title = static_cast(button.second.title); AbilityRuntime::WantAgent::WantAgentInfo buttonWantAgentInfo( requestCode, AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, @@ -1005,8 +1275,12 @@ void ReminderRequest::AddActionButtons(const bool includeSnooze) wants, nullptr ); + + std::string identity = IPCSkeleton::ResetCallingIdentity(); std::shared_ptr buttonWantAgent = AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(buttonWantAgentInfo, userId_); + IPCSkeleton::SetCallingIdentity(identity); + std::shared_ptr actionButton = NotificationActionButton::Create(nullptr, title, buttonWantAgent); notificationRequest_->AddActionButton(actionButton); @@ -1015,7 +1289,7 @@ void ReminderRequest::AddActionButtons(const bool includeSnooze) void ReminderRequest::AddRemovalWantAgent() { - int requestCode = 10; + int32_t requestCode = 10; std::vector flags; flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); auto want = std::make_shared(); @@ -1030,15 +1304,19 @@ void ReminderRequest::AddRemovalWantAgent() wants, nullptr ); + + std::string identity = IPCSkeleton::ResetCallingIdentity(); std::shared_ptr wantAgent = AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, userId_); + IPCSkeleton::SetCallingIdentity(identity); + notificationRequest_->SetRemovalWantAgent(wantAgent); } std::shared_ptr ReminderRequest::CreateWantAgent( AppExecFwk::ElementName &element) const { - int requestCode = 10; + int32_t requestCode = 10; std::vector flags; flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); auto want = std::make_shared(); @@ -1052,7 +1330,10 @@ std::shared_ptr ReminderRequest::CreateWan wants, nullptr ); - return AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, userId_); + std::string identity = IPCSkeleton::ResetCallingIdentity(); + auto wantAgent = AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, userId_); + IPCSkeleton::SetCallingIdentity(identity); + return wantAgent; } void ReminderRequest::SetMaxScreenWantAgent(AppExecFwk::ElementName &element) @@ -1073,7 +1354,7 @@ void ReminderRequest::SetState(bool deSet, const uint8_t newState, std::string f if (deSet) { state_ |= newState; } else { - state_ &= ~newState; + state_ &= static_cast(~newState); } ANSR_LOGI("Switch the reminder(reminderId=%{public}d) state, from %{public}s to %{public}s, called by %{public}s", reminderId_, GetState(oldState).c_str(), GetState(state_).c_str(), function.c_str()); @@ -1110,7 +1391,7 @@ bool ReminderRequest::UpdateNextReminder(const bool &force) } else { result = UpdateNextReminder(); } - std::string info = result == true ? "success" : "no next"; + std::string info = result ? "success" : "no next"; ANSR_LOGI("updateNextReminder(id=%{public}d, %{public}s): force=%{public}d, trigger time is: %{public}s", reminderId_, info.c_str(), force, GetDateTimeInfo(static_cast(triggerTimeInMilli_ / MILLI_SECONDS)).c_str()); @@ -1121,7 +1402,7 @@ void ReminderRequest::UpdateNotificationCommon() { time_t now; (void)time(&now); // unit is seconds. - notificationRequest_->SetDeliveryTime(static_cast(now) * MILLI_SECONDS); + notificationRequest_->SetDeliveryTime(GetDurationSinceEpochInMilli(now)); notificationRequest_->SetLabel(NOTIFICATION_LABEL); notificationRequest_->SetShowDeliveryTime(true); notificationRequest_->SetTapDismissed(true); @@ -1131,8 +1412,8 @@ void ReminderRequest::UpdateNotificationCommon() notificationNormalContent->SetTitle(title_); auto notificationContent = std::make_shared(notificationNormalContent); notificationRequest_->SetContent(notificationContent); - if (reminderType_ == ReminderRequest::ReminderType::TIMER - || reminderType_ == ReminderRequest::ReminderType::ALARM) { + if ((reminderType_ == ReminderRequest::ReminderType::TIMER) || + (reminderType_ == ReminderRequest::ReminderType::ALARM)) { notificationRequest_->SetUnremovable(true); } auto flags = std::make_shared(); @@ -1141,6 +1422,25 @@ void ReminderRequest::UpdateNotificationCommon() notificationRequest_->SetFlags(flags); } +void ReminderRequest::UpdateNotificationBundleInfo() +{ + std::string ownerBundleName = notificationRequest_->GetOwnerBundleName(); + if (!(ownerBundleName.empty())) { + return; + } + ANSR_LOGD("ownerBundleName=%{public}s, bundleName_=%{public}s", + ownerBundleName.c_str(), bundleName_.c_str()); + notificationRequest_->SetOwnerBundleName(bundleName_); + notificationRequest_->SetCreatorBundleName(bundleName_); + notificationRequest_->SetCreatorUid(uid_); + ErrCode errCode = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid_, userId_); + if (errCode != ERR_OK) { + ANSR_LOGE("GetOsAccountLocalIdFromUid fail."); + return; + } + notificationRequest_->SetCreatorUserId(userId_); +} + void ReminderRequest::UpdateNotificationContent(const bool &setSnooze) { if (notificationRequest_ == nullptr) { @@ -1152,11 +1452,12 @@ void ReminderRequest::UpdateNotificationContent(const bool &setSnooze) if (timeIntervalInMilli_ != 0) { // snooze the reminder by manual extendContent = GetShowTime(triggerTimeInMilli_) + - snoozeContent_ == "" ? "" : (" (" + snoozeContent_ + ")"); + (snoozeContent_ == "" ? "" : (" (" + snoozeContent_ + ")")); + notificationRequest_->SetTapDismissed(false); } else { // the reminder is expired now, when timeInterval is 0 extendContent = GetShowTime(reminderTimeInMilli_) + - expiredContent_ == "" ? "" : (" (" + expiredContent_ + ")"); + (expiredContent_ == "" ? "" : (" (" + expiredContent_ + ")")); } } else if (IsAlerting()) { // the reminder is alerting, or ring duration is 0 @@ -1164,12 +1465,12 @@ void ReminderRequest::UpdateNotificationContent(const bool &setSnooze) } else if (snoozeTimesDynamic_ != snoozeTimes_) { // the reminder is snoozing by period artithmetic, when the ring duration is over. extendContent = GetShowTime(triggerTimeInMilli_) + - snoozeContent_ == "" ? "" : (" (" + snoozeContent_ + ")"); + (snoozeContent_ == "" ? "" : (" (" + snoozeContent_ + ")")); notificationRequest_->SetTapDismissed(false); } else { // the reminder has already snoozed by period arithmetic, when the ring duration is over. extendContent = GetShowTime(reminderTimeInMilli_) + - expiredContent_ == "" ? "" : (" (" + expiredContent_ + ")"); + (expiredContent_ == "" ? "" : (" (" + expiredContent_ + ")")); } displayContent_ = content_ + " " + extendContent; ANSR_LOGD("Display content=%{public}s", displayContent_.c_str()); @@ -1189,7 +1490,7 @@ void ReminderRequest::UpdateNotificationStateForSnooze() UpdateActionButtons(true); } -int ReminderRequest::GetActualTime(const TimeTransferType &type, int cTime) +int32_t ReminderRequest::GetActualTime(const TimeTransferType &type, int32_t cTime) { switch (type) { case (TimeTransferType::YEAR): // year @@ -1197,7 +1498,7 @@ int ReminderRequest::GetActualTime(const TimeTransferType &type, int cTime) case (TimeTransferType::MONTH): // month return 1 + cTime; case (TimeTransferType::WEEK): { // week - int sunDay = 7; + int32_t sunDay = 7; if (cTime == 0) { return sunDay; } else { @@ -1209,7 +1510,7 @@ int ReminderRequest::GetActualTime(const TimeTransferType &type, int cTime) } } -int ReminderRequest::GetCTime(const TimeTransferType &type, int actualTime) +int32_t ReminderRequest::GetCTime(const TimeTransferType &type, int32_t actualTime) { switch (type) { case (TimeTransferType::YEAR): // year @@ -1217,7 +1518,7 @@ int ReminderRequest::GetCTime(const TimeTransferType &type, int actualTime) case (TimeTransferType::MONTH): // month return actualTime - 1; case (TimeTransferType::WEEK): { // week - int sunDay = 7; + int32_t sunDay = 7; if (actualTime == sunDay) { return 0; } else { @@ -1229,23 +1530,117 @@ int ReminderRequest::GetCTime(const TimeTransferType &type, int actualTime) } } -int32_t ReminderRequest::GetUid(const int &userId, const std::string &bundleName) +int32_t ReminderRequest::GetUid(const int32_t &userId, const std::string &bundleName) { AppExecFwk::ApplicationInfo info; sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + ANSR_LOGE("Failed to get uid due to get systemAbilityManager is null."); + return -1; + } sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); sptr bundleMgr = iface_cast(remoteObject); - bundleMgr->GetApplicationInfo(bundleName, AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, - static_cast(userId), info); + bundleMgr->GetApplicationInfo(bundleName, AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, info); + ANSR_LOGD("uid=%{public}d", info.uid); return static_cast(info.uid); } -int ReminderRequest::GetUserId(const int &uid) +int32_t ReminderRequest::GetUserId(const int32_t &uid) { - int userId = -1; + int32_t userId = -1; AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); + ANSR_LOGD("userId=%{public}d", userId); return userId; } + +void ReminderRequest::AppendValuesBucket(const sptr &reminder, + const sptr &bundleOption, NativeRdb::ValuesBucket &values) +{ + values.PutInt(REMINDER_ID, reminder->GetReminderId()); + values.PutString(PKG_NAME, bundleOption->GetBundleName()); + values.PutInt(USER_ID, reminder->GetUserId()); + values.PutInt(UID, reminder->GetUid()); + values.PutString(APP_LABEL, ""); // no use, compatible with old version. + values.PutInt(REMINDER_TYPE, static_cast(reminder->GetReminderType())); + values.PutLong(REMINDER_TIME, reminder->GetReminderTimeInMilli()); + values.PutLong(TRIGGER_TIME, reminder->GetTriggerTimeInMilli()); + values.PutLong( + RTC_TRIGGER_TIME, reminder->GetTriggerTimeInMilli()); // no use, compatible with old version. + values.PutLong(TIME_INTERVAL, reminder->GetTimeInterval()); + values.PutInt(SNOOZE_TIMES, reminder->GetSnoozeTimes()); + values.PutInt(DYNAMIC_SNOOZE_TIMES, reminder->GetSnoozeTimesDynamic()); + values.PutLong(RING_DURATION, reminder->GetRingDuration()); + values.PutString(IS_EXPIRED, reminder->IsExpired() ? "true" : "false"); + values.PutString(IS_ACTIVE, ""); // no use, compatible with old version. + values.PutInt(STATE, reminder->GetState()); + values.PutString(ZONE_ID, ""); // no use, compatible with old version. + values.PutString(HAS_SCHEDULED_TIMEOUT, ""); // no use, compatible with old version. + values.PutString(ACTION_BUTTON_INFO, reminder->GetButtonInfo()); + values.PutInt(SLOT_ID, reminder->GetSlotType()); + values.PutInt(NOTIFICATION_ID, reminder->GetNotificationId()); + values.PutString(TITLE, reminder->GetTitle()); + values.PutString(CONTENT, reminder->GetContent()); + values.PutString(SNOOZE_CONTENT, reminder->GetSnoozeContent()); + values.PutString(EXPIRED_CONTENT, reminder->GetExpiredContent()); + auto wantAgentInfo = reminder->GetWantAgentInfo(); + if (wantAgentInfo == nullptr) { + std::string info = "null" + ReminderRequest::SEP_WANT_AGENT + "null"; + values.PutString(AGENT, info); + } else { + values.PutString(AGENT, wantAgentInfo->pkgName + + ReminderRequest::SEP_WANT_AGENT + wantAgentInfo->abilityName); + } + auto maxScreenWantAgentInfo = reminder->GetMaxScreenWantAgentInfo(); + if (maxScreenWantAgentInfo == nullptr) { + std::string info = "null" + ReminderRequest::SEP_WANT_AGENT + "null"; + values.PutString(MAX_SCREEN_AGENT, info); + } else { + values.PutString(MAX_SCREEN_AGENT, maxScreenWantAgentInfo->pkgName + + ReminderRequest::SEP_WANT_AGENT + maxScreenWantAgentInfo->abilityName); + } +} + +void ReminderRequest::InitDbColumns() +{ + AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", false); + AddColumn(PKG_NAME, "TEXT NOT NULL", false); + AddColumn(USER_ID, "INT NOT NULL", false); + AddColumn(UID, "INT NOT NULL", false); + AddColumn(APP_LABEL, "TEXT", false); + AddColumn(REMINDER_TYPE, "INT NOT NULL", false); + AddColumn(REMINDER_TIME, "BIGINT NOT NULL", false); + AddColumn(TRIGGER_TIME, "BIGINT NOT NULL", false); + AddColumn(RTC_TRIGGER_TIME, "BIGINT NOT NULL", false); + AddColumn(TIME_INTERVAL, "BIGINT NOT NULL", false); + AddColumn(SNOOZE_TIMES, "INT NOT NULL", false); + AddColumn(DYNAMIC_SNOOZE_TIMES, "INT NOT NULL", false); + AddColumn(RING_DURATION, "BIGINT NOT NULL", false); + AddColumn(IS_EXPIRED, "TEXT NOT NULL", false); + AddColumn(IS_ACTIVE, "TEXT NOT NULL", false); + AddColumn(STATE, "INT NOT NULL", false); + AddColumn(ZONE_ID, "TEXT", false); + AddColumn(HAS_SCHEDULED_TIMEOUT, "TEXT", false); + AddColumn(ACTION_BUTTON_INFO, "TEXT", false); + AddColumn(SLOT_ID, "INT", false); + AddColumn(NOTIFICATION_ID, "INT NOT NULL", false); + AddColumn(TITLE, "TEXT", false); + AddColumn(CONTENT, "TEXT", false); + AddColumn(SNOOZE_CONTENT, "TEXT", false); + AddColumn(EXPIRED_CONTENT, "TEXT", false); + AddColumn(AGENT, "TEXT", false); + AddColumn(MAX_SCREEN_AGENT, "TEXT", false); +} + +void ReminderRequest::AddColumn( + const std::string &name, const std::string &type, const bool &isEnd) +{ + columns.push_back(name); + if (!isEnd) { + sqlOfAddColumns += name + " " + type + ", "; + } else { + sqlOfAddColumns += name + " " + type; + } } } +} \ No newline at end of file diff --git a/frameworks/ans/native/src/reminder_request_alarm.cpp b/frameworks/ans/native/src/reminder_request_alarm.cpp index f5a549729d310340397863571d3a25fe0fd3fc29..3a3ee1af65fca4354147cbddc34999be8bed0af3 100644 --- a/frameworks/ans/native/src/reminder_request_alarm.cpp +++ b/frameworks/ans/native/src/reminder_request_alarm.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -13,10 +13,11 @@ * limitations under the License. */ -#include "ans_log_wrapper.h" - #include "reminder_request_alarm.h" +#include "ans_log_wrapper.h" +#include "reminder_store.h" + namespace OHOS { namespace Notification { const uint8_t ReminderRequestAlarm::DAYS_PER_WEEK = 7; @@ -28,6 +29,11 @@ const uint8_t ReminderRequestAlarm::MINUTES_PER_HOUR = 60; const int8_t ReminderRequestAlarm::INVALID_INT_VALUE = -1; const int8_t ReminderRequestAlarm::DEFAULT_SNOOZE_TIMES = 3; +// For database recovery. +const std::string ReminderRequestAlarm::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; +const std::string ReminderRequestAlarm::ALARM_HOUR = "alarm_hour"; +const std::string ReminderRequestAlarm::ALARM_MINUTE = "alarm_minute"; + ReminderRequestAlarm::ReminderRequestAlarm(uint8_t hour, uint8_t minute, const std::vector daysOfWeek) : ReminderRequest(ReminderRequest::ReminderType::ALARM) { @@ -49,11 +55,11 @@ ReminderRequestAlarm::ReminderRequestAlarm(const ReminderRequestAlarm &other) : void ReminderRequestAlarm::CheckParamValid() const { - if (hour_ >= HOURS_PER_DAY || hour_ < 0) { + if (hour_ >= HOURS_PER_DAY) { ANSR_LOGE("setted hour is not between [0, 24)"); throw std::invalid_argument("setted hour is not between [0, 24)"); } - if (minute_ < 0 || minute_ >= MINUTES_PER_HOUR) { + if (minute_ >= MINUTES_PER_HOUR) { ANSR_LOGE("setted minute is not between [0, 60)"); throw std::invalid_argument("setted minute is not between [0, 60)"); } @@ -154,10 +160,12 @@ int8_t ReminderRequestAlarm::GetNextAlarm(const time_t now, const time_t target) if (repeatDays_ == 0) { return INVALID_INT_VALUE; } - int today = GetActualTime(TimeTransferType::WEEK, gmtime(&now)->tm_wday); - int dayCount = now >= target ? 1 : 0; + struct tm nowTime; + (void)gmtime_r(&now, &nowTime); + int32_t today = GetActualTime(TimeTransferType::WEEK, nowTime.tm_wday); + int32_t dayCount = now >= target ? 1 : 0; for (; dayCount <= DAYS_PER_WEEK; dayCount++) { - int day = (today + dayCount) % DAYS_PER_WEEK; + int32_t day = (today + dayCount) % DAYS_PER_WEEK; day = (day == 0) ? SUNDAY : day; if (IsRepeatDay(day)) { break; @@ -167,17 +175,17 @@ int8_t ReminderRequestAlarm::GetNextAlarm(const time_t now, const time_t target) return dayCount; } -bool ReminderRequestAlarm::IsRepeatDay(int day) const +bool ReminderRequestAlarm::IsRepeatDay(int32_t day) const { return (repeatDays_ & (1 << (day - 1))) > 0; } -std::vector ReminderRequestAlarm::GetDaysOfWeek() const +std::vector ReminderRequestAlarm::GetDaysOfWeek() const { - std::vector repeatDays; - int days[] = {1, 2, 3, 4, 5, 6, 7}; - int len = sizeof(days) / sizeof(int); - for (int i = 0; i < len; i++) { + std::vector repeatDays; + int32_t days[] = {1, 2, 3, 4, 5, 6, 7}; + int32_t len = sizeof(days) / sizeof(int32_t); + for (int32_t i = 0; i < len; i++) { if (IsRepeatDay(days[i])) { repeatDays.push_back(days[i]); } @@ -269,7 +277,11 @@ ReminderRequestAlarm *ReminderRequestAlarm::Unmarshalling(Parcel &parcel) { ANSR_LOGD("New alarm"); auto objptr = new (std::nothrow) ReminderRequestAlarm(); - if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + if (objptr == nullptr) { + ANSR_LOGE("Failed to create reminder alarm due to no memory."); + return objptr; + } + if (!objptr->ReadFromParcel(parcel)) { delete objptr; objptr = nullptr; } @@ -296,5 +308,46 @@ bool ReminderRequestAlarm::ReadFromParcel(Parcel &parcel) ANSR_LOGD("hour_=%{public}d, minute_=%{public}d, repeatDays_=%{public}d", hour_, minute_, repeatDays_); return true; } + +void ReminderRequestAlarm::RecoverFromDb(const std::shared_ptr &resultSet) +{ + ReminderRequest::RecoverFromDb(resultSet); + + // repeatDays + repeatDays_ = + static_cast(RecoverInt64FromDb(resultSet, REPEAT_DAYS_OF_WEEK, DbRecoveryType::INT)); + + // hour + hour_ = + static_cast(RecoverInt64FromDb(resultSet, ALARM_HOUR, DbRecoveryType::INT)); + + // minute + minute_ = + static_cast(RecoverInt64FromDb(resultSet, ALARM_MINUTE, DbRecoveryType::INT)); +} + +void ReminderRequestAlarm::AppendValuesBucket(const sptr &reminder, + const sptr &bundleOption, NativeRdb::ValuesBucket &values) +{ + uint8_t repeatDays = 0; + uint8_t hour = 0; + uint8_t minute = 0; + if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + repeatDays = alarm->GetRepeatDay(); + hour = alarm->GetHour(); + minute = alarm->GetMinute(); + } + values.PutInt(REPEAT_DAYS_OF_WEEK, repeatDays); + values.PutInt(ALARM_HOUR, hour); + values.PutInt(ALARM_MINUTE, minute); +} + +void ReminderRequestAlarm::InitDbColumns() +{ + ReminderRequest::AddColumn(REPEAT_DAYS_OF_WEEK, "INT", false); + ReminderRequest::AddColumn(ALARM_HOUR, "INT", false); + ReminderRequest::AddColumn(ALARM_MINUTE, "INT", true); +} } } \ No newline at end of file diff --git a/frameworks/ans/native/src/reminder_request_calendar.cpp b/frameworks/ans/native/src/reminder_request_calendar.cpp index 0809af1294726c2a50f9e02e688d28fdf0fc4970..7cc3a58099b57d4458055dd7317073edea00e282 100644 --- a/frameworks/ans/native/src/reminder_request_calendar.cpp +++ b/frameworks/ans/native/src/reminder_request_calendar.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -13,10 +13,10 @@ * limitations under the License. */ -#include "ans_log_wrapper.h" - #include "reminder_request_calendar.h" +#include "ans_log_wrapper.h" + namespace OHOS { namespace Notification { const uint8_t ReminderRequestCalendar::MAX_MONTHS_OF_YEAR = 12; @@ -25,13 +25,25 @@ const uint8_t ReminderRequestCalendar::JANUARY = 1; const uint8_t ReminderRequestCalendar::DECEMBER = 12; const uint8_t ReminderRequestCalendar::DEFAULT_SNOOZE_TIMES = 3; +// For database recovery. +const std::string ReminderRequestCalendar::REPEAT_DAYS = "repeat_days"; +const std::string ReminderRequestCalendar::REPEAT_MONTHS = "repeat_months"; +const std::string ReminderRequestCalendar::FIRST_DESIGNATE_YEAR = "first_designate_year"; +const std::string ReminderRequestCalendar::FIRST_DESIGNATE_MONTH = "first_designate_month"; +const std::string ReminderRequestCalendar::FIRST_DESIGNATE_DAY = "first_designate_day"; +const std::string ReminderRequestCalendar::CALENDAR_YEAR = "calendar_year"; +const std::string ReminderRequestCalendar::CALENDAR_MONTH = "calendar_month"; +const std::string ReminderRequestCalendar::CALENDAR_DAY = "calendar_day"; +const std::string ReminderRequestCalendar::CALENDAR_HOUR = "calendar_hour"; +const std::string ReminderRequestCalendar::CALENDAR_MINUTE = "calendar_minute"; + ReminderRequestCalendar::ReminderRequestCalendar(const tm &dateTime, const std::vector &repeatMonths, const std::vector &repeatDays) : ReminderRequest(ReminderRequest::ReminderType::CALENDAR) { - // 1. record the infomation which designated by user at first time. - firstDesignateYear_ = GetActualTime(TimeTransferType::YEAR, dateTime.tm_year); - firstDesignateMonth_ = GetActualTime(TimeTransferType::MONTH, dateTime.tm_mon); + // 1. record the information which designated by user at first time. + firstDesignateYear_ = static_cast(GetActualTime(TimeTransferType::YEAR, dateTime.tm_year)); + firstDesignateMonth_ = static_cast(GetActualTime(TimeTransferType::MONTH, dateTime.tm_mon)); firstDesignateDay_ = dateTime.tm_mday; SetRepeatMonths(repeatMonths); SetRepeatDaysOfMonth(repeatDays); @@ -39,8 +51,8 @@ ReminderRequestCalendar::ReminderRequestCalendar(const tm &dateTime, // 2. get the latest valid trigger time. InitDateTime(dateTime); - hour_ = dateTime_.tm_hour; - minute_ = dateTime_.tm_min; + hour_ = static_cast(dateTime_.tm_hour); + minute_ = static_cast(dateTime_.tm_min); uint64_t nextTriggerTime = INVALID_LONG_LONG_VALUE; if ((nextTriggerTime = GetNextTriggerTime()) != INVALID_LONG_LONG_VALUE) { time_t target = static_cast(nextTriggerTime / MILLI_SECONDS); @@ -51,10 +63,10 @@ ReminderRequestCalendar::ReminderRequestCalendar(const tm &dateTime, "Not exist next trigger time, please check the param of ReminderRequestCalendar constructor."); } - // 2. set the time infomation (used to transfer to proxy service) which is decided to trigger firstly. - year_ = GetActualTime(TimeTransferType::YEAR, dateTime_.tm_year); - month_ = GetActualTime(TimeTransferType::MONTH, dateTime_.tm_mon); - day_ = dateTime_.tm_mday; + // 2. set the time information (used to transfer to proxy service) which is decided to trigger firstly. + year_ = static_cast(GetActualTime(TimeTransferType::YEAR, dateTime_.tm_year)); + month_ = static_cast(GetActualTime(TimeTransferType::MONTH, dateTime_.tm_mon)); + day_ = static_cast(dateTime_.tm_mday); second_ = 0; SetTriggerTimeInMilli(nextTriggerTime); } @@ -86,7 +98,7 @@ uint8_t ReminderRequestCalendar::GetDaysOfMonth(const uint16_t &year, const uint uint8_t leapParam1 = 4; uint8_t leapParam2 = 100; if (month == february) { - days = ((((0 == year % leapParam1) && (0 != year % leapParam2)) || (0 == year % solarYear)) + days = ((((year % leapParam1 == 0) && (year % leapParam2 != 0)) || (year % solarYear == 0)) ? leapMonth : nonLeapMonth); } else { days = daysArray[month - 1]; @@ -105,7 +117,7 @@ uint8_t ReminderRequestCalendar::GetNextDay( struct tm setTime; setTime.tm_year = GetCTime(TimeTransferType::YEAR, settedYear); setTime.tm_mon = GetCTime(TimeTransferType::MONTH, settedMonth); - setTime.tm_mday = i; + setTime.tm_mday = static_cast(i); setTime.tm_hour = target.tm_hour; setTime.tm_min = target.tm_min; setTime.tm_sec = target.tm_sec; @@ -191,7 +203,7 @@ uint64_t ReminderRequestCalendar::GetNextTriggerTimeAsRepeatReminder(const tm &n } if ((triggerTimeInMilli = GetTimeInstantMilli(setYear, setMonth, setDay, hour_, minute_, second_)) != INVALID_LONG_LONG_VALUE) { - ANSR_LOGD("Next calendar time:%{public}u/%{public}u/%{public}u %{public}u:%{public}u:%{public}u", + ANSR_LOGD("Next calendar time:%{public}hu/%{public}hhu/%{public}hhu %{public}hhu:%{public}hhu:%{public}hhu", setYear, setMonth, setDay, hour_, minute_, second_); } return triggerTimeInMilli; @@ -203,10 +215,10 @@ uint64_t ReminderRequestCalendar::GetTimeInstantMilli( struct tm tar; tar.tm_year = GetCTime(TimeTransferType::YEAR, year); tar.tm_mon = GetCTime(TimeTransferType::MONTH, month); - tar.tm_mday = day; - tar.tm_hour = hour; - tar.tm_min = minute; - tar.tm_sec = second; + tar.tm_mday = static_cast(day); + tar.tm_hour = static_cast(hour); + tar.tm_min = static_cast(minute); + tar.tm_sec = static_cast(second); tar.tm_isdst = -1; ANSR_LOGD("tar: %{public}d-%{public}d-%{public}d %{public}d:%{public}d:%{public}d", @@ -223,10 +235,10 @@ void ReminderRequestCalendar::InitDateTime() { dateTime_.tm_year = GetCTime(TimeTransferType::YEAR, year_); dateTime_.tm_mon = GetCTime(TimeTransferType::MONTH, month_); - dateTime_.tm_mday = day_; - dateTime_.tm_hour = hour_; - dateTime_.tm_min = minute_; - dateTime_.tm_sec = second_; + dateTime_.tm_mday = static_cast(day_); + dateTime_.tm_hour = static_cast(hour_); + dateTime_.tm_min = static_cast(minute_); + dateTime_.tm_sec = static_cast(second_); dateTime_.tm_isdst = -1; } @@ -284,7 +296,7 @@ void ReminderRequestCalendar::SetMonth(const uint8_t &month, const bool &isSet) void ReminderRequestCalendar::SetRepeatMonths(const std::vector &repeatMonths) { if (repeatMonths.size() > MAX_MONTHS_OF_YEAR) { - ANSR_LOGW("The length of repeat months array should not larger than %{public}u", MAX_MONTHS_OF_YEAR); + ANSR_LOGW("The length of repeat months array should not larger than %{public}hhu", MAX_MONTHS_OF_YEAR); throw std::invalid_argument( "The length of repeat months array should not larger than " + std::to_string(MAX_MONTHS_OF_YEAR)); } @@ -297,7 +309,7 @@ void ReminderRequestCalendar::SetRepeatMonths(const std::vector &repeat void ReminderRequestCalendar::SetRepeatDaysOfMonth(const std::vector &repeateDays) { if (repeateDays.size() > MAX_DAYS_OF_MONTH) { - ANSR_LOGW("The length of repeat days array should not larger than %{public}u", MAX_DAYS_OF_MONTH); + ANSR_LOGW("The length of repeat days array should not larger than %{public}hhu", MAX_DAYS_OF_MONTH); throw std::invalid_argument( "The length of repeat days array should not larger than " + std::to_string(MAX_DAYS_OF_MONTH)); } @@ -310,7 +322,7 @@ void ReminderRequestCalendar::SetRepeatDaysOfMonth(const std::vector &r std::vector ReminderRequestCalendar::GetRepeatMonths() const { std::vector repeatMonths; - for (int i = 0; i < MAX_MONTHS_OF_YEAR; i++) { + for (int32_t i = 0; i < MAX_MONTHS_OF_YEAR; i++) { if (IsRepeatMonth(i + 1)) { repeatMonths.push_back(i + 1); } @@ -321,7 +333,7 @@ std::vector ReminderRequestCalendar::GetRepeatMonths() const std::vector ReminderRequestCalendar::GetRepeatDays() const { std::vector repeatDays; - for (int i = 0; i < MAX_DAYS_OF_MONTH; i++) { + for (int32_t i = 0; i < MAX_DAYS_OF_MONTH; i++) { if (IsRepeatDay(i + 1)) { repeatDays.push_back(i + 1); } @@ -438,8 +450,12 @@ bool ReminderRequestCalendar::Marshalling(Parcel &parcel) const ReminderRequestCalendar *ReminderRequestCalendar::Unmarshalling(Parcel &parcel) { ANSR_LOGD("New calendar"); - auto objptr = new ReminderRequestCalendar(); - if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + auto objptr = new (std::nothrow) ReminderRequestCalendar(); + if (objptr == nullptr) { + ANS_LOGE("Failed to create reminder calendar due to no memory."); + return objptr; + } + if (!objptr->ReadFromParcel(parcel)) { delete objptr; objptr = nullptr; } @@ -498,5 +514,96 @@ bool ReminderRequestCalendar::ReadFromParcel(Parcel &parcel) } return true; } + +void ReminderRequestCalendar::RecoverFromDb(const std::shared_ptr &resultSet) +{ + ReminderRequest::RecoverFromDb(resultSet); + + // repeatDay + repeatDay_ = static_cast(RecoverInt64FromDb(resultSet, REPEAT_DAYS, DbRecoveryType::INT)); + + // repeatMonth + repeatMonth_ = + static_cast(RecoverInt64FromDb(resultSet, REPEAT_MONTHS, DbRecoveryType::INT)); + + // firstDesignateYear + firstDesignateYear_ = + static_cast(RecoverInt64FromDb(resultSet, FIRST_DESIGNATE_YEAR, DbRecoveryType::INT)); + + // firstDesignateMonth + firstDesignateMonth_ = + static_cast(RecoverInt64FromDb(resultSet, FIRST_DESIGNATE_MONTH, DbRecoveryType::INT)); + + // firstDesignateDay + firstDesignateDay_ = + static_cast(RecoverInt64FromDb(resultSet, FIRST_DESIGNATE_DAY, DbRecoveryType::INT)); + + // year + year_ = static_cast(RecoverInt64FromDb(resultSet, CALENDAR_YEAR, DbRecoveryType::INT)); + + // month + month_ = static_cast(RecoverInt64FromDb(resultSet, CALENDAR_MONTH, DbRecoveryType::INT)); + + // day + day_ = static_cast(RecoverInt64FromDb(resultSet, CALENDAR_DAY, DbRecoveryType::INT)); + + // hour + hour_ = static_cast(RecoverInt64FromDb(resultSet, CALENDAR_HOUR, DbRecoveryType::INT)); + + // minute + minute_ = static_cast(RecoverInt64FromDb(resultSet, CALENDAR_MINUTE, DbRecoveryType::INT)); +} + +void ReminderRequestCalendar::AppendValuesBucket(const sptr &reminder, + const sptr &bundleOption, NativeRdb::ValuesBucket &values) +{ + uint32_t repeatDay = 0; + uint16_t repeatMonth = 0; + uint16_t firstDesignateYear = 0; + uint8_t firstDesignateMonth = 0; + uint8_t firstDesignateDay = 0; + uint16_t year = 0; + uint8_t month = 0; + uint8_t day = 0; + uint8_t hour = 0; + uint8_t minute = 0; + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + repeatDay = calendar->GetRepeatDay(); + repeatMonth = calendar->GetRepeatMonth(); + firstDesignateYear = calendar->GetFirstDesignateYear(); + firstDesignateMonth = calendar->GetFirstDesignageMonth(); + firstDesignateDay = calendar->GetFirstDesignateDay(); + year = calendar->GetYear(); + month = calendar->GetMonth(); + day = calendar->GetDay(); + hour = calendar->GetHour(); + minute = calendar->GetMinute(); + } + values.PutInt(REPEAT_DAYS, repeatDay); + values.PutInt(REPEAT_MONTHS, repeatMonth); + values.PutInt(FIRST_DESIGNATE_YEAR, firstDesignateYear); + values.PutInt(FIRST_DESIGNATE_MONTH, firstDesignateMonth); + values.PutInt(FIRST_DESIGNATE_DAY, firstDesignateDay); + values.PutInt(CALENDAR_YEAR, year); + values.PutInt(CALENDAR_MONTH, month); + values.PutInt(CALENDAR_DAY, day); + values.PutInt(CALENDAR_HOUR, hour); + values.PutInt(CALENDAR_MINUTE, minute); +} + +void ReminderRequestCalendar::InitDbColumns() +{ + ReminderRequest::AddColumn(REPEAT_DAYS, "INT", false); + ReminderRequest::AddColumn(REPEAT_MONTHS, "INT", false); + ReminderRequest::AddColumn(FIRST_DESIGNATE_YEAR, "INT", false); + ReminderRequest::AddColumn(FIRST_DESIGNATE_MONTH, "INT", false); + ReminderRequest::AddColumn(FIRST_DESIGNATE_DAY, "INT", false); + ReminderRequest::AddColumn(CALENDAR_YEAR, "INT", false); + ReminderRequest::AddColumn(CALENDAR_MONTH, "INT", false); + ReminderRequest::AddColumn(CALENDAR_DAY, "INT", false); + ReminderRequest::AddColumn(CALENDAR_HOUR, "INT", false); + ReminderRequest::AddColumn(CALENDAR_MINUTE, "INT", false); +} } } \ No newline at end of file diff --git a/frameworks/ans/native/src/reminder_request_timer.cpp b/frameworks/ans/native/src/reminder_request_timer.cpp index d0fd4337b2432cc0974cfcb9d5103ad071705014..4b5c878143304caca833b1dd6382091f202236b7 100644 --- a/frameworks/ans/native/src/reminder_request_timer.cpp +++ b/frameworks/ans/native/src/reminder_request_timer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -13,14 +13,14 @@ * limitations under the License. */ +#include "reminder_request_timer.h" + #include #include #include "ans_log_wrapper.h" #include "time_service_client.h" -#include "reminder_request_timer.h" - namespace OHOS { namespace Notification { ReminderRequestTimer::ReminderRequestTimer(uint64_t countDownTimeInSeconds) @@ -33,7 +33,16 @@ ReminderRequestTimer::ReminderRequestTimer(uint64_t countDownTimeInSeconds) ReminderRequest::SetTriggerTimeInMilli( ReminderRequest::GetDurationSinceEpochInMilli(now) + countDownTimeInSeconds_ * ReminderRequest::MILLI_SECONDS); sptr timer = MiscServices::TimeServiceClient::GetInstance(); - firstRealTimeInMilliSeconds_ = timer->GetBootTimeMs(); + if (timer == nullptr) { + ANSR_LOGW("Failed to get boot time due to TimeServiceClient is null."); + } else { + int64_t bootTimeMs = timer->GetBootTimeMs(); + if (bootTimeMs >= 0) { + firstRealTimeInMilliSeconds_ = static_cast(bootTimeMs); + } else { + ANSR_LOGW("Get boot time error."); + } + } } ReminderRequestTimer::ReminderRequestTimer(const ReminderRequestTimer &other) : ReminderRequest(other) @@ -80,7 +89,7 @@ void ReminderRequestTimer::CheckParamsValid(const uint64_t countDownTimeInSecond } } -void ReminderRequestTimer::UpdateTimeInfo(const std::string description) +void ReminderRequestTimer::UpdateTimeInfo(const std::string &description) { if (IsExpired()) { return; @@ -90,9 +99,17 @@ void ReminderRequestTimer::UpdateTimeInfo(const std::string description) (void)time(&now); // unit is seconds. whenToChangeSysTime_ = ReminderRequest::GetDurationSinceEpochInMilli(now); sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr) { + ANSR_LOGW("Failed to updateTime info due to TimeServiceClient is null."); + return; + } int64_t bootTime = timer->GetBootTimeMs(); + if (bootTime < 0) { + ANSR_LOGW("BootTime is illegal"); + return; + } SetTriggerTimeInMilli(whenToChangeSysTime_ + (countDownTimeInSeconds_ * MILLI_SECONDS - - (bootTime - firstRealTimeInMilliSeconds_))); + (static_cast(bootTime) - firstRealTimeInMilliSeconds_))); } bool ReminderRequestTimer::Marshalling(Parcel &parcel) const @@ -113,8 +130,12 @@ bool ReminderRequestTimer::Marshalling(Parcel &parcel) const ReminderRequestTimer *ReminderRequestTimer::Unmarshalling(Parcel &parcel) { - auto objptr = new ReminderRequestTimer(); - if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + auto objptr = new (std::nothrow) ReminderRequestTimer(); + if (objptr == nullptr) { + ANSR_LOGE("Failed to create reminder timer due to no memory."); + return objptr; + } + if (!objptr->ReadFromParcel(parcel)) { delete objptr; objptr = nullptr; } diff --git a/frameworks/ans/native/src/reminder_store.cpp b/frameworks/ans/native/src/reminder_store.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1cd8e95dcb0c93b3d99815394005417b07bf22ae --- /dev/null +++ b/frameworks/ans/native/src/reminder_store.cpp @@ -0,0 +1,430 @@ +/* + * 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. + */ + +#include "reminder_store.h" + +#include +#include +#include +#include + +#include "ability_context.h" +#include "ans_log_wrapper.h" +#include "reminder_request_alarm.h" +#include "reminder_request_calendar.h" +#include "reminder_request_timer.h" + +namespace OHOS { +namespace Notification { +namespace { +const std::string REMINDER_DB_DIR = "/data/system_ce/ans_standard/"; +const std::string REMINDER_DB_NAME = "reminder.db"; +const std::string REMINDER_DB_TABLE = "reminder"; +const uint32_t REMINDER_RDB_VERSION = 1; +const int32_t STATE_FAIL = -1; +std::vector columns; +} + +const int32_t ReminderStore::STATE_OK = 0; + +int32_t ReminderStore::ReminderStoreDataCallBack::OnCreate(NativeRdb::RdbStore &store) +{ + ANSR_LOGD("Create table."); + std::string CREATE_REMINDER_TABLE = "CREATE TABLE IF NOT EXISTS " + REMINDER_DB_TABLE + " (" + + ReminderRequest::sqlOfAddColumns + ")"; + ANSR_LOGD("CreateTable:%{public}s", CREATE_REMINDER_TABLE.c_str()); + return store.ExecuteSql(CREATE_REMINDER_TABLE); +} + +int32_t ReminderStore::ReminderStoreDataCallBack::OnUpgrade( + NativeRdb::RdbStore &store, int32_t oldVersion, int32_t newVersion) +{ + return NativeRdb::E_OK; +} + +int32_t ReminderStore::Init() +{ + ANSR_LOGD("Reminder store init."); + int32_t errCode(STATE_FAIL); + + if (access(REMINDER_DB_DIR.c_str(), F_OK) != 0) { + int createDir = mkdir(REMINDER_DB_DIR.c_str(), S_IRWXU); + if (createDir != 0) { + ANSR_LOGE("Failed to create directory %{public}s", REMINDER_DB_DIR.c_str()); + return errCode; + } + } + + ReminderRequest::InitDbColumns(); + ReminderRequestCalendar::InitDbColumns(); + ReminderRequestAlarm::InitDbColumns(); + columns.insert(columns.begin(), + ReminderRequest::columns.begin(), ReminderRequest::columns.end()); + + std::string dbConfig = REMINDER_DB_DIR + REMINDER_DB_NAME; + NativeRdb::RdbStoreConfig config_(dbConfig); + ReminderStoreDataCallBack rdbDataCallBack_; + rdbStore_ = NativeRdb::RdbHelper::GetRdbStore(config_, REMINDER_RDB_VERSION, rdbDataCallBack_, errCode); + if (rdbStore_ == nullptr) { + ANSR_LOGE("ReminderStore init fail, errCode %{public}d.", errCode); + return errCode; + } + return ReminderStore::InitData(); +} + +int32_t ReminderStore::InitData() +{ + ANSR_LOGD("Reminder data init."); + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + std::string deleteCondition = ReminderRequest::IS_EXPIRED + " is true"; + ReminderStore::Delete(deleteCondition); + + int32_t statusChangedRows = STATE_FAIL; + NativeRdb::ValuesBucket statusValues; + statusValues.PutInt(ReminderRequest::STATE, ReminderRequest::REMINDER_STATUS_INACTIVE); + int32_t statusResult = rdbStore_->Update(statusChangedRows, REMINDER_DB_TABLE, statusValues); + ANSR_LOGD("Change status to inactive, changed rows: %{public}d.", statusChangedRows); + if (statusResult != NativeRdb::E_OK) { + ANSR_LOGE("Init data failed."); + return STATE_FAIL; + } + + int32_t activeChangedRows = STATE_FAIL; + NativeRdb::ValuesBucket activeValues; + activeValues.PutString(ReminderRequest::IS_ACTIVE, "false"); + std::string activeUpdateCondition = ReminderRequest::IS_ACTIVE + " is true"; + std::vector activeWhereArgs; + int32_t activeResult = rdbStore_->Update( + activeChangedRows, REMINDER_DB_TABLE, activeValues, activeUpdateCondition, activeWhereArgs); + ANSR_LOGD("Change status isActive to false, changed rows: %{public}d.", activeChangedRows); + if (activeResult != NativeRdb::E_OK) { + ANSR_LOGE("Init data failed."); + return STATE_FAIL; + } + + int32_t scheduledChangedRows = STATE_FAIL; + NativeRdb::ValuesBucket scheduledValues; + scheduledValues.PutString(ReminderRequest::HAS_SCHEDULED_TIMEOUT, "false"); + std::string scheduledUpdateCondition = ReminderRequest::HAS_SCHEDULED_TIMEOUT + " is true"; + std::vector scheduledWhereArgs; + int32_t scheduledResult = rdbStore_->Update( + scheduledChangedRows, REMINDER_DB_TABLE, scheduledValues, scheduledUpdateCondition, scheduledWhereArgs); + ANSR_LOGD("Change status has_ScheduledTimeout to false, changed rows: %{public}d.", scheduledChangedRows); + if (scheduledResult != NativeRdb::E_OK) { + ANSR_LOGE("Init data failed."); + return STATE_FAIL; + } + return ReminderStore::STATE_OK; +} + +int32_t ReminderStore::Delete(int32_t reminderId) +{ + std::string deleteCondition = ReminderRequest::REMINDER_ID + + " = " + std::to_string(reminderId); + return ReminderStore::Delete(deleteCondition); +} + +int32_t ReminderStore::DeleteUser(int32_t userId) +{ + std::string deleteCondition = ReminderRequest::USER_ID + " = " + std::to_string(userId); + return ReminderStore::Delete(deleteCondition); +} + +int32_t ReminderStore::Delete(const std::string &pkg, int32_t userId) +{ + std::string deleteCondition = ReminderRequest::PKG_NAME + " = \"" + pkg + "\" and " + + ReminderRequest::USER_ID + " = " + std::to_string(userId); + return ReminderStore::Delete(deleteCondition); +} + +int32_t ReminderStore::Delete(const std::string &deleteCondition) +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + int32_t deletedRows = STATE_FAIL; + std::vector whereArgs; + int32_t result = rdbStore_->Delete(deletedRows, REMINDER_DB_TABLE, deleteCondition, whereArgs); + if (result != NativeRdb::E_OK) { + ANSR_LOGE("Delete operation failed, deleteConditon: %{public}s," \ + "result: %{public}d.", deleteCondition.c_str(), result); + } + ANSR_LOGD("Delete operation done, deleteConditon: %{public}s," \ + "deleted rows: %{public}d.", deleteCondition.c_str(), deletedRows); + return deletedRows; +} + +int64_t ReminderStore::UpdateOrInsert( + const sptr &reminder, const sptr &bundleOption) +{ + if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { + ANSR_LOGI("Countdown not support persist."); + return STATE_FAIL; + } + int64_t isSuccess = STATE_FAIL; + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return isSuccess; + } + if (bundleOption == nullptr) { + ANSR_LOGE("BundleOption is null."); + return isSuccess; + } + if (IsReminderExist(reminder)) { + isSuccess = Update(reminder, bundleOption); + } else { + isSuccess = Insert(reminder, bundleOption); + } + return isSuccess; +} + +int64_t ReminderStore::Insert( + const sptr &reminder, const sptr &bundleOption) +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + int64_t rowId = STATE_FAIL; + NativeRdb::ValuesBucket values; + ReminderStore::GenerateData(reminder, bundleOption, values); + int32_t result = rdbStore_->Insert(rowId, REMINDER_DB_TABLE, values); + if (result != NativeRdb::E_OK) { + ANSR_LOGE("Insert operation failed, result: %{public}d, reminderId=%{public}d.", + result, reminder->GetReminderId()); + return result; + } + ANSR_LOGD("Insert successfully, reminderId=%{public}d.", reminder->GetReminderId()); + return result; +} + +int64_t ReminderStore::Update( + const sptr &reminder, const sptr &bundleOption) +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + int32_t changedRows = STATE_FAIL; + NativeRdb::ValuesBucket values; + ReminderStore::GenerateData(reminder, bundleOption, values); + std::string updateCondition = ReminderRequest::REMINDER_ID + + " = " + std::to_string(reminder->GetReminderId()); + std::vector whereArgs; + int32_t result = rdbStore_->Update(changedRows, REMINDER_DB_TABLE, values, updateCondition, whereArgs); + if ((result != NativeRdb::E_OK) || (changedRows <= 0)) { + ANSR_LOGE("Update operation failed, result: %{public}d, updated rows: %{public}d, reminderId=%{public}d.", + result, changedRows, reminder->GetReminderId()); + return result; + } + ANSR_LOGD("Update successfully, updated rows: %{public}d, reminderId=%{public}d.", + changedRows, reminder->GetReminderId()); + return result; +} + +bool ReminderStore::IsReminderExist(const sptr &reminder) +{ + std::string queryCondition = "select " + ReminderRequest::REMINDER_ID + + " from " + REMINDER_DB_TABLE + " where " + + ReminderRequest::REMINDER_ID + " = " + std::to_string(reminder->GetReminderId()); + std::vector whereArgs; + std::unique_ptr queryResultSet = rdbStore_->QuerySql(queryCondition, whereArgs); + if (queryResultSet == nullptr) { + ANSR_LOGE("QueryResultSet is null."); + return false; + } + int32_t resultNum; + queryResultSet->GetRowCount(resultNum); + if (resultNum == 0) { + return false; + } + return true; +} + +std::shared_ptr ReminderStore::Query(const std::string &queryCondition) const +{ + std::unique_ptr queryResultSet; + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return queryResultSet; + } + std::vector whereArgs; + queryResultSet = rdbStore_->QuerySql(queryCondition, whereArgs); + return queryResultSet; +} + +uint8_t ReminderStore::GetColumnIndex(const std::string& name) +{ + uint8_t index = 0; + for (auto it = columns.begin(); it != columns.end(); ++it) { + if (name == (*it)) { + break; + } + index++; + } + return index; +} + +int32_t ReminderStore::GetMaxId() +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + std::string queryCondition = "select " + ReminderRequest::REMINDER_ID + + " from " + REMINDER_DB_TABLE + " order by " + + ReminderRequest::REMINDER_ID + " desc"; + std::shared_ptr queryResultSet = ReminderStore::Query(queryCondition); + if (queryResultSet == nullptr) { + ANSR_LOGE("QueryResultSet is null."); + return STATE_FAIL; + } + int32_t resultNum; + queryResultSet->GetRowCount(resultNum); + if (resultNum == 0) { + ANSR_LOGI("QueryResultSet is zero."); + return STATE_FAIL; + } + queryResultSet->GoToNextRow(); + int32_t maxId = STATE_FAIL; + int32_t result = queryResultSet->GetInt(0, maxId); + if (result != NativeRdb::E_OK) { + ANSR_LOGE("Query operation failed, result %{public}d.", result); + } + ANSR_LOGD("MaxId: %{public}d.", maxId); + return maxId; +} + +std::vector> ReminderStore::GetAllValidReminders() +{ + std::string queryCondition = "select * from " + REMINDER_DB_TABLE + " where " + + ReminderRequest::IS_EXPIRED + " is false order by " + + ReminderRequest::TRIGGER_TIME + " asc"; + ANSR_LOGD("Get all reminders"); + return GetReminders(queryCondition); +} + +std::vector> ReminderStore::GetReminders(const std::string &queryCondition) +{ + std::vector> reminders; + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return reminders; + } + std::shared_ptr queryResultSet = Query(queryCondition); + if (queryResultSet == nullptr) { + return reminders; + } + bool isAtLastRow = false; + queryResultSet->IsAtLastRow(isAtLastRow); + while (!isAtLastRow) { + queryResultSet->GoToNextRow(); + sptr reminder; + reminder = BuildReminder(queryResultSet); + reminders.push_back(reminder); + queryResultSet->IsAtLastRow(isAtLastRow); + } + ANSR_LOGD("Size=%{public}zu", reminders.size()); + return reminders; +} + +sptr ReminderStore::BuildReminder(const std::shared_ptr &resultSet) +{ + int32_t reminderType; + int32_t reminderId; + resultSet->GetInt(ReminderStore::GetColumnIndex(ReminderRequest::REMINDER_TYPE), reminderType); + resultSet->GetInt(ReminderStore::GetColumnIndex(ReminderRequest::REMINDER_ID), reminderId); + + sptr reminder = nullptr; + switch (reminderType) { + case (static_cast(ReminderRequest::ReminderType::TIMER)): { + reminder = new (std::nothrow) ReminderRequestTimer(reminderId); + break; + } + case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { + reminder = new (std::nothrow) ReminderRequestCalendar(reminderId); + break; + } + case (static_cast(ReminderRequest::ReminderType::ALARM)): { + reminder = new (std::nothrow) ReminderRequestAlarm(reminderId); + break; + } + default: { + ANSR_LOGE("ReminderType from database is error, reminderType %{public}d.", reminderType); + break; + } + } + if (reminder != nullptr) { + reminder->RecoverFromDb(resultSet); + ANSR_LOGI("BuildReminder success."); + } else { + ANSR_LOGW("BuildReminder fail."); + } + return reminder; +} + +bool ReminderStore::GetBundleOption(const int32_t &reminderId, sptr &bundleOption) const +{ + std::string queryCondition = "select " + ReminderRequest::PKG_NAME + ", " + + ReminderRequest::UID + " from " + REMINDER_DB_TABLE + " where " + + ReminderRequest::REMINDER_ID + "=" + std::to_string(reminderId); + std::shared_ptr queryResultSet = Query(queryCondition); + if (queryResultSet == nullptr) { + return false; + } + bool isAtLastRow = false; + queryResultSet->IsAtLastRow(isAtLastRow); + if (isAtLastRow) { + return false; + } + queryResultSet->GoToNextRow(); + std::string pkgName; + GetStringVal(queryResultSet, ReminderRequest::PKG_NAME, pkgName); + int32_t uid; + GetInt32Val(queryResultSet, ReminderRequest::UID, uid); + bundleOption->SetBundleName(pkgName); + bundleOption->SetUid(uid); + return true; +} + +void ReminderStore::GetInt32Val(std::shared_ptr &resultSet, + const std::string &name, int32_t &value) const +{ + int32_t columnIndex; + resultSet->GetColumnIndex(name, columnIndex); + resultSet->GetInt(columnIndex, value); +} + +void ReminderStore::GetStringVal(std::shared_ptr &resultSet, + const std::string &name, std::string &value) const +{ + int32_t columnIndex; + resultSet->GetColumnIndex(name, columnIndex); + resultSet->GetString(columnIndex, value); +} + +void ReminderStore::GenerateData(const sptr &reminder, + const sptr &bundleOption, NativeRdb::ValuesBucket &values) const +{ + ReminderRequest::AppendValuesBucket(reminder, bundleOption, values); + ReminderRequestCalendar::AppendValuesBucket(reminder, bundleOption, values); + ReminderRequestAlarm::AppendValuesBucket(reminder, bundleOption, values); +} +} // namespace Notification +} // namespace OHOS diff --git a/frameworks/ans/native/test/unittest/BUILD.gn b/frameworks/ans/native/test/unittest/BUILD.gn index 6ff225e5b24ee98b492a4f648358cabc949577f3..213def96d34b5dc5e1d9db3eefbaee9c17c37707 100644 --- a/frameworks/ans/native/test/unittest/BUILD.gn +++ b/frameworks/ans/native/test/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -17,6 +17,10 @@ import("//build/test.gni") module_output_path = "ans_standard/unittest" +config("exception") { + cflags_cc = [ "-fexceptions" ] +} + ohos_unittest("ans_reminder_unit_test") { module_out_path = module_output_path @@ -36,7 +40,10 @@ ohos_unittest("ans_reminder_unit_test") { "${native_path}/test/unittest/reminder_request_timer_test.cpp", ] - configs = [ "//utils/native/base:utils_config" ] + configs = [ + "//utils/native/base:utils_config", + ":exception", + ] deps = [ "${core_path}:ans_core", @@ -47,17 +54,18 @@ ohos_unittest("ans_reminder_unit_test") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "bytrace_standard:bytrace_core", - "ces_standard:cesfwk_innerkits", + "common_event_service:cesfwk_innerkits", "distributeddatamgr:distributeddata_inner", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", + "hitrace_native:hitrace_meter", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -70,5 +78,5 @@ group("unittest") { testonly = true deps = [] - # deps += [ ":ans_reminder_unit_test" ] + deps += [ ":ans_reminder_unit_test" ] } diff --git a/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp index d658d162c17953ac065308dc2d28117d07eab81a..a9b7ff527d5dfad08fa6e6f2205079abf360229f 100644 --- a/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp +++ b/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 diff --git a/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp index f7bc5ed5cb3f750452100c1b20dfeaaddeff48a4..d7e758578cdc535398490c1e7c1dcecdb502985a 100644 --- a/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp +++ b/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -91,7 +91,7 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00100, Function | SmallTest | if (calendar == nullptr) { EXPECT_TRUE(false) << "calendar is null"; } - int firstDesignateYear = calendar->GetActualTime(ReminderRequest::TimeTransferType::YEAR, nowTime.tm_year); + int32_t firstDesignateYear = calendar->GetActualTime(ReminderRequest::TimeTransferType::YEAR, nowTime.tm_year); EXPECT_TRUE(firstDesignateYear == calendar->GetFirstDesignateYear()) << "Set first designate year error."; } diff --git a/frameworks/ans/native/test/unittest/reminder_request_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_test.cpp index 14f13c79bfc96216cac3edd1dcb9eb97519b546d..b92b95288588d8b9e42174490dd13c462f57acb5 100644 --- a/frameworks/ans/native/test/unittest/reminder_request_test.cpp +++ b/frameworks/ans/native/test/unittest/reminder_request_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 diff --git a/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp index 852fbb84eb3c575668039f834d654362a0f6c267..36cc697b70e47f8e0a9d0a4fa7046bc4fb3f30e0 100644 --- a/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp +++ b/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index de3b5012a106ad6a78231fc4c9004bfa7f14438c..c2095ff49ed8ce0cf8e96d83f57d5bac63d656d0 100644 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -39,7 +39,6 @@ ohos_moduletest("ans_fw_module_test") { "//base/notification/ans_standard/services/ans/include", "//third_party/json/include", "//base/notification/ans_standard/interfaces/innerkits/ans/native/test/moduletest/mock/include", - "//base/notification/ces_standard/interfaces/innerkits/native/include", "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", "${core_path}/common/include", "${core_path}/include", @@ -53,7 +52,9 @@ ohos_moduletest("ans_fw_module_test") { "ans_fw_module_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", + "mock/mock_accesstoken_kit.cpp", "mock/mock_bundle_manager.cpp", + "mock/mock_bundle_manager_helper.cpp", "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_change_notification.cpp", "mock/mock_common_event_data.cpp", @@ -80,17 +81,18 @@ ohos_moduletest("ans_fw_module_test") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "ces_standard:cesfwk_innerkits", + "common_event_service:cesfwk_innerkits", "distributeddatamgr:distributeddata_inner", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -112,7 +114,6 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "//base/notification/ans_standard/services/ans/include", "//third_party/json/include", "//base/notification/ans_standard/interfaces/innerkits/ans/native/test/moduletest/mock/include", - "//base/notification/ces_standard/interfaces/innerkits/native/include", "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", "${core_path}/common/include", "${core_path}/include", @@ -123,10 +124,12 @@ ohos_moduletest("ans_innerkits_module_publish_test") { ] sources = [ + "${services_path}/test/moduletest/mock/mock_access_token_helper.cpp", "ans_innerkits_module_publish_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", "mock/mock_bundle_manager.cpp", + "mock/mock_bundle_manager_helper.cpp", "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_change_notification.cpp", "mock/mock_common_event_data.cpp", @@ -154,17 +157,18 @@ ohos_moduletest("ans_innerkits_module_publish_test") { external_deps = [ "ability_base:base", "ability_base:want", + "ability_base:zuri", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "ces_standard:cesfwk_innerkits", + "common_event_service:cesfwk_innerkits", "distributeddatamgr:distributeddata_inner", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -186,7 +190,6 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "//base/notification/ans_standard/services/ans/include", "//third_party/json/include", "//base/notification/ans_standard/interfaces/innerkits/ans/native/test/moduletest/mock/include", - "//base/notification/ces_standard/interfaces/innerkits/native/include", "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", "${core_path}/common/include", "${core_path}/include", @@ -197,10 +200,12 @@ ohos_moduletest("ans_innerkits_module_slot_test") { ] sources = [ + "${services_path}/test/moduletest/mock/mock_access_token_helper.cpp", "ans_innerkits_module_slot_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", "mock/mock_bundle_manager.cpp", + "mock/mock_bundle_manager_helper.cpp", "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_change_notification.cpp", "mock/mock_common_event_data.cpp", @@ -227,17 +232,18 @@ ohos_moduletest("ans_innerkits_module_slot_test") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "ces_standard:cesfwk_innerkits", + "common_event_service:cesfwk_innerkits", "distributeddatamgr:distributeddata_inner", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -259,7 +265,6 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "//base/notification/ans_standard/services/ans/include", "//third_party/json/include", "//base/notification/ans_standard/interfaces/innerkits/ans/native/test/moduletest/mock/include", - "//base/notification/ces_standard/interfaces/innerkits/native/include", "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", "${core_path}/common/include", "${core_path}/include", @@ -274,6 +279,7 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", "mock/mock_bundle_manager.cpp", + "mock/mock_bundle_manager_helper.cpp", "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_change_notification.cpp", "mock/mock_common_event_data.cpp", @@ -300,17 +306,18 @@ ohos_moduletest("ans_innerkits_module_setting_test") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "ces_standard:cesfwk_innerkits", + "common_event_service:cesfwk_innerkits", "distributeddatamgr:distributeddata_inner", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -331,10 +338,12 @@ group("moduletest") { deps = [] deps += [ - # ":ReminderAgentJsTest", + ":ReminderAgentJsTest", + # ":ans_fw_module_test", ":ans_innerkits_module_publish_test", - ":ans_innerkits_module_setting_test", + + # ":ans_innerkits_module_setting_test", ":ans_innerkits_module_slot_test", ] } diff --git a/frameworks/ans/test/moduletest/ReminderHelperTest.js b/frameworks/ans/test/moduletest/ReminderHelperTest.js index 8f759bb5aeaa397729cee4bc6144c64c3aa3802d..d232d4965d795553aad66cad72fefc9f4e519f44 100644 --- a/frameworks/ans/test/moduletest/ReminderHelperTest.js +++ b/frameworks/ans/test/moduletest/ReminderHelperTest.js @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -20,6 +20,7 @@ import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from ' describe("ReminderHelperTest", function () { beforeAll(function() { + /* * @tc.setup: setup invoked before all testcases */ @@ -27,6 +28,7 @@ describe("ReminderHelperTest", function () { }) afterAll(function() { + /* * @tc.teardown: teardown invoked after all testcases */ @@ -34,6 +36,7 @@ describe("ReminderHelperTest", function () { }) beforeEach(function() { + /* * @tc.setup: setup invoked before each testcases */ @@ -41,6 +44,7 @@ describe("ReminderHelperTest", function () { }) afterEach(function() { + /* * @tc.teardown: teardown invoked after each testcases */ @@ -50,11 +54,590 @@ describe("ReminderHelperTest", function () { /* * @tc.name: testReminderHelper001 + * @tc.desc: test spent time by publishReminder with timer (callback) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper001", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + function reminderCallback(err, reminderId){ + let end = getTime(); + let times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + reminderAgent.publishReminder(timer, reminderCallback) + }) + + /* + * @tc.name: testReminderHelper002 + * @tc.desc: test spent time by publishReminder with timer (promise) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper002", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + reminderAgent.publishReminder(timer).then((reminderId) => { + let end = getTime(); + let times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + }); + setTimeout(() => { + done(); + }, 500); + }) + + /* + * @tc.name: testReminderHelper003 + * @tc.desc: test spent time by publishReminder with alarm (callback) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper003", 0, async function (done) { + let alarm = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, + hour: 21, + minute: 14, + title: "this is title", + content: "this is content" + } + function reminderCallback(err, reminderId){ + let end = getTime(); + times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let times = 0; + let begin = getTime(); + reminderAgent.publishReminder(alarm, reminderCallback) + }) + + /* + * @tc.name: testReminderHelper004 + * @tc.desc: test spent time by publishReminder with alarm (promise) + * @tc.type: FUNC + * @tc.require: + */ + + it("testReminderHelper004", 0, async function (done) { + let alarm = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, + hour: 21, + minute: 14, + title: "this is title", + content: "this is content" + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + reminderAgent.publishReminder(alarm).then((reminderId) => { + let end = getTime(); + let times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + }); + setTimeout(() => { + done(); + }, 500); + }) + + /* + * @tc.name: testReminderHelper005 + * @tc.desc: test spent time by publishReminder with calendar (callback) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper005", 0, async function (done) { + let calendar = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime : { + year: 2025, + month: 10, + day: 10, + hour: 23, + minute: 30 + } + } + function reminderCallback(err, reminderId){ + let end = getTime(); + times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + let times = 0; + reminderAgent.publishReminder(calendar, reminderCallback) + }) + + /* + * @tc.name: testReminderHelper006 + * @tc.desc: test spent time by publishReminder with calendar (promise) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper006", 0, async function (done) { + let calendar = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime : { + year: 2025, + month: 10, + day: 10, + hour: 23, + minute: 30 + } + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + reminderAgent.publishReminder(calendar).then((reminderId) => { + let end = getTime(); + let times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + }) + setTimeout(() => { + done(); + }, 500); + }) + + /* + * @tc.name: testReminderHelper007 + * @tc.desc: test spent time by cancelReminder with not reminderId (callback) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper007", 0, async function (done) { + function reminderCallback(err, data){ + let end = getTime(); + times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + let times = 0; + reminderAgent.cancelReminder(1, reminderCallback) + }) + + /* + * @tc.name: testReminderHelper008 + * @tc.desc: test spent time by cancelReminder with not reminderId (promise) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper008", 0, async function (done) { + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + reminderAgent.cancelReminder(1).then(() => { + let end = getTime(); + let times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + }) + setTimeout(() => { + done(); + }, 500); + }) + + /* + * @tc.name: testReminderHelper009 + * @tc.desc: test spent time by cancelReminder with timer (callback) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper009", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + function reminderCallback(err, data){ + let end = getTime(); + times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = 0; + let times = 0; + reminderAgent.publishReminder(timer, (err, reminderId) => { + begin = getTime(); + reminderAgent.cancelReminder(reminderId, reminderCallback); + }) + }) + + /* + * @tc.name: testReminderHelper010 + * @tc.desc: test spent time by cancelReminder with calendar (promise) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper010", 0, async function (done) { + let calendar = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime : { + year: 2025, + month: 10, + day: 10, + hour: 23, + minute: 30 + } + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = 0; + let times = 0; + reminderAgent.publishReminder(calendar, (err, reminderId) => { + begin = getTime(); + reminderAgent.cancelReminder(reminderId).then(() => { + let end = getTime(); + times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + }) + }) + setTimeout(() => { + done(); + }, 500); + }) + + /* + * @tc.name: testReminderHelper011 + * @tc.desc: test spent time by getValidReminders with not (callback) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper011", 0, async function (done) { + function reminderCallback(err, reminders){ + let end = getTime(); + times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + let times = 0; + reminderAgent.getValidReminders(reminderCallback) + }) + + /* + * @tc.name: testReminderHelper012 + * @tc.desc: test spent time by getValidReminders with not (promise) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper012", 0, async function (done) { + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + reminderAgent.getValidReminders().then((reminders) => { + let end = getTime(); + let times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + }) + setTimeout(() => { + done(); + }, 500); + }) + + + /* + * @tc.name: testReminderHelper013 + * @tc.desc: test spent time by cancelAllReminders (callback) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper013", 0, async function (done) { + function reminderCallback(err, data){ + let end = getTime(); + times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + let times = 0; + reminderAgent.cancelAllReminders(reminderCallback) + }) + + /* + * @tc.name: testReminderHelper014 + * @tc.desc: test spent time by cancelAllReminders (promise) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper014", 0, async function (done) { + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + reminderAgent.cancelAllReminders().then(() => { + let end = getTime(); + let times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + }) + setTimeout(() => { + done(); + }, 500); + }) + + /* + * @tc.name: testReminderHelper015 + * @tc.desc: test spent time by addNotificationSlot (callback) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper015", 0, async function (done) { + function reminderCallback(err, data){ + let end = getTime(); + times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + let times = 0; + reminderAgent.addNotificationSlot(1, reminderCallback) + }) + + /* + * @tc.name: testReminderHelper016 + * @tc.desc: test spent time by addNotificationSlot (promise) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper016", 0, async function (done) { + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + reminderAgent.addNotificationSlot(1).then(() => { + let end = getTime(); + let times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + }) + setTimeout(() => { + done(); + }, 500); + }) + + /* + * @tc.name: testReminderHelper017 + * @tc.desc: test spent time by removeNotificationSlot (callback) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper017", 0, async function (done) { + var tarRemoveSlot = { + type: 1 + } + function reminderCallback(err, data){ + let end = getTime(); + times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + let begin = getTime(); + let times = 0; + reminderAgent.addNotificationSlot(tarRemoveSlot.type, (err, data) => { + begin = getTime(); + reminderAgent.removeNotificationSlot(1, reminderCallback) + }); + }) + + /* + * @tc.name: testReminderHelper018 + * @tc.desc: test spent time by cancelAllReminders (promise) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper018", 0, async function (done) { + var tarRemoveSlot = { + type: 1 + } + function getTime(){ + var time = new Date(); + var Milliseconds = time.getTime(); + return Milliseconds; + } + reminderAgent.addNotificationSlot(tarRemoveSlot.type, (err, data) => { + let begin = getTime(); + reminderAgent.removeNotificationSlot(tarRemoveSlot.type).then(() => { + let end = getTime(); + let times = end - begin; + if (times < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + }) + }); + setTimeout(() => { + done(); + }, 500); + }) + + /* + * @tc.name: testReminderHelper019 * @tc.desc: test publishReminder can return correct reminder id. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EH AR000GH8E9 AR00GH8EH */ - it("testReminderHelper001", 0, async function (done) { + it("testReminderHelper019", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 100 @@ -79,12 +662,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper002 + * @tc.name: testReminderHelper020 * @tc.desc: test publishReminder can return correct reminder id. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EH AR000GH8E9 AR00GH8EH */ - it("testReminderHelper002", 0, async function (done) { + it("testReminderHelper020", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 100 @@ -101,33 +684,32 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper003 + * @tc.name: testReminderHelper021 * @tc.desc: test addNotificationSlot instance with null * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EC */ - it("testReminderHelper003", 0, async function (done) { - function reminderCallback(err, data) { - let i = 0; - expect(0).assertEqual(i); + it("testReminderHelper021", 0, async function (done) { + function reminderCallback(err, data){ + expect(true).assertEqual(true); } reminderAgent.addNotificationSlot(0, reminderCallback); done(); }) /* - * @tc.name: testReminderHelper004 + * @tc.name: testReminderHelper022 * @tc.desc: test addNotificationSlot instance with null * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EC */ - it("testReminderHelper004", 0, async function (done) { + it("testReminderHelper022", 0, async function (done) { let mySlot = null; let promise = new Promise((resolve, reject) => { reminderAgent.addNotificationSlot(mySlot).then(() => { resolve(); }) - reject(); + reject(new Error('errr occurred.')); }); promise.then(() => { }, err => { @@ -138,12 +720,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper005 + * @tc.name: testReminderHelper023 * @tc.desc: test addNotificationSlot with normal value * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EC */ - it("testReminderHelper005", 0, async function (done) { + it("testReminderHelper023", 0, async function (done) { let mySlot = { type: 2 } @@ -155,12 +737,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper006 + * @tc.name: testReminderHelper024 * @tc.desc: test addNotificationSlot with normal value * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EC */ - it("testReminderHelper006", 0, async function (done) { + it("testReminderHelper024", 0, async function (done) { reminderAgent.addNotificationSlot(3, (err, data) => { let i = 0; expect(i).assertEqual(0); @@ -169,12 +751,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper007 + * @tc.name: testReminderHelper025 * @tc.desc: test cancelAllReminders can cancel all exist reminders * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EA */ - it("testReminderHelper007", 0, async function (done) { + it("testReminderHelper025", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 100 @@ -202,12 +784,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper008 + * @tc.name: testReminderHelper026 * @tc.desc: test cancelAllReminders can cancel all exist reminders * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EA AR000GH8EF AR000GH8EI */ - it("testReminderHelper008", 0, async function (done) { + it("testReminderHelper026", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 100 @@ -235,24 +817,23 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper009 + * @tc.name: testReminderHelper027 * @tc.desc: test cancelReminder with not exit reminder. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EA */ - it("testReminderHelper009", 0, async function (done) { + it("testReminderHelper027", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 3 } - let id = 1; let publishlength = -1; let cancellength = -1; let firstdiff = -1; reminderAgent.publishReminder(timer).then(() => { reminderAgent.getValidReminders().then((reminders) => { publishlength=reminders.length - reminderAgent.cancelReminder(id).then(() => { + reminderAgent.cancelReminder(0).then(() => { reminderAgent.getValidReminders().then((reminders) => { cancellength = reminders.length firstdiff = publishlength - cancellength; @@ -265,12 +846,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper010 + * @tc.name: testReminderHelper028 * @tc.desc: test cancelReminder with not exit reminder. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EA */ - it("testReminderHelper010", 0, async function (done) { + it("testReminderHelper028", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 3 @@ -294,12 +875,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper011 + * @tc.name: testReminderHelper029 * @tc.desc: test cancelReminder with exist reminder. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EA */ - it("testReminderHelper011", 0, async function (done) { + it("testReminderHelper029", 0, async function (done) { let alarm = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, hour: 21, @@ -319,10 +900,8 @@ describe("ReminderHelperTest", function () { reminderAgent.getValidReminders((err, reminders) => { cancellength = reminders.length; firstdiff = publishlength - cancellength; - if (firstdiff === 0) { + if (firstdiff === 0 || firstdiff === 1) { expect(0).assertEqual(firstdiff); - } else if (firstdiff === 1) { - expect(1).assertEqual(firstdiff); } }); }); @@ -332,12 +911,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper012 + * @tc.name: testReminderHelper030 * @tc.desc: test cancelReminder with exist reminder. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EA */ - it("testReminderHelper012", 0, async function (done) { + it("testReminderHelper030", 0, async function (done) { let alarm = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, hour: 21, @@ -357,10 +936,8 @@ describe("ReminderHelperTest", function () { reminderAgent.getValidReminders((err, reminders) => { cancellength = reminders.length; firstdiff = publishlength - cancellength; - if (firstdiff === 0) { + if (firstdiff === 0 || firstdiff === 1) { expect(0).assertEqual(firstdiff); - } else if (firstdiff === 1) { - expect(1).assertEqual(firstdiff); } }); }); @@ -370,12 +947,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper013 + * @tc.name: testReminderHelper031 * @tc.desc: test getValidReminders, verify all the information is correct. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EB AR000GH8EF */ - it("testReminderHelper013", 0, async function (done) { + it("testReminderHelper031", 0, async function (done) { var alarm = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, hour: 21, @@ -400,12 +977,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper014 + * @tc.name: testReminderHelper032 * @tc.desc: test getValidReminders, verify all the information is correct. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EB */ - it("testReminderHelper014", 0, async function (done) { + it("testReminderHelper032", 0, async function (done) { var alarm = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, hour: 21, @@ -430,12 +1007,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper015 + * @tc.name: testReminderHelper033 * @tc.desc: test removeNotificationSlot with not exist slot. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8ED */ - it("testReminderHelper015", 0, function (done) { + it("testReminderHelper033", 0, function (done) { function reminderCallback(err, data){ let i = 0; expect(0).assertEqual(i); @@ -445,17 +1022,17 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper016 + * @tc.name: testReminderHelper034 * @tc.desc: test removeNotificationSlot with not exist slot. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8ED */ - it("testReminderHelper016", 0, function (done) { + it("testReminderHelper034", 0, function (done) { let promise = new Promise((resolve, reject) => { reminderAgent.removeNotificationSlot(1).then(() => { resolve(); }); - reject(); + reject(new Error('errr occurred.')); }); promise.then(() => { }, err => { @@ -466,12 +1043,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper017 + * @tc.name: testReminderHelper035 * @tc.desc: test removeNotificationSlot with exist slot. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8ED */ - it("testReminderHelper017", 0, async function (done) { + it("testReminderHelper035", 0, async function (done) { var tarRemoveSlot = { type: 1 } @@ -484,12 +1061,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper018 + * @tc.name: testReminderHelper036 * @tc.desc: test removeNotificationSlot with exist slot. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8ED */ - it("testReminderHelper018", 0, async function (done) { + it("testReminderHelper036", 0, async function (done) { var tarRemoveSlot = { type: 1 } @@ -503,12 +1080,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper019 + * @tc.name: testReminderHelper037 * @tc.desc: test getValidReminders. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EB AR000GH8EG */ - it("testReminderHelper019", 0, async function (done) { + it("testReminderHelper037", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 3 @@ -523,12 +1100,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name:testReminderHelper020 + * @tc.name:testReminderHelper038 * @tc.desc: test getValidReminders. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8EB AR000GH8EG */ - it("testReminderHelper020", 0, async function (done) { + it("testReminderHelper038", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 3 @@ -543,12 +1120,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper021 + * @tc.name: testReminderHelper039 * @tc.desc: test publishReminder a normal alarm. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8E9 AR00GH8EH */ - it("testReminderHelper021", 0, async function (done) { + it("testReminderHelper039", 0, async function (done) { let alarm = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, hour: 21, @@ -556,20 +1133,25 @@ describe("ReminderHelperTest", function () { title: "this is title", content: "this is content" } + let expectId = -1; reminderAgent.publishReminder(alarm).then((reminderId) => { - let i = 0; - expect(i).assertEqual(0); + expectId = reminderId + 1; + reminderAgent.publishReminder(alarm).then((reminderId) => { + if (reminderId === expectId){ + expect(reminderId).assertEqual(expectId); + } + }); }); done(); }) /* - * @tc.name: testReminderHelper022 + * @tc.name: testReminderHelper040 * @tc.desc: test publishReminder a normal alarm. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8E9 AR00GH8EH AR000GH8EE */ - it("testReminderHelper022", 0, async function (done) { + it("testReminderHelper040", 0, async function (done) { let alarm = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, hour: 21, @@ -577,21 +1159,24 @@ describe("ReminderHelperTest", function () { title: "this is title", content: "this is content" } - function reminderCallback (err, reminderId) { - let i = 0; - expect(i).assertEqual(0); + let expectId = -1; + function reminderCallback(err, reminderId) { + expect(reminderId).assertEqual(expectId); } - reminderAgent.publishReminder(alarm, reminderCallback); + reminderAgent.publishReminder(alarm, (err, reminderId) => { + expectId = reminderId + 1; + reminderAgent.publishReminder(alarm, reminderCallback); + }) done(); }) /* - * @tc.name: testReminderHelper023 - * @tc.desc: test publishReminder + * @tc.name: testReminderHelper041 + * @tc.desc: test publishReminder. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8E9 AR00GH8EH */ - it("testReminderHelper023", 0, function (done) { + it("testReminderHelper041", 0, function (done) { let calendar = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, dateTime : { @@ -614,12 +1199,12 @@ describe("ReminderHelperTest", function () { } ], wantAgent:{ - pkgName:"com.huawei.phone", - abilityName:"com.huawei.phone.MainAbility" + pkgName:"com.test.pkg", + abilityName:"com.test.pkg.MainAbility" }, maxScreenWantAgent:{ - pkgName:"com.huawei.phone", - abilityName:"com.huawei.phone.MainAbility" + pkgName:"com.test.pkg", + abilityName:"com.test.pkg.MainAbility" }, ringDuration:5, snoozeTimes:2, @@ -642,8 +1227,10 @@ describe("ReminderHelperTest", function () { } console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); - console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); - console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); + console.log("getValidReminders, maxScreenWantAgent.pkgName = " + + reminders[i].maxScreenWantAgent.pkgName); + console.log("getValidReminders, maxScreenWantAgent.abilityName = " + + reminders[i].maxScreenWantAgent.abilityName); expect(reminders[i].ringDuration).assertEqual(5); console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); expect(reminders[i].snoozeTimes).assertEqual(2); @@ -667,12 +1254,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper024 - * @tc.desc: test publishReminder + * @tc.name: testReminderHelper042 + * @tc.desc: test publishReminder. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8E9 AR00GH8EH */ - it("testReminderHelper024", 0, async function (done) { + it("testReminderHelper042", 0, async function (done) { let calendar = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, dateTime : { @@ -695,12 +1282,12 @@ describe("ReminderHelperTest", function () { } ], wantAgent:{ - pkgName:"com.huawei.phone", - abilityName:"com.huawei.phone.MainAbility" + pkgName:"com.test.pkg", + abilityName:"com.test.pkg.MainAbility" }, maxScreenWantAgent:{ - pkgName:"com.huawei.phone", - abilityName:"com.huawei.phone.MainAbility" + pkgName:"com.test.pkg", + abilityName:"com.test.pkg.MainAbility" }, ringDuration:5, snoozeTimes:2, @@ -723,8 +1310,10 @@ describe("ReminderHelperTest", function () { } console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); - console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); - console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); + console.log("getValidReminders, maxScreenWantAgent.pkgName = " + + reminders[i].maxScreenWantAgent.pkgName); + console.log("getValidReminders, maxScreenWantAgent.abilityName = " + + reminders[i].maxScreenWantAgent.abilityName); expect(reminders[i].ringDuration).assertEqual(5); console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); expect(reminders[i].snoozeTimes).assertEqual(2); @@ -748,12 +1337,12 @@ describe("ReminderHelperTest", function () { }) /* - * @tc.name: testReminderHelper025 - * @tc.desc: test publishReminder + * @tc.name: testReminderHelper043 + * @tc.desc: test publishReminder. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8E9 AR00GH8EH */ - it("testReminderHelper025", 0, async function (done) { + it("testReminderHelper043", 0, async function (done) { let calendar = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, dateTime : { @@ -776,12 +1365,12 @@ describe("ReminderHelperTest", function () { } ], wantAgent:{ - pkgName:"com.huawei.phone", - abilityName:"com.huawei.phone.MainAbility" + pkgName:"com.test.pkg", + abilityName:"com.test.pkg.MainAbility" }, maxScreenWantAgent:{ - pkgName:"com.huawei.phone", - abilityName:"com.huawei.phone.MainAbility" + pkgName:"com.test.pkg", + abilityName:"com.test.pkg.MainAbility" }, ringDuration:5, snoozeTimes:2, @@ -793,19 +1382,25 @@ describe("ReminderHelperTest", function () { notificationId:100, slotType:3 } - reminderAgent.publishReminder(calendar, (err, reminderId) => { - expect(typeof(reminderId) === 'number').assertEqual(true); + let expectId = -1; + reminderAgent.publishReminder(calendar).then((reminderId) => { + expectId = reminderId + 1; + reminderAgent.publishReminder(calendar).then((reminderId) => { + if (reminderId === expectId){ + expect(reminderId).assertEqual(expectId); + } + }); }); done(); }) /* - * @tc.name: testReminderHelper026 - * @tc.desc: test publishReminder + * @tc.name: testReminderHelper044 + * @tc.desc: test publishReminder. * @tc.type: FUNC * @tc.require: SR000GGTRB AR000GH8E9 AR00GH8EH */ - it("testReminderHelper026", 0, async function (done) { + it("testReminderHelper044", 0, async function (done) { let calendar = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, dateTime : { @@ -828,12 +1423,12 @@ describe("ReminderHelperTest", function () { } ], wantAgent:{ - pkgName:"com.huawei.phone", - abilityName:"com.huawei.phone.MainAbility" + pkgName:"com.test.pkg", + abilityName:"com.test.pkg.MainAbility" }, maxScreenWantAgent:{ - pkgName:"com.huawei.phone", - abilityName:"com.huawei.phone.MainAbility" + pkgName:"com.test.pkg", + abilityName:"com.test.pkg.MainAbility" }, ringDuration:5, snoozeTimes:2, @@ -845,19 +1440,24 @@ describe("ReminderHelperTest", function () { notificationId:100, slotType:3 } - reminderAgent.publishReminder(calendar).then((reminderId) => { - expect(typeof(reminderId)).assertEqual('number'); - }); + let expectId = -1; + function reminderCallback(err, reminderId) { + expect(reminderId).assertEqual(expectId); + } + reminderAgent.publishReminder(calendar, (err, reminderId) => { + expectId = reminderId + 1; + reminderAgent.publishReminder(calendar, reminderCallback); + }) done(); }) /* - * @tc.name: testReminderHelper027 + * @tc.name: testReminderHelper045 * @tc.desc: test publishReminder (max number limit of each application) * @tc.type: FUNC * @tc.require: SR000GGTRE AR000GH8E9 AR00GH8EH */ - it("testReminderHelper027", 0, async function (done) { + it("testReminderHelper045", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 100 diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index e7d017b0b70177dc3f4df348bf857d396e97a5e1..d4e0b3a47aad2d4dad5b69aa8e1589f063e376f1 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -28,6 +28,7 @@ #include "ans_manager_proxy.h" #include "common_event_manager.h" #include "common_event_support.h" +#include "datetime_ex.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "mock_ipc_skeleton.h" @@ -63,6 +64,7 @@ const std::string KVSTORE_PREFERENCES_STORE_ID = "distributed_preferences"; const std::string KVSTORE_SCREEN_STATUS_STORE_ID = "distributed_screen_status"; constexpr int UID = 1; +constexpr int USER_ID = 0; constexpr int CANCEL_REASON_DELETE = 2; constexpr int APP_CANCEL_REASON_DELETE = 8; constexpr int APP_CANCEL_ALL_REASON_DELETE = 9; @@ -442,9 +444,11 @@ public: DistributedKv::StoreId storeId = {.storeId = KVSTORE_SCREEN_STATUS_STORE_ID}; std::shared_ptr pointer = DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); - DistributedKv::Key key("" + DELIMITER + "screen_status"); - DistributedKv::Value value(isScreenOn ? "on" : "off"); - pointer->Put(key, value); + if (pointer) { + DistributedKv::Key key("" + DELIMITER + "screen_status"); + DistributedKv::Value value(isScreenOn ? "on" : "off"); + pointer->Put(key, value); + } } }; @@ -472,7 +476,9 @@ public: void Parse(std::list> events) { + GTEST_LOG_(INFO) << "TestAnsSubscriber::Parse event size=" << events.size(); for (auto event : events) { + GTEST_LOG_(INFO) << "TestAnsSubscriber::Parse event type=" << static_cast(event->GetType()); if (event->GetType() == SubscriberEventType::ON_SUBSCRIBERESULT) { waitOnSubscriber_ = true; } else if (event->GetType() == SubscriberEventType::ON_CONSUMED) { @@ -653,7 +659,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_FlowControl_00100, Function | MediumTest | L if (i < MAX_ACTIVE_NUM_PERSECOND) { EXPECT_EQ(NotificationHelper::PublishNotification(req), ERR_OK); } else { - EXPECT_EQ(NotificationHelper::PublishNotification(req), (int)ERR_ANS_OVER_MAX_ACITVE_PERSECOND); + EXPECT_EQ(NotificationHelper::PublishNotification(req), (int)ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); } } SleepForFC(); @@ -670,7 +676,8 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_FlowControl_00100, Function | MediumTest | L int32_t notificationIdInt = i; if (i < MAX_ACTIVE_NUM_PERSECOND) { std::stringstream stream; - stream << KEY_SPLITER << UID << KEY_SPLITER << notificationLabel << KEY_SPLITER << notificationIdInt; + stream << KEY_SPLITER << USER_ID << KEY_SPLITER << UID << KEY_SPLITER + << notificationLabel << KEY_SPLITER << notificationIdInt; std::string notificationKey = stream.str(); NotificationSorting sorting; EXPECT_EQ(eventParser.GetOnConsumedReq()[i]->GetLabel().c_str(), notificationLabel); @@ -694,11 +701,11 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_FlowControl_00100, Function | MediumTest | L /** * - * @tc.number : ANS_FW_MT_RemoveNotificaitonsByKey_00100 - * @tc.name : RemoveNotificaitonsByKey_00100 + * @tc.number : ANS_FW_MT_RemoveNotificationsByKey_00100 + * @tc.name : RemoveNotificationsByKey_00100 * @tc.desc : Remove Notification by key. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitonsByKey_00100, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificationsByKey_00100, Function | MediumTest | Level1) { TestAnsSubscriber subscriber; NotificationSubscribeInfo info; @@ -726,7 +733,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitonsByKey_00100, Function | M EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetId(), 0); std::stringstream stream; - stream << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 0; + stream << KEY_SPLITER << USER_ID << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 0; std::string notificationKey = stream.str(); NotificationSorting sorting; EXPECT_EQ(eventParser.GetOnCanceledReq()[0]->GetKey(), notificationKey); @@ -740,11 +747,11 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitonsByKey_00100, Function | M /** * - * @tc.number : ANS_FW_MT_RemoveNotificaitonsByKey_00200 - * @tc.name : RemoveNotificaitonsByKey_00200 + * @tc.number : ANS_FW_MT_RemoveNotificationsByKey_00200 + * @tc.name : RemoveNotificationsByKey_00200 * @tc.desc : Remove Notification by a nonexistent key. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitonsByKey_00200, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificationsByKey_00200, Function | MediumTest | Level1) { TestAnsSubscriber subscriber; NotificationSubscribeInfo info; @@ -783,11 +790,11 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitonsByKey_00200, Function | M /** * - * @tc.number : ANS_FW_MT_RemoveNotificaitons_00100 - * @tc.name : RemoveNotificaitons_00100 + * @tc.number : ANS_FW_MT_RemoveNotifications_00100 + * @tc.name : RemoveNotifications_00100 * @tc.desc : Remove all Notifications. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitons_00100, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotifications_00100, Function | MediumTest | Level1) { TestAnsSubscriber subscriber; NotificationSubscribeInfo info; @@ -816,7 +823,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitons_00100, Function | Medium eventParser.Parse(events); EXPECT_TRUE(eventParser.GetWaitOnConsumed()); SleepForFC(); - EXPECT_EQ(NotificationHelper::RemoveNotifications(), ERR_OK); + EXPECT_EQ(NotificationHelper::RemoveNotifications(USER_ID), ERR_OK); std::vector> notifications; EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); EXPECT_EQ((int)notifications.size(), (int)0); @@ -833,11 +840,11 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitons_00100, Function | Medium /** * - * @tc.number : ANS_FW_MT_RemoveNotificaitons_00200 - * @tc.name : RemoveNotificaitons_00200 + * @tc.number : ANS_FW_MT_RemoveNotifications_00200 + * @tc.name : RemoveNotifications_00200 * @tc.desc : Remove Notifications when no Notification. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitons_00200, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotifications_00200, Function | MediumTest | Level1) { EventParser eventParser; TestAnsSubscriber subscriber; @@ -999,7 +1006,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelNotificationById_00100, Function | Med EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetId(), 1); std::stringstream stream; - stream << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 1; + stream << KEY_SPLITER << USER_ID << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 1; std::string notificationKey = stream.str(); NotificationSorting sorting; EXPECT_EQ(eventParser.GetOnCanceledReq()[0]->GetKey(), notificationKey); @@ -1094,7 +1101,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelAllNotifications_00100, Function | Med EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetId(), 0); std::stringstream stream0; - stream0 << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 0; + stream0 << KEY_SPLITER << USER_ID << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 0; std::string notificationKey0 = stream0.str(); NotificationSorting sorting0; EXPECT_EQ(eventParser.GetOnCanceledReq()[0]->GetKey(), notificationKey0); @@ -1106,7 +1113,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelAllNotifications_00100, Function | Med EXPECT_EQ(eventParser.GetOnConsumedReq()[1]->GetLabel().c_str(), NOTIFICATION_LABEL_1); EXPECT_EQ(eventParser.GetOnConsumedReq()[1]->GetId(), 1); std::stringstream stream1; - stream1 << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_1 << KEY_SPLITER << 1; + stream1 << KEY_SPLITER << USER_ID << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_1 << KEY_SPLITER << 1; std::string notificationKey1 = stream1.str(); NotificationSorting sorting1; EXPECT_EQ(eventParser.GetOnCanceledReq()[1]->GetKey(), notificationKey1); @@ -1787,7 +1794,7 @@ HWTEST_F(AnsFWModuleTest, DistributedNotification_Publish_00300, Function | Medi ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); DistributedKv::Entry outEntry; - ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), false); + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); AppExecFwk::MockSetDistributedNotificationEnabled(true); SleepForFC(); } @@ -1910,7 +1917,7 @@ HWTEST_F(AnsFWModuleTest, DistributedNotification_Remove_00200, Function | Mediu ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); - ASSERT_EQ(NotificationHelper::RemoveNotifications(), ERR_OK); + ASSERT_EQ(NotificationHelper::RemoveNotifications(USER_ID), ERR_OK); ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); ASSERT_EQ(entries.size(), std::size_t(0)); SleepForFC(); @@ -1961,7 +1968,7 @@ HWTEST_F(AnsFWModuleTest, DistributedNotification_Subscribe_00100, Function | Me ANS_LOGI("%{public}s", test_info_->name()); NotificationRequest request = CreateDistributedRequest(test_info_->name()); std::string jsonString; - NotificationJsonConverter::ConvertToJosnString(&request, jsonString); + NotificationJsonConverter::ConvertToJsonString(&request, jsonString); DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; @@ -1979,7 +1986,7 @@ HWTEST_F(AnsFWModuleTest, DistributedNotification_Subscribe_00100, Function | Me EventParser parser1; parser1.Parse(subscriber.GetEvents()); - auto notificationList = parser1.GetOnConsumedReq(); + auto notificationList = parser1.GetOnConsumedWithSortingMapReq(); EXPECT_NE(notificationList.size(), std::size_t(0)); std::shared_ptr outNotification; EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); @@ -1990,7 +1997,7 @@ HWTEST_F(AnsFWModuleTest, DistributedNotification_Subscribe_00100, Function | Me EventParser parser2; parser2.Parse(subscriber.GetEvents()); - notificationList = parser2.GetOnConsumedReq(); + notificationList = parser2.GetOnConsumedWithSortingMapReq(); EXPECT_NE(notificationList.size(), std::size_t(0)); EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); subscriber.ClearEvents(); @@ -2022,7 +2029,7 @@ HWTEST_F(AnsFWModuleTest, DistributedNotification_Subscribe_00200, Function | Me request.SetOwnerBundleName(APP_NAME); request.SetCreatorBundleName(APP_NAME); std::string jsonString; - NotificationJsonConverter::ConvertToJosnString(&request, jsonString); + NotificationJsonConverter::ConvertToJsonString(&request, jsonString); DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; @@ -2040,7 +2047,7 @@ HWTEST_F(AnsFWModuleTest, DistributedNotification_Subscribe_00200, Function | Me EventParser parser1; parser1.Parse(subscriber.GetEvents()); - auto notificationList = parser1.GetOnConsumedReq(); + auto notificationList = parser1.GetOnConsumedWithSortingMapReq(); EXPECT_NE(notificationList.size(), std::size_t(0)); std::shared_ptr outNotification; EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); @@ -2114,12 +2121,12 @@ HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00100, Function | MediumTest | Lev TestAnsSubscriber subscriber; EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); - EXPECT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + SleepForFC(); EventParser parser; parser.Parse(subscriber.GetEvents()); - auto notificationList = parser.GetOnConsumedReq(); + auto notificationList = parser.GetOnConsumedWithSortingMapReq(); std::shared_ptr outNotification; EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND); @@ -2145,12 +2152,12 @@ HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00200, Function | MediumTest | Lev TestAnsSubscriber subscriber; EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); - EXPECT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + SleepForFC(); EventParser parser; parser.Parse(subscriber.GetEvents()); - auto notificationList = parser.GetOnConsumedReq(); + auto notificationList = parser.GetOnConsumedWithSortingMapReq(); std::shared_ptr outNotification; EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND); @@ -2176,12 +2183,12 @@ HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00300, Function | MediumTest | Lev TestAnsSubscriber subscriber; EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); - EXPECT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + SleepForFC(); EventParser parser; parser.Parse(subscriber.GetEvents()); - auto notificationList = parser.GetOnConsumedReq(); + auto notificationList = parser.GetOnConsumedWithSortingMapReq(); std::shared_ptr outNotification; EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_IDLE_REMIND); @@ -2207,12 +2214,12 @@ HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00400, Function | MediumTest | Lev TestAnsSubscriber subscriber; EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); - EXPECT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + SleepForFC(); EventParser parser; parser.Parse(subscriber.GetEvents()); - auto notificationList = parser.GetOnConsumedReq(); + auto notificationList = parser.GetOnConsumedWithSortingMapReq(); std::shared_ptr outNotification; EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND); @@ -2237,25 +2244,27 @@ HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00500, Function | MediumTest | Lev request.SetCreatorBundleName(APP_NAME); request.SetDevicesSupportDisplay(devices); std::string jsonString; - NotificationJsonConverter::ConvertToJosnString(&request, jsonString); + NotificationJsonConverter::ConvertToJsonString(&request, jsonString); PublishCommonEventScreenStatus(true); - TestAnsSubscriber subscriber; - EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; - DistributedKv::StoreId storeId = {.storeId = KVSTORE_SCREEN_STATUS_STORE_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; std::shared_ptr pointer = DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + DistributedKv::Key key(GenerateDistributedKey(request, REMOTE_DEVICE_ID)); DistributedKv::Value value(jsonString); pointer->InsertDataToDoCallback(key, value); SleepForFC(); + SleepForFC(); EventParser parser; parser.Parse(subscriber.GetEvents()); - auto notificationList = parser.GetOnConsumedReq(); + auto notificationList = parser.GetOnConsumedWithSortingMapReq(); std::shared_ptr outNotification; EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND); @@ -2280,17 +2289,18 @@ HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00600, Function | MediumTest | Lev request.SetCreatorBundleName(APP_NAME); request.SetDevicesSupportDisplay(devices); std::string jsonString; - NotificationJsonConverter::ConvertToJosnString(&request, jsonString); + NotificationJsonConverter::ConvertToJsonString(&request, jsonString); PublishCommonEventScreenStatus(false); - TestAnsSubscriber subscriber; - EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; - DistributedKv::StoreId storeId = {.storeId = KVSTORE_SCREEN_STATUS_STORE_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; std::shared_ptr pointer = DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + DistributedKv::Key key(GenerateDistributedKey(request, REMOTE_DEVICE_ID)); DistributedKv::Value value(jsonString); pointer->InsertDataToDoCallback(key, value); @@ -2298,7 +2308,7 @@ HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00600, Function | MediumTest | Lev EventParser parser; parser.Parse(subscriber.GetEvents()); - auto notificationList = parser.GetOnConsumedReq(); + auto notificationList = parser.GetOnConsumedWithSortingMapReq(); std::shared_ptr outNotification; EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND); @@ -2309,12 +2319,16 @@ HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00600, Function | MediumTest | Lev } #endif -HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07100, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PublishContinuousTask_07100, Function | MediumTest | Level1) { IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); TestAnsSubscriber subscriber; EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); NotificationRequest req(0); + req.SetContent(content); req.SetLabel(NOTIFICATION_LABEL_0); EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); SleepForFC(); @@ -2344,12 +2358,16 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07100, Function IPCSkeleton::SetCallingUid(1); } -HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07200, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PublishContinuousTask_07200, Function | MediumTest | Level1) { IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); TestAnsSubscriber subscriber; EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); NotificationRequest req(0); + req.SetContent(content); req.SetLabel(NOTIFICATION_LABEL_0); EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); SleepForFC(); @@ -2381,12 +2399,16 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07200, Function IPCSkeleton::SetCallingUid(1); } -HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07300, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PublishContinuousTask_07300, Function | MediumTest | Level1) { IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); TestAnsSubscriber subscriber; EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); NotificationRequest req(0); + req.SetContent(content); req.SetLabel(NOTIFICATION_LABEL_0); EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); SleepForFC(); @@ -2417,14 +2439,17 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07300, Function IPCSkeleton::SetCallingUid(1); } -HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07400, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PublishContinuousTask_07400, Function | MediumTest | Level1) { + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); NotificationRequest req(0); + req.SetContent(content); req.SetLabel(NOTIFICATION_LABEL_0); EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), (int)ERR_ANS_NOT_SYSTEM_SERVICE); } -HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07500, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PublishContinuousTask_07500, Function | MediumTest | Level1) { TestAnsSubscriber subscriber; NotificationSubscribeInfo info; @@ -2460,13 +2485,16 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07500, Function SleepForFC(); } -HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07600, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PublishContinuousTask_07600, Function | MediumTest | Level1) { IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); TestAnsSubscriber subscriber; EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); NotificationRequest req(0); + req.SetContent(content); req.SetLabel(NOTIFICATION_LABEL_0); EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); @@ -2487,12 +2515,16 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07600, Function IPCSkeleton::SetCallingUid(1); } -HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07700, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PublishContinuousTask_07700, Function | MediumTest | Level1) { IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); TestAnsSubscriber subscriber; EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); NotificationRequest req(0); + req.SetContent(content); req.SetLabel(NOTIFICATION_LABEL_0); EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); SleepForFC(); @@ -2525,12 +2557,16 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07700, Function IPCSkeleton::SetCallingUid(1); } -HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07800, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PublishContinuousTask_07800, Function | MediumTest | Level1) { IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); TestAnsSubscriber subscriber; EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); NotificationRequest req(0); + req.SetContent(content); req.SetLabel(NOTIFICATION_LABEL_0); EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); SleepForFC(); diff --git a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp index 89aa95b853d0cd73f64fef98072b54390b4f12dc..505128d98771c8962429227e999565690e2d8897 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -20,6 +20,7 @@ #include "advanced_notification_service.h" #include "datetime_ex.h" #include "if_system_ability_manager.h" +#include "int_wrapper.h" #include "iservice_registry.h" #include "notification_helper.h" #include "notification_json_convert.h" @@ -29,7 +30,6 @@ #include "want_agent_info.h" #include "want_agent_helper.h" #include "want_params.h" -#include "ohos/aafwk/base/int_wrapper.h" using namespace testing::ext; namespace OHOS { @@ -40,7 +40,7 @@ bool OnConsumedReceived = false; bool OnCanceledReceived = false; bool OnWantReceived = false; const int32_t SLEEP_TIME = 5; -const int32_t ACTIVE_NUMS = 2; +const uint64_t ACTIVE_NUMS = 2; const int32_t CASE_ONE = 1; const int32_t CASE_TWO = 2; const int32_t CASE_THREE = 3; @@ -216,25 +216,23 @@ private: EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); std::vector> actionButtons = notificationRequest.GetActionButtons(); for (auto actionButton : actionButtons) { - std::vector> userInputs = actionButton->GetUserInputs(); - for (auto userInput : userInputs) { - EXPECT_EQ(NotificationConstant::FREE_FORM_INPUT, userInput->GetInputsSource(g_want)); - EXPECT_EQ(nullptr, userInput->GetInputsFromWant(g_want)); - std::map> map = userInput->GetMimeInputsFromWant(g_want, ""); - EXPECT_EQ(unsigned(0), map.size()); - EXPECT_EQ("inputKey", userInput->GetInputKey()); - EXPECT_NE(nullptr, userInput->GetAdditionalData()); - EXPECT_EQ(NotificationConstant::InputEditType::EDIT_DISABLED, userInput->GetEditType()); - for (auto option : userInput->GetOptions()) { - EXPECT_EQ("", option); - } - for (auto type : userInput->GetPermitMimeTypes()) { - EXPECT_EQ("mimeType", type); - } - EXPECT_EQ(false, userInput->IsMimeTypeOnly()); - EXPECT_EQ("tag", userInput->GetTag()); - EXPECT_EQ(false, userInput->IsPermitFreeFormInput()); + std::shared_ptr userInput = actionButton->GetUserInput(); + EXPECT_EQ(NotificationConstant::FREE_FORM_INPUT, userInput->GetInputsSource(g_want)); + EXPECT_EQ(nullptr, userInput->GetInputsFromWant(g_want)); + std::map> map = userInput->GetMimeInputsFromWant(g_want, ""); + EXPECT_EQ(unsigned(0), map.size()); + EXPECT_EQ("inputKey", userInput->GetInputKey()); + EXPECT_NE(nullptr, userInput->GetAdditionalData()); + EXPECT_EQ(NotificationConstant::InputEditType::EDIT_DISABLED, userInput->GetEditType()); + for (auto option : userInput->GetOptions()) { + EXPECT_EQ("", option); + } + for (auto type : userInput->GetPermitMimeTypes()) { + EXPECT_EQ("mimeType", type); } + EXPECT_EQ(false, userInput->IsMimeTypeOnly()); + EXPECT_EQ("tag", userInput->GetTag()); + EXPECT_EQ(false, userInput->IsPermitFreeFormInput()); } } @@ -503,34 +501,34 @@ void AnsInterfaceModulePublishTest::WaitOnUnsubscribeResult() void AnsInterfaceModulePublishTest::CheckJsonConverter(const NotificationRequest *request) { nlohmann::json jsonObject; - auto ret0 = NotificationJsonConverter::ConvertToJosn(request, jsonObject); + auto ret0 = NotificationJsonConverter::ConvertToJson(request, jsonObject); EXPECT_EQ(ret0, true); - GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJosn object dump ==========>" << jsonObject.dump(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJson object dump ==========>" << jsonObject.dump(); std::string jsonString; - auto ret1 = NotificationJsonConverter::ConvertToJosnString(request, jsonString); - GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJosnString ret1 ==========>" + auto ret1 = NotificationJsonConverter::ConvertToJsonString(request, jsonString); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJsonString ret1 ==========>" << (ret1 ? "true" : "false"); EXPECT_EQ(ret1, true); - GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJosnString string ==========>" << jsonString; + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJsonString string ==========>" << jsonString; GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::convert Json sleep start ==========>"; sleep(SLEEP_TIME); GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::convert Json sleep end ==========>"; - auto pRequest1 = NotificationJsonConverter::ConvertFromJosn(jsonObject); + auto pRequest1 = NotificationJsonConverter::ConvertFromJson(jsonObject); EXPECT_NE(pRequest1, nullptr); - GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertFromJosn jsonObject dump request ==========>" + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertFromJson jsonObject dump request ==========>" << pRequest1->Dump(); - auto pRequest2 = NotificationJsonConverter::ConvertFromJosnString(jsonString); + auto pRequest2 = NotificationJsonConverter::ConvertFromJsonString(jsonString); EXPECT_NE(pRequest2, nullptr); - GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertFromJosnString jsonString dump request ==========>" + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertFromJsonString jsonString dump request ==========>" << pRequest2->Dump(); nlohmann::json jsonObject2; - auto ret2 = NotificationJsonConverter::ConvertToJosn(pRequest1, jsonObject2); - GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJosn ret2 ==========>" << (ret2 ? "true" : "false"); + auto ret2 = NotificationJsonConverter::ConvertToJson(pRequest1, jsonObject2); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJson ret2 ==========>" << (ret2 ? "true" : "false"); EXPECT_EQ(ret2, true); GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::FromJson -> ToJson object dump ==========>" << jsonObject2.dump(); @@ -1153,7 +1151,7 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_GetActiveNotifications_ EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::CancelAllNotifications()); sleep(SLEEP_TIME); EXPECT_EQ(OnCanceledReceived, true); - int countBefor = 0; + uint64_t countBefor = 0; EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countBefor)); EXPECT_EQ(0, countBefor); std::string label1 = "Label1"; @@ -1174,7 +1172,7 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_GetActiveNotifications_ g_consumed_mtx.lock(); EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); WaitOnConsumed(); - int countAfter = 0; + uint64_t countAfter = 0; EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countAfter)); EXPECT_EQ(ACTIVE_NUMS, countAfter); std::vector> requests; @@ -1345,9 +1343,7 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_08000, Function std::shared_ptr dummyIcon; auto ab1 = NotificationActionButton::Create(dummyIcon, "ab1_title", wAgent2); - auto spUserInput3 = NotificationUserInput::Create("uikey3"); auto spUserInput2 = NotificationUserInput::Create("uikey2"); - ab1->AddNotificationUserInput(spUserInput3); ab1->AddNotificationUserInput(spUserInput2); auto spOnlyUserInput1 = NotificationUserInput::Create("uionlykey1"); spOnlyUserInput1->SetPermitFreeFormInput(false); @@ -1453,5 +1449,72 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_06000, Function EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); WaitOnUnsubscribeResult(); } + +/** + * @tc.number : ANS_Interface_MT_Slot_Enalbe_00100 + * @tc.name : Slot_Enalbe_00100 + * @tc.desc : Add notification slot(type is CONTENT_INFORMATION), + * make a subscriber and publish a flags notification. + * @tc.expected : Add notification slot success, make a subscriber and publish default flags notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Slot_Enalbe_00100, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::CONTENT_INFORMATION); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + + std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); + std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::CONTENT_INFORMATION); + req.SetNotificationId(CASE_SIXTEEN); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + + bool enable = false; + NotificationBundleOption bo("bundleName", 1); + EXPECT_EQ(0, NotificationHelper::SetEnabledForBundleSlot(bo, NotificationConstant::CONTENT_INFORMATION, enable)); + EXPECT_EQ(0, NotificationHelper::GetEnabledForBundleSlot(bo, NotificationConstant::CONTENT_INFORMATION, enable)); + EXPECT_EQ(enable, false); + EXPECT_EQ(ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED, NotificationHelper::PublishNotification(req)); +} + +/** + * @tc.number : ANS_Interface_MT_Slot_Enalbe_00200 + * @tc.name : Slot_Enalbe_00200 + * @tc.desc : Add notification slot(type is SERVICE_REMINDER), make a subscriber and publish a flags notification. + * @tc.expected : Add notification slot success, make a subscriber and publish default flags notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Slot_Enalbe_00200, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SERVICE_REMINDER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + + std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); + std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::SERVICE_REMINDER); + req.SetNotificationId(CASE_SIXTEEN); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + + bool enable = false; + NotificationBundleOption bo("bundleName", 1); + EXPECT_EQ(0, NotificationHelper::SetEnabledForBundleSlot(bo, NotificationConstant::SERVICE_REMINDER, enable)); + EXPECT_EQ(0, NotificationHelper::GetEnabledForBundleSlot(bo, NotificationConstant::SERVICE_REMINDER, enable)); + EXPECT_EQ(enable, false); + EXPECT_EQ((uint32_t)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED, NotificationHelper::PublishNotification(req)); + + enable = true; + EXPECT_EQ(0, NotificationHelper::SetEnabledForBundleSlot(bo, NotificationConstant::SERVICE_REMINDER, enable)); + EXPECT_EQ(0, NotificationHelper::GetEnabledForBundleSlot(bo, NotificationConstant::SERVICE_REMINDER, enable)); + EXPECT_EQ(enable, true); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp index 31675f210c0dd47e995022d567ba435ab176a3da..07139983f46b45fd3a35e0b7677ae5bead9d56dd 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp @@ -483,5 +483,81 @@ HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlotGroup_0030 EXPECT_EQ((int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST, NotificationHelper::GetNotificationSlotGroup("id", spSlotGroup)); } + +/** + * @tc.number : ANS_Interface_MT_SetEnabledForBundleSlot_00100 + * @tc.name : SetEnabledForBundleSlot_00100 + * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), get slot default enable, + * set and get slot enable. + * @tc.expected : Add notification slot success, slot default enalbe is true, get is the same as setting. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_SetEnabledForBundleSlot_00100, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); + slot.SetEnableLight(true); + slot.SetDescription("description"); + slot.SetLedLightColor(0); + slot.SetLevel(NotificationSlot::NotificationLevel::LEVEL_LOW); + slot.SetSlotGroup("group"); + slot.SetSound(Uri(".")); + std::vector style; + style.push_back(0); + slot.SetVibrationStyle(style); + slot.EnableBypassDnd(true); + slot.EnableBadge(true); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + sptr spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::SOCIAL_COMMUNICATION, spSlot)); + EXPECT_NE(spSlot, nullptr); + EXPECT_EQ(spSlot->GetEnable(), true); + + bool enable = false; + NotificationBundleOption bo("bundleName", CALLING_UID); + EXPECT_EQ(0, NotificationHelper::SetEnabledForBundleSlot(bo, NotificationConstant::SOCIAL_COMMUNICATION, enable)); + EXPECT_EQ(0, NotificationHelper::GetEnabledForBundleSlot(bo, NotificationConstant::SOCIAL_COMMUNICATION, enable)); + EXPECT_EQ(enable, false); +} + +/** + * @tc.number : ANS_Interface_MT_SetEnabledForBundleSlot_00200 + * @tc.name : SetEnabledForBundleSlot_00200 + * @tc.desc : Add slot when there is no type slot, add it. (SOCIAL_COMMUNICATION) + * @tc.expected : Set success, and get success. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_SetEnabledForBundleSlot_00200, Function | MediumTest | Level1) +{ + bool enable = true; + NotificationBundleOption bo("bundleName", CALLING_UID); + EXPECT_EQ(0, NotificationHelper::SetEnabledForBundleSlot(bo, NotificationConstant::SOCIAL_COMMUNICATION, enable)); + enable = false; + EXPECT_EQ(0, NotificationHelper::GetEnabledForBundleSlot(bo, NotificationConstant::SOCIAL_COMMUNICATION, enable)); + EXPECT_EQ(enable, true); + + sptr spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::SOCIAL_COMMUNICATION, spSlot)); + EXPECT_NE(spSlot, nullptr); + EXPECT_EQ(spSlot->GetEnable(), true); +} + +/** + * @tc.number : ANS_Interface_MT_SetEnabledForBundleSlot_00300 + * @tc.name : SetEnabledForBundleSlot_00300 + * @tc.desc : Add slot when there is no type slot, add it. (SERVICE_REMINDER) + * @tc.expected : Set false, and get false. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_SetEnabledForBundleSlot_00300, Function | MediumTest | Level1) +{ + bool enable = false; + NotificationBundleOption bo("bundleName", CALLING_UID); + EXPECT_EQ(0, NotificationHelper::SetEnabledForBundleSlot(bo, NotificationConstant::SERVICE_REMINDER, enable)); + enable = true; + EXPECT_EQ(0, NotificationHelper::GetEnabledForBundleSlot(bo, NotificationConstant::SERVICE_REMINDER, enable)); + EXPECT_EQ(enable, false); + + sptr spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::SERVICE_REMINDER, spSlot)); + EXPECT_NE(spSlot, nullptr); + EXPECT_EQ(spSlot->GetEnable(), false); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/config.json b/frameworks/ans/test/moduletest/config.json index 7d3bb1663873510fc00c1203273ad743dfbb2f43..46e2a9f391b523655bdfbb7b2a6d525dcd79dff1 100644 --- a/frameworks/ans/test/moduletest/config.json +++ b/frameworks/ans/test/moduletest/config.json @@ -13,6 +13,18 @@ }, "deviceConfig": {}, "module": { + "reqPermissions": [ + { + "name": "ohos.permission.PUBLISH_AGENT_REMINDER", + "reason": "SYSTEM_GRANT", + "usedScene": { + "ability": [ + ".FormAbility" + ], + "when": "inuse" + } + } + ], "package": "com.example.myapplication", "name": ".MyApplication", "deviceType": [ @@ -58,4 +70,3 @@ ] } } - \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h index ce1ef007f3d3239be5a04cfe8b1770fc8b760e9c..c9ce5c3a5efd8f12a282011cc3a50f86254ad607 100644 --- a/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h +++ b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -22,23 +22,23 @@ #include "application_info.h" #include "bundle_mgr_host.h" #include "bundle_mgr_interface.h" -#include "ohos/aafwk/content/want.h" #include "iremote_proxy.h" #include "iremote_stub.h" +#include "want.h" namespace OHOS { namespace AppExecFwk { class MockBundleMgrService : public BundleMgrHost { public: MockBundleMgrService() - { - } + {} ~MockBundleMgrService() {} /** * @brief Obtains the ApplicationInfo based on a given bundle name. + * * @param appName Indicates the application bundle name to be queried. * @param flag Indicates the flag used to specify information contained * in the ApplicationInfo object that will be returned. @@ -51,8 +51,10 @@ public: { return true; } + /** * @brief Obtains information about all installed applications of a specified user. + * * @param flag Indicates the flag used to specify information contained * in the ApplicationInfo objects that will be returned. * @param userId Indicates the user ID. @@ -64,8 +66,10 @@ public: { return true; } + /** * @brief Obtains the BundleInfo based on a given bundle name. + * * @param bundleName Indicates the application bundle name to be queried. * @param flag Indicates the information contained in the BundleInfo object to be returned. * @param bundleInfo Indicates the obtained BundleInfo object. @@ -77,8 +81,10 @@ public: { return true; } + /** * @brief Obtains BundleInfo of all bundles available in the system. + * * @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned. * @param bundleInfos Indicates all of the obtained BundleInfo objects. * @param userId Indicates the user ID. @@ -88,9 +94,11 @@ public: const BundleFlag flag, std::vector &bundleInfos, int32_t userId) override { return true; - }; + } + /** * @brief Obtains the application UID based on the given bundle name and user ID. + * * @param bundleName Indicates the bundle name of the application. * @param userId Indicates the user ID. * @return Returns the uid if successfully obtained; returns -1 otherwise. @@ -99,8 +107,10 @@ public: { return 0; } + /** * @brief Obtains the application ID based on the given bundle name and user ID. + * * @param bundleName Indicates the bundle name of the application. * @param userId Indicates the user ID. * @return Returns the application ID if successfully obtained; returns empty string otherwise. @@ -109,8 +119,10 @@ public: { return "bundlename"; } + /** * @brief Obtains the bundle name of a specified application based on the given UID. + * * @param uid Indicates the uid. * @param bundleName Indicates the obtained bundle name. * @return Returns true if the bundle name is successfully obtained; returns false otherwise. @@ -120,8 +132,10 @@ public: bundleName = "hello"; return true; } + /** * @brief Obtains all bundle names of a specified application based on the given application UID. + * * @param uid Indicates the uid. * @param bundleNames Indicates the obtained bundle names. * @return Returns true if the bundle names is successfully obtained; returns false otherwise. @@ -131,7 +145,9 @@ public: return true; } - /* @brief Obtains the formal name associated with the given UID. + /** + * @brief Obtains the formal name associated with the given UID. + * * @param uid Indicates the uid. * @param name Indicates the obtained formal name. * @return Returns true if the formal name is successfully obtained; returns false otherwise. @@ -140,8 +156,10 @@ public: { return true; } + /** * @brief Obtains an array of all group IDs associated with a specified bundle. + * * @param bundleName Indicates the bundle name. * @param gids Indicates the group IDs associated with the specified bundle. * @return Returns true if the gids is successfully obtained; returns false otherwise. @@ -150,8 +168,10 @@ public: { return true; } + /** * @brief Obtains the type of a specified application based on the given bundle name. + * * @param bundleName Indicates the bundle name. * @return Returns "system" if the bundle is a system application; returns "third-party" otherwise. */ @@ -159,8 +179,10 @@ public: { return ""; } + /** * @brief Check whether the app is system app by it's UID. + * * @param uid Indicates the uid. * @return Returns true if the bundle is a system application; returns false otherwise. */ @@ -168,6 +190,7 @@ public: /** * @brief Obtains the BundleInfo of application bundles based on the specified metaData. + * * @param metaData Indicates the metadata to get in the bundle. * @param bundleInfos Indicates all of the obtained BundleInfo objects. * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. @@ -176,9 +199,11 @@ public: { return true; } + /** * @brief Query the AbilityInfo by the given Want. - * @param want Indicates the infomation of the ability. + * + * @param want Indicates the information of the ability. * @param abilityInfo Indicates the obtained AbilityInfo object. * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. */ @@ -186,8 +211,10 @@ public: { return true; } + /** * @brief Query the AbilityInfo by ability.uri in config.json. + * * @param abilityUri Indicates the uri of the ability. * @param abilityInfo Indicates the obtained AbilityInfo object. * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. @@ -196,27 +223,21 @@ public: { return true; } + /** * @brief Obtains the BundleInfo of all keep-alive applications in the system. + * * @param bundleInfos Indicates all of the obtained BundleInfo objects. * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. */ virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override { return true; - }; - /** - * @brief Obtains the label of a specified ability. - * @param bundleName Indicates the bundle name. - * @param className Indicates the ability class name. - * @return Returns the label of the ability if exist; returns empty string otherwise. - */ - virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override - { - return ""; } + /** * @brief Obtains information about an application bundle contained in a ohos Ability Package (HAP). + * * @param hapFilePath Indicates the absolute file path of the HAP. * @param flag Indicates the information contained in the BundleInfo object to be returned. * @param bundleInfo Indicates the obtained BundleInfo object. @@ -227,8 +248,10 @@ public: { return true; } + /** * @brief Obtain the HAP module info of a specific ability. + * * @param abilityInfo Indicates the ability. * @param hapModuleInfo Indicates the obtained HapModuleInfo object. * @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise. @@ -237,8 +260,10 @@ public: { return true; } + /** * @brief Obtains the Want for starting the main ability of an application based on the given bundle name. + * * @param bundleName Indicates the bundle name. * @param want Indicates the obtained launch Want object. * @return Returns true if the launch Want object is successfully obtained; returns false otherwise. @@ -247,23 +272,10 @@ public: { return true; } - /** - * @brief Confirms with the permission management module to check whether a request prompt is required for granting - * a certain permission. - * @param bundleName Indicates the name of the bundle to check. - * @param permission Indicates the permission to check. - * @param userId Indicates the user id. - * @return Returns true if the current application does not have the permission and the user does not turn off - * further requests; returns false if the current application already has the permission, the permission is rejected - * by the system, or the permission is denied by the user and the user has turned off further requests. - */ - virtual bool CanRequestPermission( - const std::string &bundleName, const std::string &permissionName, const int userId) override - { - return true; - } + /** * @brief Checks whether the publickeys of two bundles are the same. + * * @param firstBundleName Indicates the first bundle name. * @param secondBundleName Indicates the second bundle name. * @return Returns SIGNATURE_UNKNOWN_BUNDLE if at least one of the given bundles is not found; @@ -274,15 +286,10 @@ public: { return 0; } - /** - * @brief Checks whether a specified bundle has been granted a specific permission. - * @param bundleName Indicates the name of the bundle to check. - * @param permission Indicates the permission to check. - * @return Returns 0 if the bundle has the permission; returns -1 otherwise. - */ - virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override; + /** * @brief Obtains detailed information about a specified permission. + * * @param permissionName Indicates the name of the ohos permission. * @param permissionDef Indicates the object containing detailed information about the given ohos permission. * @return Returns true if the PermissionDef object is successfully obtained; returns false otherwise. @@ -291,69 +298,10 @@ public: { return true; } - /** - * @brief Obtains all known permission groups in the system. - * @param permissionDefs Indicates the list of objects containing the permission group information. - * @return Returns true if the PermissionDef objects is successfully obtained; returns false otherwise. - */ - virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override - { - return true; - } - /** - * @brief Obtains all known permission groups in the system. - * @param permissions Indicates the permission array. - * @param appNames Indicates the list of application names that have the specified permissions. - * @return Returns true if the application names is successfully obtained; returns false otherwise. - */ - virtual bool GetAppsGrantedPermissions( - const std::vector &permissions, std::vector &appNames) override - { - return true; - } - /** - * @brief Requests a certain permission from user. - * @param bundleName Indicates the name of the bundle to request permission. - * @param permission Indicates the permission to request permission. - * @param userId Indicates the user id. - * @return Returns true if the permission request successfully; returns false otherwise. - */ - virtual bool RequestPermissionFromUser( - const std::string &bundleName, const std::string &permission, const int userId) override - { - return true; - } - /** - * @brief Registers a callback for listening for permission changes of all UIDs. - * @param callback Indicates the callback method to register. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool RegisterAllPermissionsChanged(const sptr &callback) override - { - return true; - } - /** - * @brief Registers a callback for listening for permission changes of specified UIDs. - * @param uids Indicates the list of UIDs whose permission changes will be monitored. - * @param callback Indicates the callback method to register. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool RegisterPermissionsChanged( - const std::vector &uids, const sptr &callback) override - { - return true; - } - /** - * @brief Unregisters a specified callback for listening for permission changes. - * @param callback Indicates the callback method to register. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool UnregisterPermissionsChanged(const sptr &callback) override - { - return true; - } + /** * @brief Obtains the FormInfo objects provided by all applications on the device. + * * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the * device. * @return Returns true if this function is successfully called; returns false otherwise. @@ -362,8 +310,10 @@ public: { return true; } + /** * @brief Obtains the FormInfo objects provided by a specified application on the device. + * * @param bundleName Indicates the bundle name of the application. * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the * device. @@ -376,6 +326,7 @@ public: /** * @brief Obtains the FormInfo objects provided by a specified. + * * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the * device. * @param moduleName Indicates the module name of the application. @@ -387,8 +338,10 @@ public: { return true; } + /** * @brief Checks whether the system has a specified capability. + * * @param capName Indicates the name of the system feature to check. * @return Returns true if the given feature specified by name is available in the system; returns false otherwise. */ @@ -396,8 +349,10 @@ public: { return true; } + /** * @brief Obtains the capabilities that are available in the system. + * * @param systemCaps Indicates the list of capabilities available in the system. * @return Returns true if capabilities in the system are successfully obtained; returns false otherwise. */ @@ -405,16 +360,20 @@ public: { return true; } + /** * @brief Checks whether the current device has been started in safe mode. + * * @return Returns true if the device is in safe mode; returns false otherwise. */ virtual bool IsSafeMode() override { return true; } + /** * @brief Clears application running data of a specified application. + * * @param bundleName Indicates the bundle name of the application whose data is to be cleared. * @return Returns true if the data cleared successfully; returns false otherwise. */ @@ -422,8 +381,10 @@ public: { return true; } + /** * @brief Register the specific bundle status callback. + * * @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result. * @return Returns true if this function is successfully called; returns false otherwise. */ @@ -431,8 +392,10 @@ public: { return true; } + /** * @brief Clear the specific bundle status callback. + * * @param bundleStatusCallback Indicates the callback to be cleared. * @return Returns true if this function is successfully called; returns false otherwise. */ @@ -440,20 +403,24 @@ public: { return true; } + /** * @brief Unregister all the callbacks of status changed. + * * @return Returns true if this function is successfully called; returns false otherwise. */ virtual bool UnregisterBundleStatusCallback() override { return true; } + /** - * @brief Dump the bundle informations with specifc flags. + * @brief Dump the bundle information with specific flags. + * * @param flag Indicates the information contained in the dump result. * @param bundleName Indicates the bundle name if needed. * @param userId Indicates the user ID. - * @param result Indicates the dump infomation result. + * @param result Indicates the dump information result. * @return Returns true if the dump result is successfully obtained; returns false otherwise. */ virtual bool DumpInfos( @@ -461,8 +428,10 @@ public: { return true; } + /** * @brief Checks whether a specified application is enabled. + * * @param bundleName Indicates the bundle name of the application. * @return Returns true if the application is enabled; returns false otherwise. */ @@ -470,8 +439,10 @@ public: { return true; } + /** * @brief Sets whether to enable a specified ability. + * * @param abilityInfo Indicates information about the ability to check. * @return Returns true if the ability is enabled; returns false otherwise. */ @@ -479,26 +450,20 @@ public: { return true; } - /** - * @brief Obtains the icon of a specified ability. - * @param bundleName Indicates the bundle name. - * @param className Indicates the ability class name. - * @return Returns the icon resource string of the ability if exist; returns empty string otherwise. - */ - virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override - { - return "abilityicon"; - } + /** * @brief Obtains the interface used to install and uninstall bundles. + * * @return Returns a pointer to IBundleInstaller class if exist; returns nullptr otherwise. */ virtual sptr GetBundleInstaller() override { return nullptr; } + /** * @brief Obtains the interface used to create or delete user. + * * @return Returns a pointer to IBundleUserMgr class if exist; returns nullptr otherwise. */ virtual sptr GetBundleUserMgr() override @@ -506,8 +471,19 @@ public: return nullptr; } + /** + * @brief Mock to set whether it is system application. + * + * @param isSystemApp Indicates the system application flag. + */ void MockSetIsSystemApp(bool isSystemApp); + /** + * @brief Get the bundle name by uid. + * + * @param uid Indicates the uid. + * @return Indicates the bundle name. + */ std::string GetBundleNameByUid(pid_t uid) { return "bundle"; diff --git a/frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h b/frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h index 7881f108a8231f3a90fef2faa6ca2266f94e4b09..4d825c97cd9ffecffc495b81f4cc548c338def19 100644 --- a/frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h +++ b/frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h @@ -24,38 +24,111 @@ public: IPCSkeleton() = default; ~IPCSkeleton() = default; - // default max is 4, only if you need a customize value + /** + * @brief Set the max number of work thread. + * Default max is 4, only if you need a customize value. + * + * @param maxThreadNum Indicates the max number of work thread + * @return Indicates the result. + */ static bool SetMaxWorkThreadNum(int maxThreadNum); - // join current thread into work loop. + /** + * @brief Join current thread into work loop. + */ static void JoinWorkThread(); - // remove current thread from work loop. + /** + * @brief Remove current thread from work loop. + */ static void StopWorkThread(); + /** + * @brief Get calling pid. + * + * @return Indicates the calling pid. + */ static int GetCallingPid(); + /** + * @brief Get calling uid. + * + * @return Indicates the calling uid. + */ static int GetCallingUid(); + /** + * @brief Get the ID of local device. + * + * @return Indicates the ID of local device. + */ static std::string GetLocalDeviceID(); + /** + * @brief Get the ID of calling device. + * + * @return Indicates the ID of calling device. + */ static std::string GetCallingDeviceID(); + /** + * @brief Whether it is locally calling. + * + * @return Return ture for calling from local, otherwise false. + */ static bool IsLocalCalling(); + /** + * @brief Get the instance. + * + * @return Indicates the instance. + */ static IPCSkeleton &GetInstance(); + /** + * @brief Get the object of context. + * + * @return Indicates the context cobject. + */ static sptr GetContextObject(); + /** + * @brief Set the object of context. + * + * @param object Indicates the context cobject. + * @return Indicates the result. + */ static bool SetContextObject(sptr &object); + /** + * @brief Flush the commands. + * + * @param object Indicates the object. + * @return Indicates the result. + */ static int FlushCommands(IRemoteObject *object); + /** + * @brief Reset calling identity. + * + * @return Indicates the result. + */ static std::string ResetCallingIdentity(); + /** + * @brief Set calling identity. + * + * @param identity Indicates the identity. + * @return Indicates the result. + */ static bool SetCallingIdentity(std::string &identity); + /** + * @brief Set calling uid. + * + * @param uid Indicates the uid. + */ static void SetCallingUid(int uid); }; -} // namespace OHOS -#endif // OHOS_IPC_IPC_SKELETON_H +} // namespace OHOS +#endif // OHOS_IPC_IPC_SKELETON_H diff --git a/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h b/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h index 771745702ccd238b8a6b50bcd89e639dfeaaf006..12645a74ccf17abaaaeb4424563c8d3bcab68720 100644 --- a/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h +++ b/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -32,85 +32,332 @@ namespace OHOS { namespace DistributedKv { class AnsTestSingleKvStore : public SingleKvStore { public: + /** + * @brief Get all entries in this store which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntries(const Key &prefixKey, std::vector &entries) const override; + /** + * @brief Get all entries in this store by query. + * + * @param query Indicates the query string. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntriesWithQuery(const std::string &query, std::vector &entries) const override; + /** + * @brief Get all entries in this store by query. + * + * @param query Indicates the query object. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntriesWithQuery(const DataQuery &query, std::vector &entries) const override; + /** + * @brief Get ResultSet in this store which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ virtual Status GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const override; + /** + * @brief Get ResultSet in this store by Query. + * + * @param query Indicates the query string. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ virtual Status GetResultSetWithQuery(const std::string &query, std::shared_ptr &resultSet) const override; + /** + * @brief Get ResultSet in this store by Query. + * + * @param query Indicates the query object. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ virtual Status GetResultSetWithQuery(const DataQuery &query, std::shared_ptr &resultSet) const override; + /** + * @brief Close the ResultSet returned by GetResultSet. + * + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status CloseResultSet(std::shared_ptr &resultSet) override; + /** + * @brief Get the number of result by query. + * + * @param query Indicates the query string. + * @param result Indicates the result. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status GetCountWithQuery(const std::string &query, int &result) const override; + /** + * @brief Get the number of result by query. + * + * @param query Indicates the query object. + * @param result Indicates the result will be returned in this parameter. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status GetCountWithQuery(const DataQuery &query, int &result) const override; + /** + * @brief Sync store with other devices. This is an asynchronous method, + * sync will fail if there is a syncing operation in progress. + * + * @param deviceIds Indicates the device list to sync. + * @param mode Indicates the sync mode, can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. + * PUSH_PULL will firstly push all not-local store to listed devices, then pull these stores back. + * @param allowedDelayMs Indicates the allowed delay milli-second to sync. default value is 0 for compatibility. + * @return Indicates the status of this Sync operation. + */ virtual Status Sync( const std::vector &deviceIds, SyncMode mode, uint32_t allowedDelayMs = 0) override; + /** + * @brief Remove the device data synced from remote. + * + * @param device Indicates the device id. + * @return Indicates the status of this remove operation. + */ virtual Status RemoveDeviceData(const std::string &device) override; + /** + * @brief Get id of this AppKvStore. + * + * @return Indicates the id of store. + */ virtual StoreId GetStoreId() const override; + /** + * @brief Delete an entry by its key. + * + * @param key Indicates the key of the entry to be deleted. + * @return Indicates the status of this delete operation. + */ virtual Status Delete(const Key &key) override; + /** + * @brief Write a pair of key and value to this store. + * + * @param key Indicates the key of this entry. Should be less than 256 bytes. key will be trimmed before store. + * @param value Indicates the value of this entry. Should be less than (1024 * 1024) bytes. + * @return Indicates the status of this put operation. + */ virtual Status Put(const Key &key, const Value &value) override; + /** + * @brief Get value from AppKvStore by its key. + * + * @param key Indicates the key of this entry. + * @param value Indicates the value will be returned in this parameter. + * @return Indicates the status of this get operation. + */ virtual Status Get(const Key &key, Value &value) override; + /** + * @brief Register change of this kvstore to a client-defined observer. + * observer->OnChange method will be called when store changes. + * One observer can subscribe more than one AppKvStore. + * + * @param subscribeType Indicates the subscribe type. + * OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, + * OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, + * OBSERVER_CHANGES_ALL means both native changes and synced data changes. + * @param observer Indicates the observer to subscribe changes. + * @return Indicates the status of this subscribe operation. + */ virtual Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + /** + * @brief Unregister a kvstore to an observer. + * + * @param subscribeType Indicates the subscribe type. + * Reserved parameter. Current is always SubscribeType::DEFAULT. + * @param observer Indicates the observer to unsubscribe this store. + * @return Indicates the status of this unsubscribe operation. + */ virtual Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + /** + * @brief Register message for sync operation. + * + * @param callback Indicates the callback to register. + * @return Indicates the status of this register operation. + */ virtual Status RegisterSyncCallback(std::shared_ptr callback) override; + /** + * @brief Unregister message for sync operation. + * + * @param callback Indicates the callback to register. + * @return Indicates the status of this register operation. + */ virtual Status UnRegisterSyncCallback() override; + /** + * @brief See Put, PutBatch put a list of entries to kvstore, + * all entries will be put in a transaction, + * if entries contains invalid entry, PutBatch will all fail. + * + * @param entries Indicates the entries. + * The entries's size should be less than 128 and memory size must be less than IPC transport limit. + * @return Indicates the status of this register operation. + */ virtual Status PutBatch(const std::vector &entries) override; + /** + * @brief Delete a list of entries in the kvstore, + * delete key not exist still return success, + * key length should not be greater than 256, and can not be empty. + * If keys contains invalid key, all delete will fail. + * + * @param keys Indicates the list of keys. + * The keys memory size should not be greater than IPC transport limit, and can not be empty. + * @return Indicates the status of this register operation. + */ virtual Status DeleteBatch(const std::vector &keys) override; + /** + * @brief Start transaction. + * All changes to this kvstore will be in a same transaction and will not change the store until Commit() or + * Rollback() is called. + * Before this transaction is committed or rollbacked, all attemption to close this store will fail. + * + * @return Indicates the status of this operation. + */ virtual Status StartTransaction() override; + /** + * @brief Commit current transaction. All changes to this store will be done after calling this method. + * Any calling of this method outside a transaction will fail. + * + * @return Indicates the status of this operation. + */ virtual Status Commit() override; + /** + * @brief Rollback current transaction. + * All changes to this store during this transaction will be rollback after calling this method. + * Any calling of this method outside a transaction will fail. + * + * @return Indicates the status of this operation. + */ virtual Status Rollback() override; + /** + * @brief Set synchronization parameters of this store. + * + * @param syncParam Indicates the sync policy parameter. + * @return Indicates the status of this operation. + */ virtual Status SetSyncParam(const KvSyncParam &syncParam) override; + /** + * @brief Get synchronization parameters of this store. + * + * @param syncParam Indicates the sync policy parameter. + * @return Indicates the status of this operation. + */ virtual Status GetSyncParam(KvSyncParam &syncParam) override; + /** + * @brief Set capability parameters of this store. + * + * @param enabled Indicates the capability Enabled status. + * @return Indicates the status of this operation. + */ virtual Status SetCapabilityEnabled(bool enabled) const override; + /** + * @brief Set capability parameters of this store. + * + * @param localLabels Indicates the labels of local. + * @param remoteSupportLabels Indicates the labels of remote support. + * @return Indicates the status of this operation. + */ virtual Status SetCapabilityRange(const std::vector &localLabels, const std::vector &remoteSupportLabels) const override; + /** + * @brief Get security level. + * + * @param securityLevel Indicates the security level. + * @return Indicates the status of this operation. + */ virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const override; + /** + * @brief Sync store with other devices only syncing the data which is satisfied with the condition. + * This is an asynchronous method, sync will fail if there is a syncing operation in progress. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * @param mode Indicates the sync mode, can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUSH_PULL. + * PUSH_PULL will firstly push all not-local store to listed devices, then pull these stores back. + * @return Indicates the status of this operation. + */ virtual Status SyncWithCondition(const std::vector &deviceIds, SyncMode mode, const DataQuery &query, std::shared_ptr syncCallback) override; + /** + * @brief Subscribe store with other devices consistently Synchronize the data which is satisfied + * with the condition. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * + * @return Indicates the status of this operation. + */ virtual Status SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; + /** + * @brief UnSubscribe store with other devices which is satisfied with the condition. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * @return Indicates the status of this UnSubscribe operation. + */ virtual Status UnsubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; - Status GetKvStoreSnapshot(std::shared_ptr observer, - std::shared_ptr &snapshot) const override; - - Status ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) override; - - Status Clear() override; - public: + /** + * @brief Mock insert into kv store. + * + * @param appId Indicates the id of App. + * @param storeId Indicates the id of store. + * @param store Indicates the store. + */ static void InsertMockKvStore(AppId appId, StoreId storeId, std::shared_ptr store); + + /** + * @brief Mock remove kv store. + * + * @param appId Indicates the id of App. + * @param storeId Indicates the id of store. + */ static void RemoveMockKvStore(AppId appId, StoreId storeId); + + /** + * @brief Mock get kvStore pointer. + * + * @param appId Indicates the id of App. + * @param storeId Indicates the id of store. + * @return Indicates the kvstore. + */ static std::shared_ptr GetMockKvStorePointer(AppId appId, StoreId storeId); struct Compare { bool operator()(const Key &a, const Key &b) const @@ -119,8 +366,27 @@ public: } }; + /** + * @brief Mock insert data into kvStore. + * + * @param key Indicates the key. + * @param value Indicates the value. + */ void InsertDataToDoCallback(const Key &key, const Value &value); + + /** + * @brief Mock update data of kvStore. + * + * @param key Indicates the key. + * @param value Indicates the value. + */ void UpdateDataToDoCallback(const Key &key, const Value &value); + + /** + * @brief Mock delete data of kvStore. + * + * @param key Indicates the key. + */ void DeleteDataToDoCallback(const Key &key); protected: diff --git a/services/distributed/test/unittest/mock/mock_event_runner.cpp b/frameworks/ans/test/moduletest/mock/mock_accesstoken_kit.cpp similarity index 66% rename from services/distributed/test/unittest/mock/mock_event_runner.cpp rename to frameworks/ans/test/moduletest/mock/mock_accesstoken_kit.cpp index 4e3cdb37c2911ce62175b359e768353c26a80bc6..7d8f042d3907a75a702b0237d96dd384facad9ad 100644 --- a/services/distributed/test/unittest/mock/mock_event_runner.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_accesstoken_kit.cpp @@ -1,30 +1,27 @@ -/* - * 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. - */ - -#include "event_runner.h" - -namespace OHOS { -namespace AppExecFwk { -EventRunner::EventRunner(bool deposit) : deposit_(deposit) -{} -EventRunner::~EventRunner() -{} - -std::shared_ptr EventRunner::Create(bool inNewThread) -{ - return std::shared_ptr(new EventRunner(false)); -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * 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. + */ + +#include "accesstoken_kit.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + return PERMISSION_GRANTED; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp b/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp index 4ee0032efcbee222a80e78a9c7d6bbe8734abaac..5d1d97a751ffea585db28e02155b2ceda2e57bde 100644 --- a/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp @@ -34,14 +34,5 @@ bool MockBundleMgrService::CheckIsSystemAppByUid(const int uid) } return (uid < SYSTEM_APP_UUID) ? false : true; } - -int MockBundleMgrService::CheckPermission(const std::string &bundleName, const std::string &permission) -{ - if (!bundleName.compare("hello")) { - return 0; - } else { - return -1; - } -} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/mock_bundle_manager_helper.cpp b/frameworks/ans/test/moduletest/mock/mock_bundle_manager_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b4c84abd03d6005edc214ccea8e243afc0e95a8b --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_manager_helper.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "bundle_manager_helper.h" + +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { +BundleManagerHelper::BundleManagerHelper() +{} + +BundleManagerHelper::~BundleManagerHelper() +{} + +void BundleManagerHelper::OnRemoteDied(const wptr &object) +{} + +std::string BundleManagerHelper::GetBundleNameByUid(int uid) +{ + return "bundleName"; +} + +bool BundleManagerHelper::IsSystemApp(int uid) +{ + return true; +} + +int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId) +{ + return 1000; +} + +bool BundleManagerHelper::GetBundleInfoByBundleName( + const std::string bundle, const int32_t userId, AppExecFwk::BundleInfo &bundleInfo) +{ + return true; +} + +bool BundleManagerHelper::CheckApiCompatibility(const sptr &bundleOption) +{ + return true; +} + +void BundleManagerHelper::Connect() +{} + +void BundleManagerHelper::Disconnect() +{} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp index 3e5817f3e8639b0c48b6625580e5737b482f6d2f..6c15c081d414daa00843e0712d68cf94a8e13f6c 100644 --- a/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -124,11 +124,6 @@ bool BundleMgrProxy::QueryKeepAliveBundleInfos(std::vector &bundleIn return true; } -std::string BundleMgrProxy::GetAbilityLabel(const std::string &bundleName, const std::string &className) -{ - return "reply.ReadString()"; -} - bool BundleMgrProxy::GetBundleArchiveInfo(const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) { return true; @@ -149,27 +144,11 @@ int BundleMgrProxy::CheckPublicKeys(const std::string &firstBundleName, const st return 1; } -int BundleMgrProxy::CheckPermission(const std::string &bundleName, const std::string &permission) -{ - return 1; -} - bool BundleMgrProxy::GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) { return true; } -bool BundleMgrProxy::GetAllPermissionGroupDefs(std::vector &permissionDefs) -{ - return true; -} - -bool BundleMgrProxy::GetAppsGrantedPermissions( - const std::vector &permissions, std::vector &appNames) -{ - return true; -} - bool BundleMgrProxy::HasSystemCapability(const std::string &capName) { return true; @@ -220,39 +199,6 @@ bool BundleMgrProxy::IsAbilityEnabled(const AbilityInfo &abilityInfo) return true; } -std::string BundleMgrProxy::GetAbilityIcon(const std::string &bundleName, const std::string &className) -{ - return "AbilityIcon"; -} - -bool BundleMgrProxy::CanRequestPermission( - const std::string &bundleName, const std::string &permissionName, const int userId) -{ - return true; -} - -bool BundleMgrProxy::RequestPermissionFromUser( - const std::string &bundleName, const std::string &permission, const int userId) -{ - return true; -} - -bool BundleMgrProxy::RegisterAllPermissionsChanged(const sptr &callback) -{ - return true; -} - -bool BundleMgrProxy::RegisterPermissionsChanged( - const std::vector &uids, const sptr &callback) -{ - return true; -} - -bool BundleMgrProxy::UnregisterPermissionsChanged(const sptr &callback) -{ - return true; -} - template bool BundleMgrProxy::GetParcelableInfo(IBundleMgr::Message code, MessageParcel &data, T &parcelableInfo) { diff --git a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp index 36738847dc66638b9ba035496f79417e0a4ab2ff..5f3fdd29e52301e33b49ae3f822d9e4f08312ce6 100644 --- a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp @@ -297,21 +297,5 @@ Status AnsTestSingleKvStore::UnsubscribeWithQuery(const std::vector { return Status::SUCCESS; } - -Status AnsTestSingleKvStore::GetKvStoreSnapshot( - std::shared_ptr observer, std::shared_ptr &snapshot) const -{ - return Status::NOT_SUPPORT; -} - -Status AnsTestSingleKvStore::ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) -{ - return Status::NOT_SUPPORT; -} - -Status AnsTestSingleKvStore::Clear() -{ - return Status::NOT_SUPPORT; -} } // namespace DistributedKv } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/message_user.h b/interfaces/innerkits/ans/native/include/message_user.h index 93bb564c461307f199882e29daa466fbdea647a7..e4f1044c24afa58a701ef4eb738413003c25d533 100644 --- a/interfaces/innerkits/ans/native/include/message_user.h +++ b/interfaces/innerkits/ans/native/include/message_user.h @@ -24,121 +24,123 @@ namespace OHOS { namespace Notification { class MessageUser final : public Parcelable, public NotificationJsonConvertionBase { public: - /** - * A constructor used to construct MessageUser - */ MessageUser(); - /** - * Default deconstructor used to deconstruct. - */ ~MessageUser(); /** - * Sets the key used to uniquely identify this MessageUser. - * @note Sets the key used to uniquely identify this MessageUser. - * If no key is set, the name set by SetName(string) is used to uniquely identify a MessageUser. + * @brief Sets the key used to uniquely identify this MessageUser.If no key is set, the name set by SetName(string) + * is used to uniquely identify a MessageUser. + * * @param key Indicates the key to set. */ void SetKey(const std::string &key); /** - * Obtains the key of this MessageUser. + * @brief Obtains the key of this MessageUser. * * @return Returns the key of this MessageUser. */ std::string GetKey() const; /** - * Sets the name of this MessageUser. + * @brief Sets the name of this MessageUser. + * * @name Indicates the name to set. */ void SetName(const std::string &name); /** - * Obtains the name of this MessageUser. + * @brief Obtains the name of this MessageUser. * * @return Returns the name of this MessageUser. */ std::string GetName() const; /** - * Sets the pixel map of this MessageUser. + * @brief Sets the pixel map of this MessageUser. + * * @param pixelMap Indicates the pixel map to set. */ void SetPixelMap(const std::shared_ptr &pixelMap); /** - * Obtains the pixel map of this MessageUser. + * @brief Obtains the pixel map of this MessageUser. * * @return Returns the pixel map of this MessageUser. */ const std::shared_ptr GetPixelMap() const; /** - * Sets the URI of this MessageUser. + * @brief Sets the URI of this MessageUser. + * * @param uri Indicates the URI to set. */ void SetUri(const Uri &uri); /** - * Obtains the URI of this MessageUser. + * @brief Obtains the URI of this MessageUser. * * @return Returns the URI of this MessageUser. */ Uri GetUri() const; /** - * Sets whether this MessageUser is a machine. - * @param machine Specifies whether this MessageUser is a machine. - * The value true indicates that it is, and the value false indicates not. + * @brief Sets whether this MessageUser is a machine. + * + * @param machine Specifies whether this MessageUser is a machine.The value true indicates that it is, + * and the value false indicates not. */ void SetMachine(bool machine); /** - * Checks whether this MessageUser is a machine. + * @brief Checks whether this MessageUser is a machine. * * @return Returns true if this MessageUser is a machine; returns false otherwise. */ bool IsMachine() const; /** - * Sets whether this MessageUser is important. - * @note This method can be used to denote users who frequently interact with the user of this device. - * @param userImportant Specifies whether this MessageUser is important. - * The value true indicates that it is important, and the value false indicates not. + * @brief Sets whether this MessageUser is important.This method can be used to denote users who frequently + * interact with the user of this device. + * + * @param userImportant Specifies whether this MessageUser is important.The value true indicates that it is + * important, and the value false indicates not. */ void SetUserAsImportant(bool userImportant); /** - * Checks whether this MessageUser is important. + * @brief Checks whether this MessageUser is important. * * @return Returns true if this MessageUser is important; returns false otherwise. */ bool IsUserImportant() const; /** - * Dumps a string representation of the object. + * @brief Dumps a string representation of the object. * - * @return A string representation of the object. + * @return Returns a string representation of the object. */ std::string Dump() const; /** - * Converts a MessageUser object into a Json. + * @brief Converts a MessageUser object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a MessageUser object from a Json. + * @brief Creates a MessageUser object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the MessageUser. + * @return Returns the MessageUser object. */ static MessageUser *FromJson(const nlohmann::json &jsonObject); /** - * Marshals a MessageUser object into a Parcel. + * @brief Marshals a MessageUser object into a Parcel. * * @param parcel Indicates the Parcel object for marshalling. * @return Returns true if the marshalling is successful; returns false otherwise. @@ -146,19 +148,19 @@ public: bool Marshalling(Parcel &parcel) const override; /** - * Unmarshals a MessageUser object from a Parcel. + * @brief Unmarshals a MessageUser object from a Parcel. * - * @param parcel Indicates the Parcel object for unmarshalling. + * @param parcel Indicates the parcel object. * @return Returns true if the unmarshalling is successful; returns false otherwise. */ static MessageUser *Unmarshalling(Parcel &parcel); private: /** - * Read NotificationSlot object from a Parcel. + * @brief Read NotificationSlot object from a Parcel. * - * @param parcel the parcel - * @return read from parcel success or fail + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel); @@ -171,9 +173,9 @@ private: bool isUserImportant_ {false}; // no object in parcel - static constexpr int VALUE_NULL = -1; + static constexpr int32_t VALUE_NULL = -1; // object exist in parcel - static constexpr int VALUE_OBJECT = 1; + static constexpr int32_t VALUE_OBJECT = 1; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification.h b/interfaces/innerkits/ans/native/include/notification.h index 2ad6c3ea63a69adcda78f148b19bb0e33427df06..44d81eb44f091417cc94fc50c404d7922b7aa28e 100644 --- a/interfaces/innerkits/ans/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -25,17 +25,17 @@ namespace Notification { class Notification final : public Parcelable { public: /** - * A constructor used to create a Notification instance by existing NotificationRequest object. + * @brief A constructor used to create a Notification instance by existing NotificationRequest object. * - * @param request the existing NotificationRequest object. + * @param request Indicates the existing NotificationRequest object. */ Notification(const sptr &request); /** - * A constructor used to create a Notification instance by existing NotificationRequest object. + * @brief A constructor used to create a Notification instance by existing NotificationRequest object. * - * @param deviceId the device id. - * @param request the existing NotificationRequest object. + * @param deviceId Indicates the device id. + * @param request Indicates the existing NotificationRequest object. */ Notification(const std::string &deviceId, const sptr &request); @@ -46,51 +46,48 @@ public: */ Notification(const Notification &other); - /** - * @brief Default destructor. - */ ~Notification(); /** * @brief Obtains whether to enable the notification light when a notification is received on the device, provided * that this device has a notification light. * - * @return Return true if led light color is set. + * @return Returns true if led light color is set. */ bool EnableLight() const; /** * @brief Obtains the sound enabled or not, set by ANS. * - * @return Return true if sound is set. + * @return Returns true if sound is set. */ bool EnableSound() const; /** * @brief Obtains the vibrate enabled or not, set by ANS. * - * @return Return true if vibrate style is set. + * @return Returns true if vibrate style is set. */ bool EnableVibrate() const; /** * @brief Obtains the bundle's name which publish this notification. * - * @return Return the bundle's name. + * @return Returns the bundle's name. */ std::string GetBundleName() const; /** * @brief Obtains the bundle's name which create this notification. * - * @return Return the creator bundle name. + * @return Returns the creator bundle name. */ std::string GetCreateBundle() const; /** * @brief Obtains the label of this notification. * - * @return Return the label. + * @return Returns the label. */ std::string GetLabel() const; @@ -100,133 +97,134 @@ public: * @return Returns the color of the notification light. */ int32_t GetLedLightColor() const; + /** * @brief Sets the notification display effect, including whether to display this notification on the lock screen, * and how it will be presented if displayed. * - * @return Return the display effect of this notification on the lock screen. + * @return Returns the display effect of this notification on the lock screen. */ NotificationConstant::VisiblenessType GetLockscreenVisibleness() const; /** * @brief The ID passed to setGroup(), or the override, or null. * - * @return string of group. + * @return Returns the string of group. */ std::string GetGroup() const; /** * @brief Obtains the id of the notification. * - * @return The id supplied to NotificationManager::Notify(int, NotificationRequest). + * @return Returns the id supplied to NotificationManager::Notify(int, NotificationRequest). */ int32_t GetId() const; /** * @brief A key for this notification record. * - * @return A unique instance key. + * @return Returns a unique instance key. */ std::string GetKey() const; /** - * @brief Obtains the notificanton request set by ANS. + * @brief Obtains the notification request set by ANS. * - * @return Return sptr. + * @return Returns NotificationRequest object. */ NotificationRequest GetNotificationRequest() const; /** * @brief Obtains the time notification was posted. * - * @return The time notificationRequest was posted. + * @return Returns the time notificationRequest was posted. */ int64_t GetPostTime() const; /** * @brief Obtains the sound uri. * - * @return Return the sound set by ANS. + * @return Returns the sound set by ANS. */ Uri GetSound() const; /** * @brief Obtains the UID of the notification creator. * - * @return Return the UID of the notification creator. + * @return Returns the UID of the notification creator. */ - pid_t GetUid() const; + int32_t GetUid() const; /** * @brief Obtains the PID of the notification creator. * - * @return Return the PID of the notification creator. + * @return Returns the PID of the notification creator. */ pid_t GetPid() const; /** - * Checks whether this notification is unremovable. - * @return true if this notification is unremovable; returns false otherwise. + * @brief Checks whether this notification is unremovable. + * @return Returns true if this notification is unremovable; returns false otherwise. */ bool IsUnremovable() const; /** - * @brief Obtains the vibration style for this notifications. if + * @brief Obtains the vibration style for this notifications. * - * @return Return the vibration style. + * @return Returns the vibration style. */ std::vector GetVibrationStyle() const; /** * @brief This notification is part of a group or not. * - * @return true if this notification is part of a group. + * @return Returns true if this notification is part of a group. */ bool IsGroup() const; /** * @brief Checks whether this notification is displayed as a floating icon on top of the screen. * - * @return true if this notification is displayed as a floating icon; returns false otherwise. + * @return Returns true if this notification is displayed as a floating icon; returns false otherwise. */ bool IsFloatingIcon() const; /** * @brief Obtains the remind type of a notification. - * @return the remind type of a notification. + * @return Returns the remind type of a notification. */ NotificationConstant::RemindType GetRemindType() const; /** - * Whether to support remove allowed. - * @return Current remove allowed status. + * @brief Whether to support remove allowed. + * @return Returns the current remove allowed status. */ bool IsRemoveAllowed() const; /** - * Gets the notification source. - * @return the notification slot type. + * @brief Gets the notification source. + * @return Returns the notification slot type. */ NotificationConstant::SourceType GetSourceType() const; /** * @brief Gets the device id of the notification source. * - * @return Return the device id. + * @return Returns the device id. */ std::string GetDeviceId() const; /** * @brief Obtains the UserId of the notification creator. * - * @return Return the UserId of the notification creator. + * @return Returns the UserId of the notification creator. */ int32_t GetUserId() const; /** * @brief Dumps a string representation of the object. * - * @return A string representation of the object. + * @return Returns a string representation of the object. */ std::string Dump() const; @@ -234,7 +232,6 @@ public: * @brief Marshals a Notification object into a Parcel. * * @param parcel Indicates the Parcel object for marshalling. - * * @return Returns true if the marshalling is successful; returns false otherwise. */ bool Marshalling(Parcel &parcel) const; @@ -243,7 +240,6 @@ public: * @brief Unmarshals a Notification object from a Parcel. * * @param Indicates the Parcel object for unmarshalling. - * * @return Returns true if the unmarshalling is successful; returns false otherwise. */ static Notification *Unmarshalling(Parcel &parcel); @@ -252,7 +248,7 @@ private: Notification(); void SetEnableSound(const bool &enable); void SetEnableLight(const bool &enable); - void SetEnableViration(const bool &enable); + void SetEnableVibration(const bool &enable); void SetLedLightColor(const int32_t &color); void SetLockScreenVisbleness(const NotificationConstant::VisiblenessType &visbleness); void SetPostTime(const int64_t &time); @@ -278,7 +274,7 @@ private: private: bool enableSound_ {false}; bool enableLight_ {false}; - bool enableViration_ {false}; + bool enableVibration_ {false}; bool isRemoveAllowed_ {true}; std::string key_ {""}; std::string deviceId_ {""}; diff --git a/interfaces/innerkits/ans/native/include/notification_action_button.h b/interfaces/innerkits/ans/native/include/notification_action_button.h index 48dfe2a238c4f6c3c49207c94fbd7d6fd1a42d62..d5280b57e972f78423fdc2d82d085cd4ae018746 100644 --- a/interfaces/innerkits/ans/native/include/notification_action_button.h +++ b/interfaces/innerkits/ans/native/include/notification_action_button.h @@ -28,7 +28,8 @@ namespace Notification { class NotificationActionButton : public Parcelable, public NotificationJsonConvertionBase { public: /** - * A static function used to create a NotificationActionButton instance with the input parameters passed. + * @brief A static function used to create a NotificationActionButton instance with the input parameters passed. + * * @param icon Indicates the icon to represent this NotificationActionButton. * @param title Indicates the title of this NotificationActionButton. * @param wantAgent Indicates the wantAgent to be triggered when this NotificationActionButton is triggered. @@ -40,8 +41,8 @@ public: * @param userInputs Indicates the NotificationUserInput object to add. * @param isContextual Indicates whether this NotificationActionButton is a contextual action, that is, whether this * NotificationActionButton is dependent on the notification message body. - * @return the shared_ptr object owns the created NotificationActionButton object otherwise return empty object if - * isContextual is true but icon or wantAgent is empty. + * @return Returns the shared_ptr object owns the created NotificationActionButton object otherwise returns empty + * object if isContextual is true but icon or wantAgent is empty. */ static std::shared_ptr Create(const std::shared_ptr &icon, const std::string &title, const std::shared_ptr &wantAgent, @@ -50,37 +51,39 @@ public: NotificationConstant::SemanticActionButton::NONE_ACTION_BUTTON, bool autoCreatedReplies = true, const std::vector> &mimeTypeOnlyInputs = {}, - const std::vector> &userInputs = {}, bool isContextual = false); + const std::shared_ptr &userInput = {}, bool isContextual = false); /** - * A static function used to create a NotificationActionButton instance by copying parameters from an existing - * NotificationActionButton object. + * @brief A static function used to create a NotificationActionButton instance by copying parameters from an + * existing NotificationActionButton object. + * * @param actionButton Indicates the existing NotificationActionButton object. - * @return the shared_ptr object owns the created NotificationActionButton object otherwise return empty object. + * @return Returns the shared_ptr object owns the created NotificationActionButton object otherwise returns + * empty object. */ static std::shared_ptr Create( const std::shared_ptr &actionButton); - /** - * Default deconstructor used to deconstruct. - */ ~NotificationActionButton() = default; /** - * Obtains the icon of this NotificationActionButton. - * @return the icon of this NotificationActionButton. + * @brief Obtains the icon of this NotificationActionButton. + * + * @return Returns the icon of this NotificationActionButton. */ const std::shared_ptr GetIcon() const; /** - * Obtains the title of this NotificationActionButton. - * @return the title of this NotificationActionButton. + * @brief Obtains the title of this NotificationActionButton. + * + * @return Returns the title of this NotificationActionButton. */ std::string GetTitle() const; /** - * Obtains the WantAgent of this NotificationActionButton. - * @return the WantAgent of this NotificationActionButton. + * @brief Obtains the WantAgent of this NotificationActionButton. + * + * @return Returns the WantAgent of this NotificationActionButton. */ const std::shared_ptr GetWantAgent() const; @@ -91,121 +94,138 @@ public: void AddAdditionalData(AAFwk::WantParams &extras); /** - * Obtains the additional data included in this NotificationActionButton. - * @return the additional data included in this NotificationActionButton. + * @brief Obtains the additional data included in this NotificationActionButton. + * + * @return Returns the additional data included in this NotificationActionButton. */ const std::shared_ptr GetAdditionalData() const; /** - * Sets a semantic action for this NotificationActionButton. - * @param semanticActionButton Indicates the semantic action to add. - * For available values, see NotificationConstant::SemanticActionButton. + * @brief Sets a semantic action for this NotificationActionButton. + * + * @param semanticActionButton Indicates the semantic action to add.For available values, + * see NotificationConstant::SemanticActionButton. */ void SetSemanticActionButton(NotificationConstant::SemanticActionButton semanticActionButton); /** - * Obtains the semantic action of this NotificationActionButton. - * @return the semantic action of this NotificationActionButton, - * as enumerated in NotificationConstant::SemanticActionButton. + * @brief Obtains the semantic action of this NotificationActionButton. + * + * @return Returns the semantic action of this NotificationActionButton, as enumerated in + * NotificationConstant::SemanticActionButton. */ NotificationConstant::SemanticActionButton GetSemanticActionButton() const; /** - * Adds a NotificationUserInput object that only allows values of particular MIME types. + * @brief Adds a NotificationUserInput object that only allows values of particular MIME types. + * * @param userInput Indicates the NotificationUserInput object to add. */ void AddMimeTypeOnlyUserInput(const std::shared_ptr &userInput); /** - * Obtains the NotificationUserInput objects that only allow values of particular MIME types + * @brief Obtains the NotificationUserInput objects that only allow values of particular MIME types * when this NotificationActionButton is sent. - * @return the list of NotificationUserInput objects allowing only values of particular MIME types. + * + * @return Returns the list of NotificationUserInput objects allowing only values of particular MIME types. */ std::vector> GetMimeTypeOnlyUserInputs() const; /** - * Adds a NotificationUserInput object used to collect user input. + * @brief Adds a NotificationUserInput object used to collect user input. + * * @param userInput Indicates the NotificationUserInput object to add. */ void AddNotificationUserInput(const std::shared_ptr &userInput); /** - * Obtains the NotificationUserInput objects to be collected from the user when this NotificationActionButton + * @brief Obtains the NotificationUserInput object to be collected from the user when this NotificationActionButton * is sent. - * @return the list of NotificationUserInput objects. + * + * @return Returns the NotificationUserInput object. */ - std::vector> GetUserInputs() const; + const std::shared_ptr GetUserInput() const; /** - * Sets whether to allow the platform to automatically generate possible replies and add them to + * @brief Sets whether to allow the platform to automatically generate possible replies and add them to * NotificationUserInput::getOptions(). + * * @param autoCreatedReplies Specifies whether to allow the platform to automatically generate possible replies. * The value true means to allow generated replies; and the value false means not. */ void SetAutoCreatedReplies(bool autoCreatedReplies); /** - * Checks whether the platform can automatically generate possible replies for this NotificationActionButton. - * @return true if the platform can generate replies; returns false otherwise. + * @brief Checks whether the platform can automatically generate possible replies for this NotificationActionButton. + * + * @return Returns true if the platform can generate replies; returns false otherwise. */ bool IsAutoCreatedReplies() const; /** - * Sets whether this NotificationActionButton is a contextual action, that is, whether this + * @brief Sets whether this NotificationActionButton is a contextual action, that is, whether this * NotificationActionButton is dependent on the notification message body. For example, a contextual * NotificationActionButton provides an address in the notification for users to open a map application. + * * @param isContextual Specifies whether this NotificationActionButton is a contextual action. * The value true indicates a contextual action, and the value false indicates not. */ void SetContextDependent(bool isContextual); /** - * Checks whether this NotificationActionButton is a contextual action, that is, whether this + * @brief Checks whether this NotificationActionButton is a contextual action, that is, whether this * NotificationActionButton is dependent on the notification message body. For example, a contextual * NotificationActionButton provides an address in the notification for users to open a map application. - * @return true if this NotificationActionButton is a contextual action; returns false otherwise. + * + * @return Returns true if this NotificationActionButton is a contextual action; returns false otherwise. */ bool IsContextDependent() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump(); /** - * Converts a NotificationActionButton object into a Json. + * @brief Converts a NotificationActionButton object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationActionButton object from a Json. + * @brief Creates a NotificationActionButton object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationActionButton. + * @return Returns the NotificationActionButton. */ static NotificationActionButton *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationActionButton + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationActionButton. */ static NotificationActionButton *Unmarshalling(Parcel &parcel); private: - /** - * Default constructor used to create a NotificationActionButton instance. - */ NotificationActionButton() = default; /** - * A constructor used to create a NotificationActionButton instance with the input parameters passed. + * @brief A constructor used to create a NotificationActionButton instance with the input parameters passed. + * * @param icon Indicates the icon to represent this NotificationActionButton. * @param title Indicates the title of this NotificationActionButton. * @param wantAgent Indicates the WantAgent to be triggered when this NotificationActionButton is triggered. @@ -222,11 +242,13 @@ private: const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, const std::vector> &mimeTypeOnlyInputs, - const std::vector> &userInputs, bool isContextual); + const std::shared_ptr &userInput, bool isContextual); /** - * Read a NotificationActionButton object from a Parcel. - * @param parcel the parcel + * @brief Read a NotificationActionButton object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel); @@ -240,7 +262,7 @@ private: }; bool autoCreatedReplies_ {true}; std::vector> mimeTypeOnlyUserInputs_ {}; - std::vector> userInputs_ {}; + std::shared_ptr userInput_ {}; bool isContextual_ {false}; }; } // namespace Notification diff --git a/interfaces/innerkits/ans/native/include/notification_basic_content.h b/interfaces/innerkits/ans/native/include/notification_basic_content.h index 65ccd08bb9656714fd3206562091063c917794be..62d860b17f18921098c0d884fad76ba53abdd81a 100644 --- a/interfaces/innerkits/ans/native/include/notification_basic_content.h +++ b/interfaces/innerkits/ans/native/include/notification_basic_content.h @@ -23,82 +23,89 @@ namespace OHOS { namespace Notification { class NotificationBasicContent : public Parcelable, public NotificationJsonConvertionBase { public: - /** - * Default deconstructor used to deconstruct. - */ virtual ~NotificationBasicContent(); /** - * Sets the additional text to be included in a notification. + * @brief Sets the additional text to be included in a notification. * The additional text is mainly a supplement to the notification text set by calling setText(std::string). * The font of the additional text is smaller than the notification text and is displayed in a separate line. + * * @param text Indicates the additional text to be included. */ virtual void SetAdditionalText(const std::string &additionalText); /** - * Obtains the additional text of a notification specified by calling setAdditionalText(std::string). - * @return the additional text of the notification. + * @brief Obtains the additional text of a notification specified by calling setAdditionalText(std::string). + * + * @return Returns the additional text of the notification. */ virtual std::string GetAdditionalText() const; /** - * Sets the text to be included in a notification. + * @brief Sets the text to be included in a notification. + * * @param text Indicates the text to be included. */ virtual void SetText(const std::string &text); /** - * Obtains the text of a notification specified by calling setText(std::string). - * @return the text of the notification. + * @brief Obtains the text of a notification specified by calling setText(std::string). + * + * @return Returns the text of the notification. */ virtual std::string GetText() const; /** - * Sets the title of a notification. + * @brief Sets the title of a notification. + * * @param title Indicates the title of the notification. */ virtual void SetTitle(const std::string &title); /** - * Obtains the title of a notification specified by calling the setTitle(std::string) method. - * @return the title of the notification. + * @brief Obtains the title of a notification specified by calling the setTitle(std::string) method. + * + * @return Returns the title of the notification. */ virtual std::string GetTitle() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ virtual std::string Dump(); /** - * Converts a NotificationBasicContent object into a Json. + * @brief Converts a NotificationBasicContent object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ virtual bool ToJson(nlohmann::json &jsonObject) const override; /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; protected: - /** - * Default constructor. - */ NotificationBasicContent() = default; /** - * Read data from a Parcel. - * @param parcel the parcel - * @return true if read success; returns false otherwise. + * @brief Read data from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if read success; returns false otherwise. */ virtual bool ReadFromParcel(Parcel &parcel); /** - * Creates a NotificationBasicContent object from a Json. + * @brief Creates a NotificationBasicContent object from a Json. + * * @param jsonObject Indicates the Json object. */ void ReadFromJson(const nlohmann::json &jsonObject); diff --git a/interfaces/innerkits/ans/native/include/notification_bundle_option.h b/interfaces/innerkits/ans/native/include/notification_bundle_option.h index 992bfff9e80ca583685acd1107b21892b99cef1b..a47eff340b77d8794eed0a21fe3b9d30edbd8c58 100644 --- a/interfaces/innerkits/ans/native/include/notification_bundle_option.h +++ b/interfaces/innerkits/ans/native/include/notification_bundle_option.h @@ -22,70 +22,75 @@ namespace OHOS { namespace Notification { class NotificationBundleOption : public Parcelable { public: - /** - * A default constructor used to create a NotificationBundleOption instance. - */ NotificationBundleOption() = default; /** - * A constructor used to create a NotificationBundleOption instance based on the creator bundle name and uid. + * @brief A constructor used to create a NotificationBundleOption instance based on the creator bundle name and uid. + * * @param bundleName Indicates the creator bundle name. * @param uid Indicates the creator uid. */ NotificationBundleOption(const std::string &bundleName, const int32_t uid); - /** - * Default deconstructor used to deconstruct. - */ virtual ~NotificationBundleOption(); /** - * Sets the creator bundle name. + * @brief Sets the creator bundle name. + * * @param bundleName Indicates the creator bundle name. */ void SetBundleName(const std::string &bundleName); /** - * Obtains the creator bundle name. - * @return the creator bundle name. + * @brief Obtains the creator bundle name. + * + * @return Returns the creator bundle name. */ std::string GetBundleName() const; /** - * Sets the creator uid. + * @brief Sets the creator uid. + * * @param uid Indicates the creator uid. */ void SetUid(const int32_t uid); /** - * Obtains the creator uid. - * @return the creator uid. + * @brief Obtains the creator uid. + * + * @return Returns the creator uid. */ int32_t GetUid() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump(); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel Indicates the object into the parcel + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationBundleOption + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationBundleOption */ static NotificationBundleOption *Unmarshalling(Parcel &parcel); private: /** - * Read data from a Parcel. - * @param parcel the parcel - * @return true if read success; returns false otherwise. + * @brief Read data from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if read success; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel); diff --git a/interfaces/innerkits/ans/native/include/notification_constant.h b/interfaces/innerkits/ans/native/include/notification_constant.h index c9dd27dc652a1ebfb1433bfdaf372457e901576a..0d349c1b9b0fff1fb0b0afdfe4b850a24290df47 100644 --- a/interfaces/innerkits/ans/native/include/notification_constant.h +++ b/interfaces/innerkits/ans/native/include/notification_constant.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -129,52 +129,52 @@ public: /** * Indicates that a notification is deleted because it is clicked. */ - static const int CLICK_REASON_DELETE = 1; + static const int32_t CLICK_REASON_DELETE = 1; /** * Indicates that a notification is deleted because the user clears it. */ - static const int CANCEL_REASON_DELETE = 2; + static const int32_t CANCEL_REASON_DELETE = 2; /** * Indicates that a notification is deleted because the user clears all notifications. */ - static const int CANCEL_ALL_REASON_DELETE = 3; + static const int32_t CANCEL_ALL_REASON_DELETE = 3; /** * Indicates that a notification is deleted because of a UI error. */ - static const int ERROR_REASON_DELETE = 4; + static const int32_t ERROR_REASON_DELETE = 4; /** * Indicates that a notification is deleted because a change has been made to the application. */ - static const int PACKAGE_CHANGED_REASON_DELETE = 5; + static const int32_t PACKAGE_CHANGED_REASON_DELETE = 5; /** * Indicates that a notification is deleted because the application context is stopped. */ - static const int USER_STOPPED_REASON_DELETE = 6; + static const int32_t USER_STOPPED_REASON_DELETE = 6; /** * Indicates that a notification is deleted because the application is banned from sending notifications. */ - static const int PACKAGE_BANNED_REASON_DELETE = 7; + static const int32_t PACKAGE_BANNED_REASON_DELETE = 7; /** * Indicates that a notification is deleted because the application cancels it. */ - static const int APP_CANCEL_REASON_DELETE = 8; + static const int32_t APP_CANCEL_REASON_DELETE = 8; /** * Indicates that a notification is deleted because the application cancels all notifications. */ - static const int APP_CANCEL_ALL_REASON_DELETE = 9; + static const int32_t APP_CANCEL_ALL_REASON_DELETE = 9; /** * Indicates that a notification is deleted for other reasons. */ - static const int APP_CANCEL_REASON_OTHER = 10; + static const int32_t APP_CANCEL_REASON_OTHER = 10; /** * The key indicates input source. diff --git a/interfaces/innerkits/ans/native/include/notification_content.h b/interfaces/innerkits/ans/native/include/notification_content.h index 0923b9ea0401cc786f58d0faed4b2975f5019bce..425b1247f79efa159bbc2f0fd29cbadf9d883a00 100644 --- a/interfaces/innerkits/ans/native/include/notification_content.h +++ b/interfaces/innerkits/ans/native/include/notification_content.h @@ -67,59 +67,65 @@ public: }; /** - * A constructor used to create a NotificationNormalContent instance (obtained by calling GetNotificationContent()) - * and set the content type to NotificationContent::Type::BASIC_TEXT (obtained by calling GetContentType()). + * @brief A constructor used to create a NotificationNormalContent instance (obtained by calling + * GetNotificationContent()) and set the content type to NotificationContent::Type::BASIC_TEXT (obtained by calling + * GetContentType()). + * * @param normalContent Indicates the NotificationNormalContent object. */ explicit NotificationContent(const std::shared_ptr &normalContent); /** - * A constructor used to create a NotificationLongTextContent instance (obtained by calling + * @brief A constructor used to create a NotificationLongTextContent instance (obtained by calling * GetNotificationContent()) and set the content type to NotificationContent::Type::LONG_TEXT (obtained by calling * GetContentType()). + * * @param longTextContent Indicates the NotificationLongTextContent object. */ explicit NotificationContent(const std::shared_ptr &longTextContent); /** - * A constructor used to create a NotificationPictureContent instance (obtained by calling GetNotificationContent()) - * and set the content type to NotificationContent::Type::PICTURE (obtained by calling GetContentType()). + * @brief A constructor used to create a NotificationPictureContent instance (obtained by calling + * GetNotificationContent()) and set the content type to NotificationContent::Type::PICTURE (obtained by calling + * GetContentType()). + * * @param pictureContent Indicates the NotificationPictureContent object. */ explicit NotificationContent(const std::shared_ptr &pictureContent); /** - * A constructor used to create a NotificationConversationalContent instance - * (obtained by calling GetNotificationContent()) and set the content type to - * NotificationContent::Type::CONVERSATION (obtained by calling GetContentType()). + * @brief A constructor used to create a NotificationConversationalContent instance (obtained by calling + * GetNotificationContent()) and set the content type to NotificationContent::Type::CONVERSATION (obtained by + * calling GetContentType()). + * * @param conversationContent Indicates the NotificationConversationalContent object. */ explicit NotificationContent(const std::shared_ptr &conversationContent); /** - * A constructor used to create a NotificationMultiLineContent instance - * (obtained by calling GetNotificationContent()) and set the content type to - * NotificationContent::Type::MULTILINE (obtained by calling GetContentType()). + * @brief A constructor used to create a NotificationMultiLineContent instance (obtained by calling + * GetNotificationContent()) and set the content type to NotificationContent::Type::MULTILINE (obtained by calling + * GetContentType()). + * * @param multiLineContent Indicates the NotificationMultiLineContent object. */ explicit NotificationContent(const std::shared_ptr &multiLineContent); /** - * A constructor used to create a NotificationMediaContent instance - * (obtained by calling GetNotificationContent()) and set the content type to - * NotificationContent::Type::MEDIA (obtained by calling GetContentType()). + * @brief A constructor used to create a NotificationMediaContent instance (obtained by calling + * GetNotificationContent()) and set the content type to NotificationContent::Type::MEDIA (obtained by calling + * GetContentType()). + * * @param mediaContent Indicates the NotificationMediaContent object. */ explicit NotificationContent(const std::shared_ptr &mediaContent); - /** - * Default deconstructor used to deconstruct. - */ virtual ~NotificationContent(); /** - * Obtains the type value of the notification content. - * @return the type value of the current content, which can be + * @brief Obtains the type value of the notification content. + * + * @return Returns the type value of the current content, which can be * NotificationContent::Type::BASIC_TEXT, * NotificationContent::Type::LONG_TEXT, * NotificationContent::Type::PICTURE, @@ -130,8 +136,9 @@ public: NotificationContent::Type GetContentType() const; /** - * Obtains the object matching the current notification content. - * @return the content object, which can be NotificationLongTextContent, + * @brief Obtains the object matching the current notification content. + * + * @return Returns the content object, which can be NotificationLongTextContent, * NotificationNormalContent, * NotificationPictureContent, * NotificationConversationalContent, @@ -141,49 +148,62 @@ public: std::shared_ptr GetNotificationContent() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump(); /** - * Converts a NotificationContent object into a Json. + * @brief Converts a NotificationContent object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationContent object from a Json. + * @brief Creates a NotificationContent object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationContent. + * @return Returns the NotificationContent. */ static NotificationContent *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel Indicates the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationContent + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationContent. */ static NotificationContent *Unmarshalling(Parcel &parcel); private: - /** - * Default constructor used to create an empty NotificationContent instance. - */ NotificationContent() = default; /** - * Read data from a Parcel. - * @param parcel the parcel - * @return true if read success; returns false otherwise. + * @brief Read data from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if read success; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel); + /** + * @brief Convert JSON object to NotificationContent object. + * + * @param target Indicates the NotificationContent object. + * @param jsonObject Indicates the JSON object. + * @return Returns true if the conversion is successful; returns false otherwise. + */ static bool ConvertJsonToContent(NotificationContent *target, const nlohmann::json &jsonObject); private: diff --git a/interfaces/innerkits/ans/native/include/notification_conversational_content.h b/interfaces/innerkits/ans/native/include/notification_conversational_content.h index 999497416e064b5b24bb771f006b7936eb2c036b..90db3cfd0238811ac48121e029b04febe8cc8c41 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_content.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_content.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -30,55 +30,58 @@ public: using MessageVector = std::vector; /** - * A constructor used to create a NotificationConversationalContent instance with the MessageUser specified. + * @brief A constructor used to create a NotificationConversationalContent instance with the MessageUser specified. + * * @param messageUser Indicates the MessageUser who sends all Message objects in this conversation-like * notification. This parameter cannot be null. */ - NotificationConversationalContent(const MessageUser &messageUser); + explicit NotificationConversationalContent(const MessageUser &messageUser); - /** - * Default deconstructor used to deconstruct. - */ ~NotificationConversationalContent() = default; /** - * Obtains the message sender to be displayed for any messages - * sent by the user in this conversation-like notification. - * @return the message sender. + * @brief Obtains the message sender to be displayed for any messages sent by the user in this conversation-like + * notification. + * + * @return Returns the message sender. */ MessageUser GetMessageUser() const; /** - * Sets the title to be displayed for the conversation. - * The title set in this method will overwrite the one set by calling setTitle(std::string). + * @brief Sets the title to be displayed for the conversation.The title set in this method will overwrite the one + * set by calling setTitle(std::string). + * * @param conversationTitle Indicates the title to be displayed for the conversation. */ void SetConversationTitle(const std::string &conversationTitle); /** - * Obtains the title to be displayed for the conversation. - * @return the title to be displayed for the conversation. + * @brief Obtains the title to be displayed for the conversation. + * + * @return Returns the title to be displayed for the conversation. */ std::string GetConversationTitle() const; /** - * Checks whether this notification represents a group conversation. - * @return true if this notification represents a group conversation; returns false otherwise. + * @brief Checks whether this notification represents a group conversation. + * + * @return Returns true if this notification represents a group conversation; returns false otherwise. */ bool IsConversationGroup() const; /** - * Sets whether this notification represents a group conversation. + * @brief Sets whether this notification represents a group conversation. * The big icon, if any, set for this notification by calling NotificationRequest::setBigIcon(PixelMap) * will be displayed only when this method is set to true. + * * @param isGroup Specifies whether this notification represents a group conversation. */ void SetConversationGroup(bool isGroup); /** - * Adds a message to this conversation-like notification based on - * the specified message content, timestamp, and MessageUser. - * All messages will be displayed in the order they are added. + * @brief Adds a message to this conversation-like notification based on the specified message content, timestamp, + * and MessageUser.All messages will be displayed in the order they are added. + * * @param text Indicates the text to be displayed as the message content. * @param timestamp Indicates the time when the message arrived. * @param sender Indicates the MessageUser who sent the message. @@ -87,60 +90,69 @@ public: const std::string &text, int64_t timestamp, const MessageUser &sender); /** - * Adds a specified message to this conversation-like notification. - * All messages will be displayed in the order they are added. + * @brief Adds a specified message to this conversation-like notification.All messages will be displayed in the + * order they are added. + * * @param message Indicates the ConversationalMessage object to add. */ void AddConversationalMessage(const MessagePtr &message); /** - * Obtains all messages included in this conversation-like notification. - * @return the list of all Message objects included. + * @brief Obtains all messages included in this conversation-like notification. + * + * @return Returns the list of all Message objects included. */ MessageVector GetAllConversationalMessages() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump() override; /** - * Converts a NotificationConversationalContent object into a Json. + * @brief Converts a NotificationConversationalContent object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ virtual bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationConversationalContent object from a Json. + * @brief Creates a NotificationConversationalContent object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationConversationalContent. + * @return Returns the NotificationConversationalContent. */ static NotificationConversationalContent *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel Indicates the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationConversationalContent + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationConversationalContent. */ static NotificationConversationalContent *Unmarshalling(Parcel &parcel); protected: /** - * Read a NotificationConversationalContent object from a Parcel. - * @param parcel the parcel + * @brief Read a NotificationConversationalContent object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel) override; private: - /** - * Default constructor used to create an empty NotificationConversationalContent instance. - */ NotificationConversationalContent() = default; private: diff --git a/interfaces/innerkits/ans/native/include/notification_conversational_message.h b/interfaces/innerkits/ans/native/include/notification_conversational_message.h index b32fe9f654eccd4066ed3ec74290e8d1e446476e..61e471ad58cb67ab53b1e68626f4537383b9e6d4 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_message.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_message.h @@ -26,7 +26,9 @@ namespace Notification { class NotificationConversationalMessage : public Parcelable, public NotificationJsonConvertionBase { public: /** - * A constructor used to create a NotificationConversationalMessage instance with the input parameters passed. + * @brief A constructor used to create a NotificationConversationalMessage instance with the input parameters + * passed. + * * @param text Indicates the text to be displayed as the message content. This parameter cannot be null. * @param timestamp Indicates the time when the message arrived. * @param sender Indicates the MessageUser who sent the message. @@ -34,88 +36,98 @@ public: NotificationConversationalMessage( const std::string &text, int64_t timestamp, const MessageUser &sender); - /** - * Default deconstructor used to deconstruct. - */ ~NotificationConversationalMessage() = default; /** - * Obtains the text to be displayed as the content of this message. - * @return the message content. + * @brief Obtains the text to be displayed as the content of this message. + * + * @return Returns the message content. */ std::string GetText() const; /** - * Obtains the time when this message arrived. - * @return the time when this message arrived. + * @brief Obtains the time when this message arrived. + * + * @return Returns the time when this message arrived. */ int64_t GetArrivedTime() const; /** - * Obtains the sender of this message. - * @return the message sender. + * @brief Obtains the sender of this message. + * + * @return Returns the message sender. */ MessageUser GetSender() const; /** - * Sets the MIME type and URI of this message. + * @brief Sets the MIME type and URI of this message. + * * @param mimeType Indicates the MIME type of this message. * @param uri Indicates the URI that points to the message content whose type is specified by the given MIME type. */ void SetData(const std::string &mimeType, const std::shared_ptr &uri); /** - * Obtains the MIME type of this message. - * @return the MIME type of this message. + * @brief Obtains the MIME type of this message. + * + * @return Returns the MIME type of this message. */ std::string GetMimeType() const; /** - * Obtains the URI of the message content with the specific MIME type. - * @return the URI of the message content with the specific MIME type. + * @brief Obtains the URI of the message content with the specific MIME type. + * + * @return Returns the URI of the message content with the specific MIME type. */ const std::shared_ptr GetUri() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump(); /** - * Converts a NotificationConversationalMessage object into a Json. + * @brief Converts a NotificationConversationalMessage object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationConversationalMessage object from a Json. + * @brief Creates a NotificationConversationalMessage object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationConversationalMessage. + * @return Returns the NotificationConversationalMessage. */ static NotificationConversationalMessage *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel Indicates the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationConversationalMessage + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationConversationalMessage. */ static NotificationConversationalMessage *Unmarshalling(Parcel &parcel); private: - /** - * Default constructor used to create an empty NotificationConversationalMessage instance. - */ NotificationConversationalMessage() = default; /** - * Read a NotificationConversationalMessage object from a Parcel. - * @param parcel the parcel + * @brief Read a NotificationConversationalMessage object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel); diff --git a/interfaces/innerkits/ans/native/include/notification_distributed_options.h b/interfaces/innerkits/ans/native/include/notification_distributed_options.h index 56d9e65029dc002407362e75c07e88cdc12d21f3..6d0ad4c6014d5b180bc8194f1ffc40490baf5c0f 100644 --- a/interfaces/innerkits/ans/native/include/notification_distributed_options.h +++ b/interfaces/innerkits/ans/native/include/notification_distributed_options.h @@ -23,96 +23,107 @@ namespace OHOS { namespace Notification { class NotificationDistributedOptions : public Parcelable, public NotificationJsonConvertionBase { public: - /** - * Default constructor used to create a NotificationDistributedOptions instance. - */ NotificationDistributedOptions() = default; /** - * Constructor used to create a NotificationDistributedOptions instance. + * @brief Constructor used to create a NotificationDistributedOptions instance. + * * @param distribute Specifies whether a notification is distributed. - * @param dvsDisplay The devices that support display. - * @param dvsOperate The devices that support operate. + * @param dvsDisplay Indicates the devices that support display. + * @param dvsOperate Indicates the devices that support operate. */ NotificationDistributedOptions( bool distribute, const std::vector &dvsDisplay, const std::vector &dvsOperate); - /** - * Default deconstructor used to deconstruct. - */ ~NotificationDistributedOptions() = default; /** - * Sets whether a notification is distributed. + * @brief Sets whether a notification is distributed. + * * @param distribute Specifies whether a notification is distributed. */ void SetDistributed(bool distribute); /** - * Checks whether a notification is distributed. - * @return true if the notification is distributed; returns false otherwise. + * @brief Checks whether a notification is distributed. + * + * @return Returns true if the notification is distributed; returns false otherwise. */ bool IsDistributed() const; /** - * Sets devices that support display. - * @param devices The devices that support display. + * @brief Sets devices that support display. + * + * @param devices Indicates the devices that support display. */ void SetDevicesSupportDisplay(const std::vector &devices); /** - * Obtains the devices that support display. - * @return the devices that support display. + * @brief Obtains the devices that support display. + * + * @return Returns the devices that support display. */ std::vector GetDevicesSupportDisplay() const; /** - * Sets devices that support operate. - * @param devices The devices that support operate. + * @brief Sets devices that support operate. + * + * @param devices Indicates the devices that support operate. */ void SetDevicesSupportOperate(const std::vector &devices); /** - * Obtains the devices that support operate. - * @return the devices that support operate. + * @brief Obtains the devices that support operate. + * + * @return Returns the devices that support operate. */ std::vector GetDevicesSupportOperate() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump(); /** - * Converts a NotificationDistributedOptions object into a Json. + * @brief Converts a NotificationDistributedOptions object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationDistributedOptions object from a Json. + * @brief Creates a NotificationDistributedOptions object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationDistributedOptions. + * @return Returns the NotificationDistributedOptions. */ static NotificationDistributedOptions *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel Indicates the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationDistributedOptions + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationDistributedOptions object. */ static NotificationDistributedOptions *Unmarshalling(Parcel &parcel); private: /** - * Read a NotificationDistributedOptions object from a Parcel. - * @param parcel the parcel + * @brief Read a NotificationDistributedOptions object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel); diff --git a/interfaces/innerkits/ans/native/include/notification_flags.h b/interfaces/innerkits/ans/native/include/notification_flags.h index 5a53ab17880da4802640984ea5c87f9920915ada..a2cc0d56f38301b5d7627971530e37b03c6f0e73 100644 --- a/interfaces/innerkits/ans/native/include/notification_flags.h +++ b/interfaces/innerkits/ans/native/include/notification_flags.h @@ -30,7 +30,7 @@ public: * Default constructor used to create an empty NotificationFlags instance. */ NotificationFlags() = default; - + /** * Default deconstructor used to deconstruct. */ diff --git a/interfaces/innerkits/ans/native/include/notification_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index 7a82980a17566f9428f03ca290bd244a0e03deb4..8ebfb8b8a142425598e8ca96dc4211efe09d96d6 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -30,7 +30,7 @@ namespace Notification { class NotificationHelper { public: /** - * Creates a notification slot. + * @brief Creates a notification slot. * @note You can call the NotificationRequest::SetSlotType(NotificationConstant::SlotType) method to bind the slot * for publishing. A NotificationSlot instance cannot be used directly after being initialized. Instead, you have to * call this method to create a notification slot and bind the slot ID to a NotificationRequest object so that the @@ -45,7 +45,7 @@ public: static ErrCode AddNotificationSlot(const NotificationSlot &slot); /** - * Adds a notification slot by type. + * @brief Adds a notification slot by type. * * @param slotType Indicates the notification slot type to be added. * @return Returns add notification slot result. @@ -53,7 +53,7 @@ public: static ErrCode AddSlotByType(const NotificationConstant::SlotType &slotType); /** - * Creates multiple notification slots. + * @brief Creates multiple notification slots. * * @param slots Indicates the notification slots to create. * @return Returns add notification slots result. @@ -61,7 +61,7 @@ public: static ErrCode AddNotificationSlots(const std::vector &slots); /** - * Deletes a created notification slot based on the slot ID. + * @brief Deletes a created notification slot based on the slot ID. * * @param slotType Indicates the type of the slot, which is created by AddNotificationSlot * This parameter must be specified. @@ -70,14 +70,14 @@ public: static ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType); /** - * Deletes all notification slots. + * @brief Deletes all notification slots. * * @return Returns remove all slots result. */ static ErrCode RemoveAllSlots(); /** - * Queries a created notification slot. + * @brief Queries a created notification slot. * * @param slotType Indicates the ID of the slot, which is created by AddNotificationSlot(NotificationSlot). This * parameter must be specified. @@ -87,14 +87,14 @@ public: static ErrCode GetNotificationSlot(const NotificationConstant::SlotType &slotType, sptr &slot); /** - * Obtains all notification slots of this application. + * @brief Obtains all notification slots of this application. * @param slots Indicates the created NotificationSlot. * @return Returns all notification slots of this application. */ static ErrCode GetNotificationSlots(std::vector> &slots); /** - * Creates a notification slot group to which a NotificationSlot object can be bound by + * @brief Creates a notification slot group to which a NotificationSlot object can be bound by * calling NotificationSlot::SetSlotGroup(string). * @note A NotificationSlotGroup instance cannot be used directly after being initialized. * Instead, you have to call this method to create a notification slot group so that you can bind @@ -108,7 +108,7 @@ public: static ErrCode AddNotificationSlotGroup(const NotificationSlotGroup &slotGroup); /** - * Creates multiple notification slot groups. + * @brief Creates multiple notification slot groups. * @note The precautions for using this method are similar to those for * AddNotificationSlotGroup(NotificationSlotGroup). * @@ -118,7 +118,7 @@ public: static ErrCode AddNotificationSlotGroups(const std::vector &slotGroups); /** - * Deletes a created notification slot group based on the slot group ID. + * @brief Deletes a created notification slot group based on the slot group ID. * * @param slotGroupId Indicates the ID of the notification slot group, which is created by * AddNotificationSlotGroup(NotificationSlotGroup) This parameter must be specified. @@ -127,16 +127,16 @@ public: static ErrCode RemoveNotificationSlotGroup(const std::string &slotGroupId); /** - * Queries a created notification slot group. + * @brief Queries a created notification slot group. * - * @param groupId Indicates the ID of the slot group. - * @param group Indicates the created NotificationSlotGroup. + * @param groupId Indicates the ID of the slot group. + * @param group Indicates the created NotificationSlotGroup. * @return Returns get notification slot group result. */ static ErrCode GetNotificationSlotGroup(const std::string &groupId, sptr &group); /** - * Obtains a list of created notification slot groups. + * @brief Obtains a list of created notification slot groups. * * @param groups Indicates a list of created notification slot groups. * @return Returns get notification slot groups result. @@ -144,16 +144,16 @@ public: static ErrCode GetNotificationSlotGroups(std::vector> &groups); /** - * Obtains number of slot. + * @brief Obtains number of slot. * * @param bundleOption Indicates the bundle name and uid of the application. * @param num Indicates number of slot. * @return Returns get slot number by bundle result. */ - static ErrCode GetNotificationSlotNumAsBundle(const NotificationBundleOption &bundleOption, int &num); + static ErrCode GetNotificationSlotNumAsBundle(const NotificationBundleOption &bundleOption, uint64_t &num); /** - * Publishes a notification. + * @brief Publishes a notification. * @note If a notification with the same ID has been published by the current application and has not been deleted, * this method will update the notification. * @@ -164,7 +164,7 @@ public: static ErrCode PublishNotification(const NotificationRequest &request); /** - * Publishes a notification with a specified label. + * @brief Publishes a notification with a specified label. * @note If a notification with the same ID has been published by the current application and has not been deleted, * this method will update the notification. * @@ -176,7 +176,7 @@ public: static ErrCode PublishNotification(const std::string &label, const NotificationRequest &request); /** - * Publishes a notification on a specified remote device. + * @brief Publishes a notification on a specified remote device. * @note If a notification with the same ID has been published by the current application and has not been deleted, * this method will update the notification. * @@ -189,7 +189,7 @@ public: static ErrCode PublishNotification(const NotificationRequest &request, const std::string &deviceId); /** - * Cancels a published notification. + * @brief Cancels a published notification. * * @param notificationId Indicates the unique notification ID in the application. * The value must be the ID of a published notification. @@ -199,7 +199,7 @@ public: static ErrCode CancelNotification(int32_t notificationId); /** - * Cancels a published notification matching the specified label and notificationId. + * @brief Cancels a published notification matching the specified label and notificationId. * * @param label Indicates the label of the notification to cancel. * @param notificationId Indicates the ID of the notification to cancel. @@ -208,29 +208,43 @@ public: static ErrCode CancelNotification(const std::string &label, int32_t notificationId); /** - * Cancels all the published notifications. + * @brief Cancels all the published notifications. + * * @note To cancel a specified notification, see CancelNotification(int_32). * @return Returns cancel all notifications result. */ static ErrCode CancelAllNotifications(); /** - * Obtains the number of active notifications of the current application in the system. + * @brief Cancels a published agent notification. + * + * @param notificationId Indicates the unique notification ID in the application. + * The value must be the ID of a published notification. + * Otherwise, this method does not take effect. + * @param representativeBundle Indicates the name of application bundle your application is representing. + * @param userId Indicates the specific user. + * @return Returns cancel notification result. + */ + static ErrCode CancelAsBundle(int32_t notificationId, const std::string &representativeBundle, int32_t userId); + + /** + * @brief Obtains the number of active notifications of the current application in the system. * * @param nums Indicates the number of active notifications of the current application. * @return Returns get active notification nums result. */ - static ErrCode GetActiveNotificationNums(int32_t &num); + static ErrCode GetActiveNotificationNums(uint64_t &num); /** - * Obtains active notifications of the current application in the system. + * @brief Obtains active notifications of the current application in the system. + * * @param request Indicates active NotificationRequest objects of the current application. * @return Returns get active notifications result. */ static ErrCode GetActiveNotifications(std::vector> &request); /** - * Obtains the map for sorting notifications of the current application. + * @brief Obtains the map for sorting notifications of the current application. * * @param sortingMap Indicates the NotificationSortingMap object for the current application. * @return Returns get current app sorting result. @@ -238,7 +252,8 @@ public: static ErrCode GetCurrentAppSorting(sptr &sortingMap); /** - * Allows another application to act as an agent to publish notifications in the name of your application bundle. + * @brief Allows another application to act as an agent to publish notifications in the name of your application + * bundle. * * @param agent Indicates the name of the application bundle that can publish notifications for your application. * @return Returns set notification agent result. @@ -246,7 +261,7 @@ public: static ErrCode SetNotificationAgent(const std::string &agent); /** - * Obtains the name of the application bundle that can publish notifications in the name of your application. + * @brief Obtains the name of the application bundle that can publish notifications in the name of your application. * * @param agent Indicates the name of the application bundle that can publish notifications for your application if * any; returns null otherwise. @@ -255,7 +270,7 @@ public: static ErrCode GetNotificationAgent(std::string &agent); /** - * Checks whether your application has permission to publish notifications by calling + * @brief Checks whether your application has permission to publish notifications by calling * PublishNotificationAsBundle(string, NotificationRequest) in the name of another application indicated by the * given representativeBundle. * @@ -266,7 +281,7 @@ public: static ErrCode CanPublishNotificationAsBundle(const std::string &representativeBundle, bool &canPublish); /** - * Publishes a notification in the name of a specified application bundle. + * @brief Publishes a notification in the name of a specified application bundle. * @note If the notification to be published has the same ID as a published notification that has not been canceled, * the existing notification will be replaced by the new one. * @@ -274,20 +289,21 @@ public: * This parameter must be specified. * @param representativeBundle Indicates the name of the application bundle that allows your application to publish * notifications for it by calling setNotificationAgent. - * @return publish notification as bundle result. + * @return Returns publish notification as bundle result. */ static ErrCode PublishNotificationAsBundle( const std::string &representativeBundle, const NotificationRequest &request); /** - * Sets the number of active notifications of the current application as the number to be displayed on the + * @brief Sets the number of active notifications of the current application as the number to be displayed on the * notification badge. + * * @return Returns set notification badge num result. */ static ErrCode SetNotificationBadgeNum(); /** - * Sets the number to be displayed on the notification badge of the application. + * @brief Sets the number to be displayed on the notification badge of the application. * * @param num Indicates the number to display. A negative number indicates that the badge setting remains unchanged. * The value 0 indicates that no badge is displayed on the application icon. @@ -297,7 +313,7 @@ public: static ErrCode SetNotificationBadgeNum(int32_t num); /** - * Checks whether this application has permission to publish notifications. The caller must have + * @brief Checks whether this application has permission to publish notifications. The caller must have * system permissions to call this method. * * @param allowed True if this application has the permission; returns false otherwise @@ -306,7 +322,7 @@ public: static ErrCode IsAllowedNotify(bool &allowed); /** - * Checks whether this application has permission to publish notifications. + * @brief Checks whether this application has permission to publish notifications. * * @param allowed True if this application has the permission; returns false otherwise * @return Returns is allowed notify result. @@ -314,7 +330,7 @@ public: static ErrCode IsAllowedNotifySelf(bool &allowed); /** - * Allow the current application to publish notifications on a specified device. + * @brief Allow the current application to publish notifications on a specified device. * * @param deviceId Indicates the ID of the device running the application. At present, this parameter can * only be null or an empty string, indicating the current device. @@ -323,33 +339,33 @@ public: static ErrCode RequestEnableNotification(std::string &deviceId); /** - * Checks whether this application is in the suspended state.Applications in this state cannot publish + * @brief Checks whether this application is in the suspended state.Applications in this state cannot publish * notifications. * - * @param suspended True if this application is suspended; returns false otherwise. + * @param suspended True if this application is suspended; false otherwise. * @return Returns are notifications suspended. */ static ErrCode AreNotificationsSuspended(bool &suspended); /** - * Checks whether this application has permission to modify the Do Not Disturb (DND) notification policy. + * @brief Checks whether this application has permission to modify the Do Not Disturb (DND) notification policy. * - * @param hasPermission True if this application is suspended; returns false otherwise. + * @param hasPermission True if this application is suspended; false otherwise. * @return Returns has notification policy access permission. */ static ErrCode HasNotificationPolicyAccessPermission(bool &hasPermission); /** - * Obtains the importance level of this application. + * @brief Obtains the importance level of this application. * - * @param importance the importance level of this application, which can be LEVEL_NONE, + * @param importance Indicates the importance level of this application, which can be LEVEL_NONE, LEVEL_MIN, LEVEL_LOW, LEVEL_DEFAULT, LEVEL_HIGH, or LEVEL_UNDEFINED. * @return Returns get bundle importance result */ static ErrCode GetBundleImportance(NotificationSlot::NotificationLevel &importance); /** - * Subscribes to notifications from all applications. This method can be called only by applications + * @brief Subscribes to notifications from all applications. This method can be called only by applications * with required system permissions. * @note To subscribe to a notification, inherit the {NotificationSubscriber} class, override its * callback methods and create a subscriber. The subscriber will be used as a parameter of this method. @@ -365,7 +381,7 @@ public: static ErrCode SubscribeNotification(const NotificationSubscriber &subscriber); /** - * Subscribes to all notifications based on the filtering criteria. This method can be called only + * @brief Subscribes to all notifications based on the filtering criteria. This method can be called only * by applications with required system permissions. * @note After {subscribeInfo} is specified, a subscriber receives only the notifications that * meet the filter criteria specified by {subscribeInfo}. @@ -385,7 +401,7 @@ public: const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo); /** - * Unsubscribes from all notifications. This method can be called only by applications with required + * @brief Unsubscribes from all notifications. This method can be called only by applications with required * system permissions. * @note Generally, you subscribe to a notification by calling the * {SubscribeNotification(NotificationSubscriber)} method. If you do not want your application @@ -402,7 +418,7 @@ public: static ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber); /** - * Unsubscribes from all notifications based on the filtering criteria. This method can be called + * @brief Unsubscribes from all notifications based on the filtering criteria. This method can be called * only by applications with required system permissions. * @note A subscriber will no longer receive the notifications from specified notification sources. * @@ -415,7 +431,7 @@ public: static ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo); /** - * Removes a specified removable notification of other applications. + * @brief Removes a specified removable notification of other applications. * @note Your application must have platform signature to use this method. * * @param key Indicates the key of the notification to remove. @@ -424,7 +440,7 @@ public: static ErrCode RemoveNotification(const std::string &key); /** - * Removes a specified removable notification of other applications. + * @brief Removes a specified removable notification of other applications. * @note Your application must have platform signature to use this method. * * @param bundleOption Indicates the bundle name and uid of the application whose notifications are to be removed. @@ -436,7 +452,7 @@ public: const NotificationBundleOption &bundleOption, const int32_t notificationId, const std::string &label); /** - * Removes a specified removable notification of other applications. + * @brief Removes a specified removable notification of other applications. * @note Your application must have platform signature to use this method. * * @param bundleOption Indicates the bundle name and uid of the application whose notifications are to be removed. @@ -445,7 +461,7 @@ public: static ErrCode RemoveAllNotifications(const NotificationBundleOption &bundleOption); /** - * Removes all removable notifications of a specified bundle. + * @brief Removes all removable notifications of a specified bundle. * @note Your application must have platform signature to use this method. * * @param bundleOption Indicates the bundle name and uid of the application whose notifications are to be removed. @@ -454,14 +470,14 @@ public: static ErrCode RemoveNotificationsByBundle(const NotificationBundleOption &bundleOption); /** - * Removes all removable notifications in the system. + * @brief Removes all removable notifications in the system. * @note Your application must have platform signature to use this method. * @return Returns remove notifications result. */ static ErrCode RemoveNotifications(); /** - * Returns all notification slots belonging to the specified bundle. + * @brief Obtains all notification slots belonging to the specified bundle. * * @param bundleOption Indicates the bundle name and uid of the application. * @param slots Indicates a list of notification slots. @@ -471,7 +487,7 @@ public: const NotificationBundleOption &bundleOption, std::vector> &slots); /** - * Update all notification slots for the specified bundle. + * @brief Update all notification slots for the specified bundle. * * @param bundleOption Indicates the bundle name and uid of the application. * @param slots Indicates a list of new notification slots. @@ -481,7 +497,7 @@ public: const NotificationBundleOption &bundleOption, const std::vector> &slots); /** - * Update all notification slot groups for the specified bundle. + * @brief Update all notification slot groups for the specified bundle. * * @param bundleOption Indicates the bundle name and uid of the application. * @param groups Indicates a list of new notification slot groups. @@ -491,7 +507,7 @@ public: const NotificationBundleOption &bundleOption, const std::vector> &groups); /** - * Obtains all active notifications in the current system. The caller must have system permissions to + * @brief Obtains all active notifications in the current system. The caller must have system permissions to * call this method. * * @param notification Indicates all active notifications of this application. @@ -500,31 +516,32 @@ public: static ErrCode GetAllActiveNotifications(std::vector> ¬ification); /** - * Obtains the active notifications corresponding to the specified key in the system. To call this method + * @brief Obtains the active notifications corresponding to the specified key in the system. To call this method * to obtain particular active notifications, you must have received the notifications and obtained the key * via {Notification::GetKey()}. * * @param key Indicates the key array for querying corresponding active notifications. * If this parameter is null, this method returns all active notifications in the system. - * @return Returns the set of active notifications corresponding to the specified key. + * @param notification Indicates the set of active notifications corresponding to the specified key. + * @return Returns get all active notifications. */ static ErrCode GetAllActiveNotifications( const std::vector key, std::vector> ¬ification); /** - * Checks whether a specified application has the permission to publish notifications. If bundle specifies + * @brief Checks whether a specified application has the permission to publish notifications. If bundle specifies * the current application, no permission is required for calling this method. If bundle specifies another * application, the caller must have system permissions. * * @param bundleOption Indicates the bundle name and uid of the application. - * @param allowed True if the application has permissions; returns false otherwise. + * @param allowed True if the application has permissions; false otherwise. * @return Returns is allowed notify result. */ static ErrCode IsAllowedNotify(const NotificationBundleOption &bundleOption, bool &allowed); /** - * Sets whether to allow all applications to publish notifications on a specified device. The caller must have - * system permissions to call this method. + * @brief Sets whether to allow all applications to publish notifications on a specified device. The caller must + * have system permissions to call this method. * * @param deviceId Indicates the ID of the device running the application. At present, this parameter can only * be null or an empty string, indicating the current device. @@ -536,20 +553,20 @@ public: static ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled); /** - * Sets whether to allow the current application to publish notifications on a specified device. The caller + * @brief Sets whether to allow the current application to publish notifications on a specified device. The caller * must have system permissions to call this method. * * @param deviceId Indicates the ID of the device running the application. At present, this parameter can * only be null or an empty string, indicating the current device. * @param enabled Specifies whether to allow the current application to publish notifications. The value * true indicates that notifications are allowed, and the value false indicates that - * notifications are not allowed. + * notifications are not allowed. * @return Returns set notifications enabled for default bundle result. */ static ErrCode SetNotificationsEnabledForDefaultBundle(const std::string &deviceId, bool enabled); /** - * Sets whether to allow a specified application to publish notifications on a specified device. The caller + * @brief Sets whether to allow a specified application to publish notifications on a specified device. The caller * must have system permissions to call this method. * * @param bundleOption Indicates the bundle name and uid of the application. @@ -564,7 +581,7 @@ public: const NotificationBundleOption &bundleOption, std::string &deviceId, bool enabled); /** - * Sets whether to allow a specified application to show badge. + * @brief Sets whether to allow a specified application to show badge. * * @param bundleOption Indicates the bundle name and uid of the application. * @param enabled Specifies whether to allow the given application to show badge. @@ -573,7 +590,7 @@ public: static ErrCode SetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool enabled); /** - * Obtains the flag that whether to allow a specified application to show badge. + * @brief Obtains the flag that whether to allow a specified application to show badge. * * @param bundleOption Indicates the bundle name and uid of the application. * @param enabled Specifies whether to allow the given application to show badge. @@ -582,7 +599,7 @@ public: static ErrCode GetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool &enabled); /** - * Obtains the flag that whether to allow the current application to show badge. + * @brief Obtains the flag that whether to allow the current application to show badge. * * @param enabled Specifies whether to allow the given application to show badge. * @return Returns get result. @@ -590,24 +607,24 @@ public: static ErrCode GetShowBadgeEnabled(bool &enabled); /** - * Cancel the notification of the specified group of this application. + * @brief Cancel the notification of the specified group of this application. * - * @param groupName the specified group name. + * @param groupName Indicates the specified group name. * @return Returns cancel group result. */ static ErrCode CancelGroup(const std::string &groupName); /** - * Remove the notification of the specified group of the specified application. + * @brief Remove the notification of the specified group of the specified application. * * @param bundleOption Indicates the bundle name and uid of the specified application. - * @param groupName the specified group name. + * @param groupName Indicates the specified group name. * @return Returns remove group by bundle result. */ static ErrCode RemoveGroupByBundle(const NotificationBundleOption &bundleOption, const std::string &groupName); /** - * Sets the do not disturb time. + * @brief Sets the do not disturb time. * @note Your application must have system signature to call this method. * * @param doNotDisturbDate Indicates the do not disturb time to set. @@ -616,7 +633,7 @@ public: static ErrCode SetDoNotDisturbDate(const NotificationDoNotDisturbDate &doNotDisturbDate); /** - * Obtains the do not disturb time. + * @brief Obtains the do not disturb time. * @note Your application must have system signature to call this method. * * @param doNotDisturbDate Indicates the do not disturb time to get. @@ -625,7 +642,7 @@ public: static ErrCode GetDoNotDisturbDate(NotificationDoNotDisturbDate &doNotDisturbDate); /** - * Obtains the flag that whether to support do not disturb mode. + * @brief Obtains the flag that whether to support do not disturb mode. * * @param doesSupport Specifies whether to support do not disturb mode. * @return Returns check result. @@ -633,7 +650,7 @@ public: static ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); /** - * Check if the device supports distributed notification. + * @brief Check if the device supports distributed notification. * * @param enabled True if the device supports distributed notification; false otherwise. * @return Returns is distributed enabled result. @@ -641,7 +658,7 @@ public: static ErrCode IsDistributedEnabled(bool &enabled); /** - * Set whether the device supports distributed notifications. + * @brief Set whether the device supports distributed notifications. * * @param enable Specifies whether to enable the device to support distributed notification. * The value true indicates that the device is enabled to support distributed notifications, and @@ -651,7 +668,7 @@ public: static ErrCode EnableDistributed(const bool enabled); /** - * Set whether an application supports distributed notifications. + * @brief Set whether an application supports distributed notifications. * * @param bundleOption Indicates the bundle name and uid of an application. * @param enabled Specifies whether to enable an application to support distributed notification. @@ -663,7 +680,7 @@ public: static ErrCode EnableDistributedByBundle(const NotificationBundleOption &bundleOption, const bool enabled); /** - * Set whether this application supports distributed notifications. + * @brief Set whether this application supports distributed notifications. * * @param enabled Specifies whether to enable this application to support distributed notification. * The value true indicates that this application is enabled to support distributed notifications, @@ -674,7 +691,7 @@ public: static ErrCode EnableDistributedSelf(const bool enabled); /** - * Check whether an application supports distributed notifications. + * @brief Check whether an application supports distributed notifications. * * @param bundleOption Indicates the bundle name and uid of an application. * @param enabled True if the application supports distributed notification; false otherwise. @@ -683,7 +700,7 @@ public: static ErrCode IsDistributedEnableByBundle(const NotificationBundleOption &bundleOption, bool &enabled); /** - * Obtains the device remind type. + * @brief Obtains the device remind type. * @note Your application must have system signature to call this method. * * @param remindType Indicates the device remind type to get. @@ -692,7 +709,7 @@ public: static ErrCode GetDeviceRemindType(NotificationConstant::RemindType &remindType); /** - * Publishes a continuous task notification. + * @brief Publishes a continuous task notification. * @param request Indicates the NotificationRequest object for setting the notification content. * This parameter must be specified. * @return Returns publish continuous task notification result. @@ -700,7 +717,7 @@ public: static ErrCode PublishContinuousTaskNotification(const NotificationRequest &request); /** - * Cancels a published continuous task notification matching the specified label and notificationId. + * @brief Cancels a published continuous task notification matching the specified label and notificationId. * * @param label Indicates the label of the continuous task notification to cancel. * @param notificationId Indicates the ID of the continuous task notification to cancel. @@ -709,24 +726,24 @@ public: static ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId); /** - * Obtains whether the template is supported by the system. + * @brief Obtains whether the template is supported by the system. * - * @param support whether is it a system supported template. + * @param support Indicates whether is it a system supported template. * @return Returns check result. */ static ErrCode IsSupportTemplate(const std::string &templateName, bool &support); - + /** - * Checks whether this application has permission to publish notifications under the user. + * @brief Checks whether this application has permission to publish notifications under the user. * * @param userId Indicates the userId of the application. - * @param allowed True if the application has permissions; returns false otherwise. + * @param allowed True if the application has permissions; false otherwise. * @return Returns get allowed result. */ static ErrCode IsAllowedNotify(const int32_t &userId, bool &allowed); /** - * Sets whether to allow all applications to publish notifications on a specified user. + * @brief Sets whether to allow all applications to publish notifications on a specified user. * The caller must have system permissions to call this method. * * @param userId Indicates the ID of the user running the application. @@ -738,7 +755,7 @@ public: static ErrCode SetNotificationsEnabledForAllBundles(const int32_t &userId, bool enabled); /** - * Removes notifications under specified user. + * @brief Removes notifications under specified user. * @note Your application must have platform signature to use this method. * * @param userId Indicates the ID of user whose notifications are to be removed. @@ -747,7 +764,7 @@ public: static ErrCode RemoveNotifications(const int32_t &userId); /** - * Sets the do not disturb time on a specified user. + * @brief Sets the do not disturb time on a specified user. * @note Your application must have system signature to call this method. * * @param userId Indicates the specific user. @@ -757,7 +774,7 @@ public: static ErrCode SetDoNotDisturbDate(const int32_t &userId, const NotificationDoNotDisturbDate &doNotDisturbDate); /** - * Obtains the do not disturb time on a specified user. + * @brief Obtains the do not disturb time on a specified user. * @note Your application must have system signature to call this method. * * @param userId Indicates the specific user. @@ -765,6 +782,28 @@ public: * @return Returns set do not disturb time result. */ static ErrCode GetDoNotDisturbDate(const int32_t &userId, NotificationDoNotDisturbDate &doNotDisturbDate); + + /** + * Set whether the application slot is enabled. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param slotType Indicates type of slot. + * @param enabled the type of slot enabled. + * @return Returns get slot number by bundle result. + */ + static ErrCode SetEnabledForBundleSlot( + const NotificationBundleOption &bundleOption, const NotificationConstant::SlotType &slotType, bool enabled); + + /** + * Obtains whether the application slot is enabled. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param slotType Indicates type of slot. + * @param enabled the type of slot enabled to get. + * @return Returns get slot number by bundle result. + */ + static ErrCode GetEnabledForBundleSlot( + const NotificationBundleOption &bundleOption, const NotificationConstant::SlotType &slotType, bool &enabled); }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_json_convert.h b/interfaces/innerkits/ans/native/include/notification_json_convert.h index 2a6fb1683bcc312619b78acd7ee8851049432dd2..77720da48fdd7da7bd8f76e6fcf912fc9a988ca6 100644 --- a/interfaces/innerkits/ans/native/include/notification_json_convert.h +++ b/interfaces/innerkits/ans/native/include/notification_json_convert.h @@ -23,20 +23,26 @@ namespace OHOS { namespace Notification { class NotificationJsonConvertionBase { public: - /** - * Default deconstructor used to deconstruct. - */ virtual ~NotificationJsonConvertionBase() = default; + /** + * @brief Converts NotificationJsonConvertionBase object to json object. + * + * @param jsonObject Indicates the json object. + */ virtual bool ToJson(nlohmann::json &jsonObject) const = 0; }; class NotificationJsonConverter { public: /** - * Convert NotificationJsonConvertionBase object to json object. + * @brief Converts NotificationJsonConvertionBase object to json object. + * + * @param convertionBase Indicates the NotificationJsonConvertionBase object. + * @param jsonObject Indicates the json object. + * @return Returns true if the conversion is successful; returns false otherwise. */ - static bool ConvertToJosn(const NotificationJsonConvertionBase *convertionBase, nlohmann::json &jsonObject) + static bool ConvertToJson(const NotificationJsonConvertionBase *convertionBase, nlohmann::json &jsonObject) { if (convertionBase == nullptr) { ANS_LOGE("Converter : Invalid base object"); @@ -46,7 +52,14 @@ public: return convertionBase->ToJson(jsonObject); } - static bool ConvertToJosnString(const NotificationJsonConvertionBase *convertionBase, std::string &jsonString) + /** + * @brief Converts NotificationJsonConvertionBase object to json string. + * + * @param convertionBase Indicates the NotificationJsonConvertionBase object. + * @param jsonString Indicates the json string. + * @return Returns true if the conversion is successful; returns false otherwise. + */ + static bool ConvertToJsonString(const NotificationJsonConvertionBase *convertionBase, std::string &jsonString) { if (convertionBase == nullptr) { ANS_LOGE("Converter : Invalid base object"); @@ -63,8 +76,14 @@ public: return true; } + /** + * @brief Converts json object to a subclass object whose base class is NotificationJsonConvertionBase. + * + * @param jsonObject Indicates the json object. + * @return Returns the subclass object. + */ template - static T *ConvertFromJosn(const nlohmann::json &jsonObject) + static T *ConvertFromJson(const nlohmann::json &jsonObject) { if (jsonObject.is_null() or !jsonObject.is_object()) { ANS_LOGE("Converter : Invalid JSON object"); @@ -74,8 +93,14 @@ public: return T::FromJson(jsonObject); } + /** + * @brief Converts json string to a subclass object whose base class is NotificationJsonConvertionBase. + * + * @param jsonString Indicates the json string. + * @return Returns the subclass object. + */ template - static T *ConvertFromJosnString(const std::string &jsonString) + static T *ConvertFromJsonString(const std::string &jsonString) { if (jsonString.empty()) { ANS_LOGE("Converter : Invalid JSON string"); diff --git a/interfaces/innerkits/ans/native/include/notification_long_text_content.h b/interfaces/innerkits/ans/native/include/notification_long_text_content.h index 85d50017f84f8e10d128657851d052742b5bbabd..e98b0af5aef11b6a7c0c118a63d70c8bef74f0a9 100644 --- a/interfaces/innerkits/ans/native/include/notification_long_text_content.h +++ b/interfaces/innerkits/ans/native/include/notification_long_text_content.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -23,104 +23,116 @@ namespace OHOS { namespace Notification { class NotificationLongTextContent : public NotificationBasicContent { public: - /** - * Default constructor used to create a NotificationLongTextContent instance. - */ NotificationLongTextContent() = default; /** - * A constructor used to create a NotificationLongTextContent instance with the input parameter longText passed. + * @brief A constructor used to create a NotificationLongTextContent instance with the input parameter longText + * passed. + * * @param longText Indicates the long text to be included. The value contains a maximum of 1024 characters. */ explicit NotificationLongTextContent(const std::string &longText); - /** - * Default deconstructor used to deconstruct. - */ ~NotificationLongTextContent() = default; /** - * Sets the title to be displayed when this long text notification is expanded. After this title is set, + * @brief Sets the title to be displayed when this long text notification is expanded. After this title is set, * the title set by setTitle(string) will be displayed only when this notification is in the collapsed state. + * * @param exTitle Indicates the title to be displayed when this notification is expanded. */ void SetExpandedTitle(const std::string &exTitle); /** - * Obtains the title that will be displayed for this long text notification when it is expanded. - * @return the title to be displayed when this notification is expanded. + * @brief Obtains the title that will be displayed for this long text notification when it is expanded. + * + * @return Returns the title to be displayed when this notification is expanded. */ std::string GetExpandedTitle() const; /** - * Sets the brief text to be included in a long text notification. + * @brief Sets the brief text to be included in a long text notification. * The brief text is a summary of a long text notification and is displayed in the first line of the notification. * Similar to setAdditionalText(string), the font of the brief text is also smaller than the notification text. * The positions where the brief text and additional text will display may conflict. * If both texts are set, only the additional text will be displayed. + * * @param briefText Indicates the brief text to be included. */ void SetBriefText(const std::string &briefText); /** - * Obtains the brief text of a long text notification specified by calling the setBriefText(string) method. - * @return the brief text of the long text notification. + * @brief Obtains the brief text of a long text notification specified by calling the setBriefText(string) method. + * + * @return Returns the brief text of the long text notification. */ std::string GetBriefText() const; /** - * Sets the long text to be included in a long text notification. + * @brief Sets the long text to be included in a long text notification. + * * @param longText Indicates the long text to be included. The value contains a maximum of 1024 characters. */ void SetLongText(const std::string &longText); /** - * Obtains a notification's long text, which is set by calling the setLongText(string) method. - * @return the long text. + * @brief Obtains a notification's long text, which is set by calling the setLongText(string) method. + * + * @return Returns the long text. */ std::string GetLongText() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump() override; /** - * Converts a NotificationLongTextContent object into a Json. + * @brief Converts a NotificationLongTextContent object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationLongTextContent object from a Json. + * @brief Creates a NotificationLongTextContent object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationLongTextContent. + * @return Returns the NotificationLongTextContent. */ static NotificationLongTextContent *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel Indicates the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationLongTextContent + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationLongTextContent object. */ static NotificationLongTextContent *Unmarshalling(Parcel &parcel); protected: /** - * Read a NotificationLongTextContent object from a Parcel. - * @param parcel the parcel + * @brief Read a NotificationLongTextContent object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel) override; private: /** - * the maximum lenth of longtext is 1024 characters. + * the maximum length of longtext is 1024 characters. */ static const std::size_t MAX_LONGTEXT_LENGTH; diff --git a/interfaces/innerkits/ans/native/include/notification_media_content.h b/interfaces/innerkits/ans/native/include/notification_media_content.h index 5044fa89b3206b7065a85fb4e9d0d288523773fd..57e06ae0365d9b2d21e36fae13f83da2174e0a31 100644 --- a/interfaces/innerkits/ans/native/include/notification_media_content.h +++ b/interfaces/innerkits/ans/native/include/notification_media_content.h @@ -25,32 +25,28 @@ class AVToken; class NotificationMediaContent : public NotificationBasicContent { public: - /** - * Default constructor used to create a NotificationMediaContent instance. - */ NotificationMediaContent() = default; - /** - * Default deconstructor used to deconstruct. - */ ~NotificationMediaContent() = default; /** - * Attaches a specified AVToken to this media playback notification. + * @brief Attaches a specified AVToken to this media playback notification. * After an AVToken is attached, this notification can interact with the associated AVSession * so that users can control media playback in this notification. + * * @param avToken Indicates the AVToken to attach. */ void SetAVToken(const std::shared_ptr &avToken); /** - * Obtains the AVToken attached to this media playback notification. - * @return the AVToken attached to this notification. + * @brief Obtains the AVToken attached to this media playback notification. + * + * @return Returns the AVToken that attached to this notification. */ const std::shared_ptr GetAVToken() const; /** - * Sets up to three NotificationActionButton objects to be shown in this media playback notification. + * @brief Sets up to three NotificationActionButton objects to be shown in this media playback notification. * Before publishing this notification, you should also call * NotificationRequest::addActionButton(NotificationActionButton) to add specified NotificationActionButton objects * for this notification so that this method can take effect. The added action buttons will be assigned sequence @@ -58,53 +54,64 @@ public: * must match those assigned to added action buttons. Otherwise, the notification will fail to publish. By default, * the sequence number starts from 0. If you want to show three action buttons, the value of actions should be 0, * 1, 2. + * * @param actions Indicates the list of sequence numbers representing the NotificationActionButton objects * to be shown in this notification. */ void SetShownActions(const std::vector &actions); /** - * Obtains the list of sequence numbers representing the NotificationActionButton objects + * @brief Obtains the list of sequence numbers representing the NotificationActionButton objects * to be shown in this media playback notification. - * @return the list of the action buttons to be shown. + * + * @return Returns the list of the action buttons to be shown. */ std::vector GetShownActions() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump() override; /** - * Converts a NotificationMediaContent object into a Json. + * @brief Converts a NotificationMediaContent object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ virtual bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationMediaContent object from a Json. + * @brief Creates a NotificationMediaContent object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationMediaContent. + * @return Returns the NotificationMediaContent object. */ static NotificationMediaContent *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * @param parcel the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationMediaContent + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationMediaContent object. */ static NotificationMediaContent *Unmarshalling(Parcel &parcel); protected: /** - * Read a NotificationMediaContent object from a Parcel. - * @param parcel the parcel + * @brief Read a NotificationMediaContent object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel) override; diff --git a/interfaces/innerkits/ans/native/include/notification_multiline_content.h b/interfaces/innerkits/ans/native/include/notification_multiline_content.h index 7f0e91655289d225592102ec49b8f7aab7f5eeef..61daf92f37476c14b8199cb48bfe7bd968f11808 100644 --- a/interfaces/innerkits/ans/native/include/notification_multiline_content.h +++ b/interfaces/innerkits/ans/native/include/notification_multiline_content.h @@ -23,95 +23,105 @@ namespace OHOS { namespace Notification { class NotificationMultiLineContent : public NotificationBasicContent { public: - /** - * Default constructor used to create a NotificationMultiLineContent instance. - */ NotificationMultiLineContent() = default; - /** - * Default deconstructor used to deconstruct. - */ ~NotificationMultiLineContent() = default; /** - * Sets the title to be displayed when this multi-line notification is expanded. + * @brief Sets the title to be displayed when this multi-line notification is expanded. * After this title is set, the title set by setTitle(string) will be displayed only * when this notification is in the collapsed state. + * * @param exTitle Indicates the title to be displayed when this notification is expanded. */ void SetExpandedTitle(const std::string &exTitle); /** - * Obtains the title that will be displayed for this multi-line notification when it is expanded. - * @return the title to be displayed when this notification is expanded. + * @brief Obtains the title that will be displayed for this multi-line notification when it is expanded. + * + * @return Returns the title to be displayed when this notification is expanded. */ std::string GetExpandedTitle() const; /** - * Sets the brief text to be included in a multi-line notification. + * @brief Sets the brief text to be included in a multi-line notification. * The brief text is a summary of this multi-line notification and is displayed in the first line of * the notification. Similar to setAdditionalText(string), the font of the brief text is also * smaller than the notification text set by calling setText(string). * The positions where the brief text and additional text will display may conflict. * If both texts are set, only the additional text will be displayed. + * * @param briefText Indicates the brief text to be included. */ void SetBriefText(const std::string &briefText); /** - * Obtains the brief text that has been set by calling setBriefText(string) for this multi-line notification. - * @return the brief text of this notification. + * @brief Obtains the brief text that has been set by calling setBriefText(string) for this multi-line notification. + * + * @return Returns the brief text of this notification. */ std::string GetBriefText() const; /** - * Adds a single line of text to this notification. + * @brief Adds a single line of text to this notification. * You can call this method up to seven times to add seven lines to a notification. + * * @param oneLine Indicates the single line of text to be included. */ void AddSingleLine(const std::string &oneLine); /** - * Obtains the list of lines included in this multi-line notification. - * @return the list of lines included in this notification. + * @brief Obtains the list of lines included in this multi-line notification. + * + * @return Returns the list of lines included in this notification. */ std::vector GetAllLines() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump() override; /** - * Converts a NotificationMultiLineContent object into a Json. + * @brief Converts a NotificationMultiLineContent object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ virtual bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationMultiLineContent object from a Json. + * @brief Creates a NotificationMultiLineContent object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationMultiLineContent. + * @return Returns the NotificationMultiLineContent object. */ static NotificationMultiLineContent *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationMultiLineContent + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationMultiLineContent object. */ static NotificationMultiLineContent *Unmarshalling(Parcel &parcel); protected: /** - * Read a NotificationMultiLineContent object from a Parcel. - * @param parcel the parcel + * @brief Read a NotificationMultiLineContent object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel) override; diff --git a/interfaces/innerkits/ans/native/include/notification_normal_content.h b/interfaces/innerkits/ans/native/include/notification_normal_content.h index 6bd04ae5760fe620eef0b390e610229eb6da2403..45183b13fa827d3bc98816e72bbca61d576fe5ce 100644 --- a/interfaces/innerkits/ans/native/include/notification_normal_content.h +++ b/interfaces/innerkits/ans/native/include/notification_normal_content.h @@ -23,44 +23,46 @@ namespace OHOS { namespace Notification { class NotificationNormalContent : public NotificationBasicContent { public: - /** - * Default constructor used to create a NotificationNormalContent instance. - */ NotificationNormalContent() = default; - /** - * Default deconstructor used to deconstruct. - */ ~NotificationNormalContent() = default; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump() override; /** - * Converts a NotificationNormalContent object into a Json. + * @brief Converts a NotificationNormalContent object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationNormalContent object from a Json. + * @brief Creates a NotificationNormalContent object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationNormalContent. + * @return Returns the NotificationNormalContent object. */ static NotificationNormalContent *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationNormalContent + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationNormalContent object. */ static NotificationNormalContent *Unmarshalling(Parcel &parcel); }; diff --git a/interfaces/innerkits/ans/native/include/notification_picture_content.h b/interfaces/innerkits/ans/native/include/notification_picture_content.h index 8ed0dc54b0824b45ae92a1c2dbbd0453f8c51366..fe2e21c76488915e74397918d192817f8d0aa98b 100644 --- a/interfaces/innerkits/ans/native/include/notification_picture_content.h +++ b/interfaces/innerkits/ans/native/include/notification_picture_content.h @@ -24,93 +24,104 @@ namespace OHOS { namespace Notification { class NotificationPictureContent : public NotificationBasicContent { public: - /** - * Default constructor used to create an empty NotificationPictureContent instance. - */ NotificationPictureContent() = default; - /** - * Default deconstructor used to deconstruct. - */ ~NotificationPictureContent() = default; /** - * Sets the title to be displayed when this picture-attached notification is expanded. + * @brief Sets the title to be displayed when this picture-attached notification is expanded. * After this title is set, the title set by setTitle(string) will be displayed only * when this notification is in the collapsed state. + * * @param exTitle Indicates the title to be displayed when this notification is expanded. */ void SetExpandedTitle(const std::string &exTitle); /** - * Obtains the title that will be displayed for this picture-attached notification when it is expanded. - * @return the title to be displayed when this notification is expanded. + * @brief Obtains the title that will be displayed for this picture-attached notification when it is expanded. + * + * @return Returns the title to be displayed when this notification is expanded. */ std::string GetExpandedTitle() const; /** - * Sets the brief text to be included in a picture-attached notification. + * @brief Sets the brief text to be included in a picture-attached notification. * The brief text is a summary of a picture-attached notification and is displayed in the first line of the * notification. Similar to setAdditionalText(string), the font of the brief text is also smaller than the * notification text. The positions where the brief text and additional text will display may conflict. If both * texts are set, only the additional text will be displayed. + * * @param briefText Indicates the brief text to be included. */ void SetBriefText(const std::string &briefText); /** - * Obtains the brief text of a picture-attached notification specified by calling the setBriefText(string) method. - * @return the brief text of the picture-attached notification. + * @brief Obtains the brief text of a picture-attached notification specified by calling the setBriefText(string) + * method. + * + * @return Returns the brief text of the picture-attached notification. */ std::string GetBriefText() const; /** - * Sets the picture to be included in a notification. + * @brief Sets the picture to be included in a notification. + * * @param bigPicture Indicates the PixelMap of the picture to be included. */ void SetBigPicture(const std::shared_ptr &bigPicture); /** - * Obtains the PixelMap of the picture specified by calling the setBigPicture(PixelMap) method. - * @return the PixelMap of the picture included in the notification. + * @brief Obtains the PixelMap of the picture specified by calling the setBigPicture(PixelMap) method. + * + * @return Returns the PixelMap of the picture included in the notification. */ const std::shared_ptr GetBigPicture() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump() override; /** - * Converts a NotificationPictureContent object into a Json. + * @brief Converts a NotificationPictureContent object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ virtual bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationPictureContent object from a Json. + * @brief Creates a NotificationPictureContent object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationPictureContent. + * @return Returns the NotificationPictureContent object. */ static NotificationPictureContent *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationPictureContent + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationPictureContent object. */ static NotificationPictureContent *Unmarshalling(Parcel &parcel); protected: /** - * Read a NotificationPictureContent object from a Parcel. - * @param parcel the parcel + * @brief Read a NotificationPictureContent object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel) override; diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index 85de466d8dffa5e24eedce9f936bbefd8a21210d..b4a2737f00e7ff549d30dedab2d777f8ec00e13a 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -24,10 +24,10 @@ #include "notification_flags.h" #include "notification_json_convert.h" #include "notification_template.h" -#include "ohos/aafwk/content/want_params.h" #include "parcel.h" #include "pixel_map.h" #include "want_agent.h" +#include "want_params.h" namespace OHOS { namespace Notification { @@ -139,234 +139,266 @@ public: static const uint32_t COLOR_DEFAULT; public: - /** - * Default constructor used to create a NotificationRequest instance. - */ NotificationRequest() = default; /** - * A constructor used to create a NotificationRequest instance with the input parameter notificationId passed. - * @param notificationId notification ID + * @brief A constructor used to create a NotificationRequest instance with the input parameter notificationId + * passed. + * + * @param notificationId Indicates notification ID. */ explicit NotificationRequest(int32_t notificationId); /** - * A constructor used to create a NotificationRequest instance by copying parameters from an existing one. - * @param other the existing object + * @brief A constructor used to create a NotificationRequest instance by copying parameters from an existing one. + * + * @param other Indicates the existing object. */ NotificationRequest(const NotificationRequest &other); /** - * A constructor used to create a NotificationRequest instance by copying parameters from an existing one. - * @param other the existing object + * @brief A constructor used to create a NotificationRequest instance by copying parameters from an existing one. + * + * @param other Indicates the existing object. */ NotificationRequest &operator=(const NotificationRequest &other); - /** - * Default deconstructor used to deconstruct. - */ virtual ~NotificationRequest(); /** - * Checks whether this notification is in progress. - * @return true if this notification is in progress; returns false otherwise. + * @brief Checks whether this notification is in progress. + * + * @return Returns true if this notification is in progress; returns false otherwise. */ bool IsInProgress() const; /** - * Sets whether this notification is in progress. + * @brief Sets whether this notification is in progress. * Users cannot directly dismiss notifications in progress because * they usually contain some ongoing background services such as music playback. + * * @param isOngoing Specifies whether this notification is in progress. */ void SetInProgress(bool isOngoing); /** - * Checks whether this notification is unremovable. - * @return true if this notification is unremovable; returns false otherwise. + * @brief Checks whether this notification is unremovable. + * + * @return Returns true if this notification is unremovable; returns false otherwise. */ bool IsUnremovable() const; /** - * Sets whether this notification is unremovable. + * @brief Sets whether this notification is unremovable. * If it is set to be unremovable, it cannot be removed by users. + * * @param isUnremovable Specifies whether this notification is unremovable. */ void SetUnremovable(bool isUnremovable); /** - * Sets the number to be displayed for this notification. + * @brief Sets the number to be displayed for this notification. + * * @param number Indicates the number to set. */ void SetBadgeNumber(int32_t number); /** - * Obtains the number to be displayed for this notification. - * @return the number to be displayed for this notification. + * @brief Obtains the number to be displayed for this notification. + * + * @return Returns the number to be displayed for this notification. */ int32_t GetBadgeNumber() const; /** - * Sets the current notification ID to uniquely identify the notification in the application. + * @brief Sets the current notification ID to uniquely identify the notification in the application. * After a notification is received, its ID is obtained by using the getNotificationId() method. + * * @param notificationId Indicates the ID of the notification to be set. */ void SetNotificationId(int32_t notificationId); /** - * Obtains the notification ID, which is unique in the current application. + * @brief Obtains the notification ID, which is unique in the current application. + * * @return the notification ID. */ int32_t GetNotificationId() const; /** - * Adds an WantAgent to this notification. - * After a notification is tapped, - * subsequent operations such as ability and common events will be triggered as set by WantAgent. + * @brief Adds an WantAgent to this notification. + * After a notification is tapped, subsequent operations such as ability and common events will be triggered as + * set by WantAgent. + * * @param wantAgent Indicates the operation triggered by tapping the notification, which can be set by * WantAgent. */ void SetWantAgent(const std::shared_ptr &wantAgent); /** - * Obtains the WantAgent contained in this notification. - * @return the WantAgent contained in this notification. + * @brief Obtains the WantAgent contained in this notification. + * + * @return Returns the WantAgent contained in this notification. */ const std::shared_ptr GetWantAgent() const; /** - * Sets an WantAgent object that is triggered when the user explicitly removes this notification. + * @brief Sets an WantAgent object that is triggered when the user explicitly removes this notification. + * * @param wantAgent Indicates the WantAgent object to be triggered. */ void SetRemovalWantAgent(const std::shared_ptr &wantAgent); /** - * Obtains the WantAgent object that is triggered when the user explicitly removes this notification. - * @return the WantAgent object to be triggered. + * @brief Obtains the WantAgent object that is triggered when the user explicitly removes this notification. + * + * @return Returns the WantAgent object to be triggered. */ const std::shared_ptr GetRemovalWantAgent() const; /** - * Sets the WantAgent to start when the device is not in use, + * @brief Sets the WantAgent to start when the device is not in use, * instead of showing this notification in the status bar. * When the device is in use, the system UI displays a pop-up notification * instead of starting the WantAgent specified by maxScreenWantAgent. * Your application must have the ohos.permission.USE_WHOLE_SCREEN permission to use this method. + * * @param wantAgent Indicates the WantAgent object containing information about the to-be-started ability that * uses the Page template. */ void SetMaxScreenWantAgent(const std::shared_ptr &wantAgent); /** - * Obtains the full-screen WantAgent set by calling setMaxScreenWantAgent(WantAgent). - * @return the full-screen WantAgent. + * @brief Obtains the full-screen WantAgent set by calling setMaxScreenWantAgent(WantAgent). + * + * @return Returns the full-screen WantAgent. */ const std::shared_ptr GetMaxScreenWantAgent() const; /** - * Sets extra parameters that are stored as key-value pairs for the notification. + * @brief Sets extra parameters that are stored as key-value pairs for the notification. + * * @param extras Indicates the WantParams object containing the extra parameters in key-value pair format. */ void SetAdditionalData(const std::shared_ptr &extras); /** - * Obtains the WantParams object set in the notification. - * @return the WantParams object. + * @brief Obtains the WantParams object set in the notification. + * + * @return Returns the WantParams object. */ const std::shared_ptr GetAdditionalData() const; /** - * Sets the time to deliver a notification. + * @brief Sets the time to deliver a notification. + * * @param deliveryTime Indicates the time in milliseconds. */ void SetDeliveryTime(int64_t deliveryTime); /** - * Obtains the time when a notification is delivered. - * @return the time in milliseconds. + * @brief Obtains the time when a notification is delivered. + * + * @return Returns the time in milliseconds. */ int64_t GetDeliveryTime() const; /** - * Checks whether the notification delivery time is displayed for this notification. - * @return true if the time is displayed; returns false otherwise. + * @brief Checks whether the notification delivery time is displayed for this notification. + * + * @return Returns true if the time is displayed; returns false otherwise. */ bool IsShowDeliveryTime() const; /** - * Sets whether to show the notification delivery time for this notification. + * @brief Sets whether to show the notification delivery time for this notification. * This method is valid only when the notification delivery time has been set by calling setDeliveryTime(int64_t). + * * @param showDeliveryTime Specifies whether to show the notification delivery time. */ void SetShowDeliveryTime(bool showDeliveryTime); /** - * Adds a NotificationActionButton to this notification. + * @brief Adds a NotificationActionButton to this notification. * An operation button is usually placed next to the notification content by the system. * Each action button must contain an icon, a title, and an WantAgent. When a notification is expanded, * a maximum of three action buttons can be displayed from left to right in the order they were added. * When the notification is collapsed, no action buttons will be displayed. + * * @param actionButton Indicates the NotificationActionButton object to add. */ void AddActionButton(const std::shared_ptr &actionButton); /** - * Obtains the list of all NotificationActionButton objects included in this notification. - * @return the list of NotificationActionButton objects. + * @brief Obtains the list of all NotificationActionButton objects included in this notification. + * + * @return Returns the list of NotificationActionButton objects. */ const std::vector> GetActionButtons() const; /** - * Clear the list of all NotificationActionButton objects included in this notification. + * @brief Clear the list of all NotificationActionButton objects included in this notification. */ void ClearActionButtons(); /** - * Checks whether the platform is allowed to generate contextual NotificationActionButton objects for this + * @brief Checks whether the platform is allowed to generate contextual NotificationActionButton objects for this * notification. - * @return true if the platform is allowed to generate contextual NotificationActionButton objects; + * + * @return Returns true if the platform is allowed to generate contextual NotificationActionButton objects; * returns false otherwise. */ bool IsPermitSystemGeneratedContextualActionButtons() const; /** - * Sets whether to allow the platform to generate contextual NotificationActionButton objects for this notification. + * @brief Sets whether to allow the platform to generate contextual NotificationActionButton objects for this + * notification. + * * @param permitted Specifies whether to allow the platform to generate contextual NotificationActionButton objects. * The default value true indicates that the platform is allowed to generate contextual action buttons, * and the value false indicates not. */ void SetPermitSystemGeneratedContextualActionButtons(bool permitted); + bool IsAgentNotification() const; + + void SetIsAgentNotification(bool isAgent); + /** - * Adds a MessageUser object and associates it with this notification. + * @brief Adds a MessageUser object and associates it with this notification. + * * @param messageUser Indicates the MessageUser object to add. */ void AddMessageUser(const std::shared_ptr &messageUser); /** - * Obtains all MessageUser objects associated with this notification. - * @return the list of MessageUser objects associated with this notification. + * @brief Obtains all MessageUser objects associated with this notification. + * + * @return Returns the list of MessageUser objects associated with this notification. */ const std::vector> GetMessageUsers() const; /** - * Checks whether this notification is set to alert only once, + * @brief Checks whether this notification is set to alert only once, * which means that sound or vibration will no longer be played * for notifications with the same ID upon their updates. - * @return true if this notification is set to alert only once; returns false otherwise. + * + * @return Returns true if this notification is set to alert only once; returns false otherwise. */ bool IsAlertOneTime() const; /** - * Sets whether to have this notification alert only once. + * @brief Sets whether to have this notification alert only once. * If a notification alerts only once, sound or vibration will no longer be played * for notifications with the same ID upon their updates after they are published. + * * @param isAlertOnce Specifies whether to have this notification alert only once. */ void SetAlertOneTime(bool isAlertOnce); /** - * Sets the time to delete a notification. + * @brief Sets the time to delete a notification. + * * @param deletedTime Indicates the time in milliseconds. * The default value is 0, indicating that the notification will not be automatically deleted. * To enable the notification to be automatically deleted, set this parameter to an integer greater than 0. @@ -374,98 +406,112 @@ public: void SetAutoDeletedTime(int64_t deletedTime); /** - * Obtains the period during which a notification is deleted. - * @return the period in milliseconds. + * @brief Obtains the period during which a notification is deleted. + * + * @return Returns the period in milliseconds. */ int64_t GetAutoDeletedTime() const; /** - * Sets the little icon of the notification. + * @brief Sets the little icon of the notification. + * * @param littleIcon Indicates the icon of the notification. */ void SetLittleIcon(const std::shared_ptr &littleIcon); /** - * Obtains the icon of the notification. - * @return the notification icon. + * @brief Obtains the icon of the notification. + * + * @return Returns the notification icon. */ const std::shared_ptr GetLittleIcon() const; /** - * Sets the large icon of this notification, which is usually displayed on the right of the notification. + * @brief Sets the large icon of this notification, which is usually displayed on the right of the notification. + * * @param bigIcon Indicates the large icon to set. It must be a PixelMap object. */ void SetBigIcon(const std::shared_ptr &bigIcon); /** - * Obtains the large icon of this notification. - * @return the large icon of this notification. + * @brief Obtains the large icon of this notification. + * + * @return Returns the large icon of this notification. */ const std::shared_ptr GetBigIcon() const; /** - * Sets the classification of this notification, which describes the purpose of this notification. + * @brief Sets the classification of this notification, which describes the purpose of this notification. * Notification classifications are used to filter and sort notifications. + * * @param classification Indicates the notification classification predefined in the system, * such as CLASSIFICATION_CALL or CLASSIFICATION_NAVIGATION etc. */ void SetClassification(const std::string &classification); /** - * Obtains the classification of this notification. - * @return the classification of this notification. + * @brief Obtains the classification of this notification. + * + * @return Returns the classification of this notification. */ std::string GetClassification() const; /** - * Sets the background color of this notification. + * @brief Sets the background color of this notification. * This method is valid only when background color has been enabled by calling setColorEnabled(bool). + * * @param color Indicates the background color to set. For details about the value range, see Color. */ void SetColor(uint32_t color); /** - * Obtains the background color of this notification. + * @brief Obtains the background color of this notification. * The return value, except for the default color COLOR_DEFAULT, * is the bitwise OR operation result of 0xFF000000 and the ARGB value set by setColor(uint32_t). - * @return the background color of this notification. + * + * @return Returns the background color of this notification. */ uint32_t GetColor() const; /** - * Checks whether background color is enabled for this notification. - * @return true if background color is enabled; returns false otherwise. + * @brief Checks whether background color is enabled for this notification. + * + * @return Returns true if background color is enabled; returns false otherwise. */ bool IsColorEnabled() const; /** - * Sets whether to enable background color for this notification. + * @brief Sets whether to enable background color for this notification. * If colorEnabled is set to true, this method takes effect only * when the notification content type has been set to NotificationRequest. * NotificationMediaContent in the NotificationRequest object through * NotificationRequest::setContent(NotificationContent) and an AVToken has been attached to * that NotificationMediaContent object through NotificationMediaContent::setAVToken(AVToken). + * * @param colorEnabled Specifies whether to enable background color. */ void SetColorEnabled(bool colorEnabled); /** - * Sets the notification content type to NotificationNormalContent, NotificationLongTextContent, + * @brief Sets the notification content type to NotificationNormalContent, NotificationLongTextContent, * or NotificationPictureContent etc. * Each content type indicates a particular notification content. + * * @param content Indicates the notification content type. */ void SetContent(const std::shared_ptr &content); /** - * Obtains the notification content set by calling the setContent(NotificationContent) method. - * @return the notification content. + * @brief Obtains the notification content set by calling the setContent(NotificationContent) method. + * + * @return Returns the notification content. */ const std::shared_ptr GetContent() const; /** - * Obtains the notification type. - * @return the type of the current notification, which can be + * @brief Obtains the notification type. + * + * @return Returns the type of the current notification, which can be * NotificationContent::Type::BASIC_TEXT, * NotificationContent::Type::LONG_TEXT, * NotificationContent::Type::PICTURE, @@ -476,52 +522,58 @@ public: NotificationContent::Type GetNotificationType() const; /** - * Checks whether the notification creation time is displayed as a countdown timer. - * @return true if the time is displayed as a countdown timer; returns false otherwise. + * @brief Checks whether the notification creation time is displayed as a countdown timer. + * + * @return Returns true if the time is displayed as a countdown timer; returns false otherwise. */ bool IsCountdownTimer() const; /** - * Sets whether to show the notification creation time as a countdown timer. + * @brief Sets whether to show the notification creation time as a countdown timer. * This method is valid only when setShowStopwatch(boolean) is set to true. + * * @param isCountDown Specifies whether to show the notification creation time as a countdown timer. */ void SetCountdownTimer(bool isCountDown); /** - * Sets the group alert type for this notification, + * @brief Sets the group alert type for this notification, * which determines how the group overview and other notifications in a group are published. * The group information must have been set by calling setGroupValue(string). * Otherwise, this method does not take effect. + * * @param type Indicates the group alert type to set. which can be GroupAlertType::ALL (default value), * GroupAlertType::OVERVIEW, or GroupAlertType::CHILD etc. */ void SetGroupAlertType(NotificationRequest::GroupAlertType type); /** - * Obtains the group alert type of this notification. - * @return the group alert type of this notification. + * @brief Obtains the group alert type of this notification. + * + * @return Returns the group alert type of this notification. */ NotificationRequest::GroupAlertType GetGroupAlertType() const; /** - * Checks whether this notification is the group overview. - * @return true if this notification is the group overview; returns false otherwise. + * @brief Checks whether this notification is the group overview. + * + * @return Returns true if this notification is the group overview; returns false otherwise. */ bool IsGroupOverview() const; /** - * Sets whether to use this notification as the overview of its group. + * @brief Sets whether to use this notification as the overview of its group. * This method helps display the notifications that are assigned the same group name by calling * setGroupName(string) as one stack in the notification bar. * Each group requires only one group overview. After a notification is set as the group overview, * it becomes invisible if another notification in the same group is published. + * * @param overView Specifies whether to set this notification as the group overview. */ void SetGroupOverview(bool overView); /** - * Sets the group information for this notification. + * @brief Sets the group information for this notification. * If no groups are set for notifications, all notifications from the same application will appear * in the notification bar as one stack with the number of stacked notifications displayed. * If notifications are grouped and there are multiple groups identified by different groupName, @@ -530,185 +582,211 @@ public: * setGroupOverview(bool), and other notifications are considered as child notifications. * Otherwise, notifications will not be displayed as one group even if they are assigned the same groupName by * calling setGroupName(string). + * * @param groupName Specifies whether to set this notification as the group overview. */ void SetGroupName(const std::string &groupName); /** - * Obtains the group information about this notification. - * @return the group information about this notification. + * @brief Obtains the group information about this notification. + * + * @return Returns the group information about this notification. */ std::string GetGroupName() const; /** - * Checks whether this notification is relevant only to the local device and cannot be displayed on remote devices. - * @return true if this notification is relevant only to the local device; returns false otherwise. + * @brief Checks whether this notification is relevant only to the local device and cannot be displayed on remote + * devices. + * + * @return Returns true if this notification is relevant only to the local device; returns false otherwise. */ bool IsOnlyLocal() const; /** - * Sets whether this notification is relevant only to the local device and cannot be displayed on remote devices. - * This method takes effect only for notifications published by calling + * @brief Sets whether this notification is relevant only to the local device and cannot be displayed on remote + * devices.This method takes effect only for notifications published by calling * NotificationHelper::publishNotification(NotificationRequest) or * NotificationHelper#publishNotification(string, NotificationRequest). * Notifications published using NotificationHelper::publishNotification(NotificationRequest, string) * in a distributed system will not be affected. + * * @param flag Specifies whether this notification can be displayed only on the local device. */ void SetOnlyLocal(bool flag); /** - * Sets the text that will be displayed as a link to the settings of the application. + * @brief Sets the text that will be displayed as a link to the settings of the application. * Calling this method is invalid if the notification content type has been set to NotificationLongTextContent * or NotificationPictureContent in the NotificationRequest object through setContent(NotificationContent). + * * @param text Indicates the text to be included. You can set it to any valid link. */ void SetSettingsText(const std::string &text); /** - * Obtains the text that will be displayed as a link to the settings of the application. - * @return the text displayed as the link to the application settings. + * @brief Obtains the text that will be displayed as a link to the settings of the application. + * + * @return Returns the text displayed as the link to the application settings. */ std::string GetSettingsText() const; /** - * Deprecated. - * Obtains the time when a notification is created. - * @return the time in milliseconds. + * @brief Deprecated. Obtains the time when a notification is created. + * + * @return Returns the time in milliseconds. */ int64_t GetCreateTime() const; /** - * Checks whether the notification creation time is displayed as a stopwatch. - * @return true if the time is displayed as a stopwatch; returns false otherwise. + * @brief Checks whether the notification creation time is displayed as a stopwatch. + * + * @return Returns true if the time is displayed as a stopwatch; returns false otherwise. */ bool IsShowStopwatch() const; /** - * Sets whether to show the notification creation time as a stopwatch. + * @brief Sets whether to show the notification creation time as a stopwatch. * This method is valid only when the notification creation time has been set by calling setDeliveryTime(int64_t). * When the notification creation time is set to be shown as a stopwatch, the interval between the current time * and the creation time set by setDeliveryTime(int64_t) is dynamically displayed for this notification * in Minutes: Seconds format. If the interval is longer than 60 minutes, it will be displayed * in Hours: Minutes: Seconds format. If this method and setShowDeliveryTime(boolean) are both set to true, only * this method takes effect, that is, the notification creation time will be shown as a stopwatch. + * * @param isShow Specifies whether to show the notification creation time as a stopwatch. */ void SetShowStopwatch(bool isShow); /** - * Sets the slot type of a notification to bind the created NotificationSlot object. + * @brief Sets the slot type of a notification to bind the created NotificationSlot object. * You can use NotificationSlot to create a slot object, * then set the notification vibration and lock screen display, and use the current method to bind the slot. * The value must be the type of an existing NotificationSlot object. + * * @param slotType Indicates the unique type of the NotificationSlot object. */ void SetSlotType(NotificationConstant::SlotType slotType); /** - * Obtains the slot type of a notification set by calling the setSlotType(string) method. - * @return the notification slot type. + * @brief Obtains the slot type of a notification set by calling the setSlotType(string) method. + * + * @return Returns the notification slot type. */ NotificationConstant::SlotType GetSlotType() const; /** - * Sets a key used for sorting notifications from the same application bundle. + * @brief Sets a key used for sorting notifications from the same application bundle. + * * @param key Indicates the key to set. */ void SetSortingKey(const std::string &key); /** - * Obtains the key used for sorting notifications from the same application bundle. - * @return the key for sorting notifications. + * @brief Obtains the key used for sorting notifications from the same application bundle. + * + * @return Returns the key for sorting notifications. */ std::string GetSortingKey() const; /** - * Sets the scrolling text to be displayed in the status bar when this notification is received. + * @brief Sets the scrolling text to be displayed in the status bar when this notification is received. + * * @param text Indicates the scrolling text to be displayed. */ void SetStatusBarText(const std::string &text); /** - * Obtains the scrolling text that will be displayed in the status bar when this notification is received. - * @return the scrolling notification text. + * @brief Obtains the scrolling text that will be displayed in the status bar when this notification is received. + * + * @return Returns the scrolling notification text. */ std::string GetStatusBarText() const; /** - * Checks whether the current notification will be automatically dismissed after being tapped. - * @return true if the notification will be automatically dismissed; returns false otherwise. + * @brief Checks whether the current notification will be automatically dismissed after being tapped. + * + * @return Returns true if the notification will be automatically dismissed; returns false otherwise. */ bool IsTapDismissed() const; /** - * Sets whether to automatically dismiss a notification after being tapped. + * @brief Sets whether to automatically dismiss a notification after being tapped. * If you set tapDismissed to true, * you must call the setWantAgent(WantAgent) method to make the settings take effect. + * * @param isDismissed Specifies whether a notification will be automatically dismissed after being tapped. */ void SetTapDismissed(bool isDismissed); /** - * Sets the notification display effect, including whether to display this notification on the lock screen, + * @brief Sets the notification display effect, including whether to display this notification on the lock screen, * and how it will be presented if displayed. * For details, see NotificationSlot::setLockscreenVisibleness(int). * If the lock screen display effect is set for a NotificationRequest object * and its associated NotificationSlot object, the display effect set in the NotificationRequest object prevails. + * * @param type Indicates the notification display effect on the lock screen. */ void SetVisibleness(NotificationConstant::VisiblenessType type); /** - * Obtains the display effect of this notification on the lock screen. - * @return the display effect of this notification on the lock screen. + * @brief Obtains the display effect of this notification on the lock screen. + * + * @return Returns the display effect of this notification on the lock screen. */ NotificationConstant::VisiblenessType GetVisibleness() const; /** - * Sets the badge icon style for this notification. + * @brief Sets the badge icon style for this notification. * This method does not take effect if the home screen does not support badge icons. + * * @param style Indicates the type of the badge icon to be displayed for this notification. * The value must be BadgeStyle::NONE, BadgeStyle::LITTLE, or BadgeStyle::BIG. */ void SetBadgeIconStyle(NotificationRequest::BadgeStyle style); /** - * Obtains the badge icon style of this notification. - * @return the badge icon style of this notification. + * @brief Obtains the badge icon style of this notification. + * + * @return Returns the badge icon style of this notification. */ NotificationRequest::BadgeStyle GetBadgeIconStyle() const; /** - * Sets the shortcut ID for this notification. + * @brief Sets the shortcut ID for this notification. * After a shortcut ID is set for a notification, the notification will be associated with the corresponding * home-screen shortcut, and the shortcut will be hidden when the Home application displays the badge or content * of the notification. + * * @param shortcutId Indicates the shortcut ID to set. */ void SetShortcutId(const std::string &shortcutId); /** - * Obtains the shortcut ID associated with this notification. - * @return the shortcut ID of this notification. + * @brief Obtains the shortcut ID associated with this notification. + * + * @return Returns the shortcut ID of this notification. */ std::string GetShortcutId() const; /** - * Sets whether this notification is displayed as a floating icon on top of the screen. + * @brief Sets whether this notification is displayed as a floating icon on top of the screen. + * * @param floatingIcon Specifies whether a notification is displayed as a floating icon on top of the screen. */ void SetFloatingIcon(bool floatingIcon); /** - * Checks whether this notification is displayed as a floating icon on top of the screen. - * @return true if this notification is displayed as a floating icon; returns false otherwise. + * @brief Checks whether this notification is displayed as a floating icon on top of the screen. + * + * @return Returns true if this notification is displayed as a floating icon; returns false otherwise. */ bool IsFloatingIcon() const; /** - * Sets how the progress bar will be displayed for this notification. + * @brief Sets how the progress bar will be displayed for this notification. * A progress bar is usually used in notification scenarios such as download. + * * @param progress Indicates the current value displayed for the notification progress bar. * @param progressMax Indicates the maximum value displayed for the notification progress bar. * @param indeterminate Specifies whether the progress bar is indeterminate. The value true indicates that @@ -717,227 +795,293 @@ public: void SetProgressBar(int32_t progress, int32_t progressMax, bool indeterminate); /** - * Obtains the maximum value displayed for the progress bar of this notification. - * @return the maximum value of the notification progress bar. + * @brief Obtains the maximum value displayed for the progress bar of this notification. + * + * @return Returns the maximum value of the notification progress bar. */ int32_t GetProgressMax() const; /** - * Obtains the current value displayed for the progress bar of this notification. - * @return the current value of the notification progress bar. + * @brief Obtains the current value displayed for the progress bar of this notification. + * + * @return Returns the current value of the notification progress bar. */ int32_t GetProgressValue() const; /** - * Checks whether the progress bar of this notification is indeterminate. - * @return true if the notification progress bar is indeterminate; returns false otherwise. + * @brief Checks whether the progress bar of this notification is indeterminate. + * + * @return Returns true if the notification progress bar is indeterminate; returns false otherwise. */ bool IsProgressIndeterminate() const; /** - * Sets the most recent NotificationUserInput records that have been sent through this notification. + * @brief Sets the most recent NotificationUserInput records that have been sent through this notification. * The most recent input must be stored in index 0, * the second most recent input must be stored in index 1, and so on. * The system displays a maximum of five inputs. + * * @param text Indicates the list of inputs to set. */ void SetNotificationUserInputHistory(const std::vector &text); /** - * Obtains the most recent NotificationUserInput records - * @return the most recent NotificationUserInput records + * @brief Obtains the most recent NotificationUserInput records. + * + * @return Returns the most recent NotificationUserInput records. */ std::vector GetNotificationUserInputHistory() const; /** - * Sets an alternative notification to be displayed on the lock screen for this notification. + * @brief Sets an alternative notification to be displayed on the lock screen for this notification. * The display effect (whether and how this alternative notification will be displayed) is subject to * the configuration in NotificationSlot::setLockscreenVisibleness(int). + * * @param other Indicates the alternative notification to be displayed on the lock screen. */ void SetPublicNotification(const std::shared_ptr &other); /** - * Obtains the alternative notification to be displayed on the lock screen for this notification. - * @return the alternative notification to be displayed on the lock screen for this notification. + * @brief Obtains the alternative notification to be displayed on the lock screen for this notification. + * + * @return Returns the alternative notification to be displayed on the lock screen for this notification. */ const std::shared_ptr GetPublicNotification() const; /** - * Obtains the unique hash code of a notification in the current application. + * @brief Obtains the unique hash code of a notification in the current application. * To obtain a valid hash code, you must have subscribed to and received the notification. * A valid notification hash code is a string composed of multiple attributes separated by an underscore (_), * including the notification ID, creator bundle name, creator UID, and owner bundle name. - * @return the hash code of the notification. + * + * @return Returns the hash code of the notification. */ std::string GetNotificationHashCode() const; /** - * Sets the bundle name of the notification owner. + * @brief Sets the bundle name of the notification owner. * The notification owner refers to the application that subscribes to the notification. - * @param ownerName the bundle name of the notification owner. + * + * @param ownerName Indicates the bundle name of the notification owner. */ void SetOwnerBundleName(const std::string &ownerName); /** - * Obtains the bundle name of the notification owner. + * @brief Obtains the bundle name of the notification owner. * The notification owner refers to the application that subscribes to the notification. - * @return the bundle name of the notification owner. + * + * @return Returns the bundle name of the notification owner. */ std::string GetOwnerBundleName() const; /** - * Sets the bundle name of the notification creator. + * @brief Sets the bundle name of the notification creator. * The notification creator refers to the application that publishes the notification. - * @param creatorName the bundle name of the notification creator. + * + * @param creatorName Indicates the bundle name of the notification creator. */ void SetCreatorBundleName(const std::string &creatorName); /** - * Obtains the bundle name of the notification creator. + * @brief Obtains the bundle name of the notification creator. * The notification creator refers to the application that publishes the notification. - * @return the bundle name of the notification creator. + * + * @return Returns the bundle name of the notification creator. */ std::string GetCreatorBundleName() const; /** - * Sets the PID of the notification creator. - * @param pid the PID of the notification creator. + * @brief Sets the PID of the notification creator. + * + * @param pid Indicates the PID of the notification creator. */ void SetCreatorPid(pid_t pid); /** - * Obtains the PID of the notification creator. - * @return the PID of the notification creator. + * @brief Obtains the PID of the notification creator. + * + * @return Returns the PID of the notification creator. */ pid_t GetCreatorPid() const; /** - * Sets the UID of the notification creator. - * @param uid the UID of the notification creator. + * @brief Sets the UID of the notification creator. + * + * @param uid Indicates the UID of the notification creator. + */ + void SetCreatorUid(int32_t uid); + + /** + * @brief Obtains the UID of the notification creator. + * + * @return Returns the UID of the notification creator. */ - void SetCreatorUid(pid_t uid); + int32_t GetCreatorUid() const; /** - * Obtains the UID of the notification creator. - * @return the UID of the notification creator. + * @brief Sets the UID of the notification owner. + * + * @param uid the UID of the notification owner. */ - pid_t GetCreatorUid() const; + void SetOwnerUid(int32_t uid); /** - * Sets the label of this notification. - * @param label the label of this notification. + * @brief Obtains the UID of the notification owner. + * + * @return the UID of the notification owner. + */ + int32_t GetOwnerUid() const; + + /** + * @brief Sets the label of this notification. + * + * @param label Indicates the label of this notification. */ void SetLabel(const std::string &label); /** - * Obtains the label of this notification. + * @brief Obtains the label of this notification. * The label is set via NotificationHelper::publishNotification(string, NotificationRequest). * This method returns null if no specific label is set for this notification. - * @return the label of this notification. + * + * @return Returns the label of this notification. */ std::string GetLabel() const; /** - * Sets whether this notification is distributed. + * @brief Sets whether this notification is distributed. + * * @param distribute Specifies whether a notification is displayed as a floating icon on top of the screen. */ void SetDistributed(bool distribute); /** - * Sets devices that support display. - * @param devices The devices that support display. + * @brief Sets devices that support display. + * + * @param devices Indicates the devices that support display. */ void SetDevicesSupportDisplay(const std::vector &devices); /** - * Sets devices that support operate. - * @param devices The devices that support operate. + * @brief Sets devices that support operate. + * + * @param devices Indicates the devices that support operate. */ void SetDevicesSupportOperate(const std::vector &devices); /** - * Obtains the distributed Options. - * @return the distributed Options. + * @brief Obtains the distributed Options. + * + * @return Returns the distributed Options. */ NotificationDistributedOptions GetNotificationDistributedOptions() const; /** - * Sets the UserId of the notification creator. - * @param userId the UserId of the notification creator. + * @brief Sets the UserId of the notification creator. + * + * @param userId Indicates the UserId of the notification creator. */ void SetCreatorUserId(int32_t userId); /** - * Obtains the UserId of the notification creator. - * @return the UserId of the notification creator. + * @brief Obtains the UserId of the notification creator. + * + * @return Returns the UserId of the notification creator. */ int32_t GetCreatorUserId() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Sets the UserId of the notification owner. + * + * @param userId the UserId of the notification owner. + */ + void SetOwnerUserId(int32_t userId); + + /** + * @brief Obtains the UserId of the notification owner. + * + * @return the UserId of the notification owner. + */ + int32_t GetOwnerUserId() const; + + /** + * @brief Returns a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump(); /** - * Converts a NotificationRequest object into a Json. + * @brief Converts a NotificationRequest object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationRequest object from a Json. + * @brief Creates a NotificationRequest object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationRequest. + * @return Returns the NotificationRequest. */ static NotificationRequest *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a NotificationRequest object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a NotificationRequest object into a Parcel. + * + * @param parcel Indicates the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationRequest. + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationRequest. */ static NotificationRequest *Unmarshalling(Parcel &parcel); /** - * Sets the template of this notification. - * @param template the template of this notification. + * @brief Sets the template of this notification. + * + * @param template Indicates the template of this notification. */ void SetTemplate(const std::shared_ptr &templ); /** - * Obtains the Template of the notification. - * @return the Template of the notification. + * @brief Obtains the Template of the notification. + * + * @return Returns the Template of the notification. */ std::shared_ptr GetTemplate() const; /** - * Sets the flags of this notification. - * @param flags the flags of this notification. + * @brief Sets the flags of this notification. + * + * @param flags Indicates the flags of this notification. */ void SetFlags(const std::shared_ptr &flags); /** - * Obtains the flags of the notification. - * @return the flags of the notification. + * @brief Obtains the flags of the notification. + * + * @return Returns the flags of the notification. */ std::shared_ptr GetFlags() const; /** - * Sets the UserId of the notification receiver. - * @param userId the UserId of the notification receiver. + * @brief Sets the userId of the notification receiver. + * + * @param userId Indicates the userId of the notification receiver. */ void SetReceiverUserId(int32_t userId); /** - * Obtains the UserId of the notification receiver. - * @return the UserId of the notification receiver. + * @brief Obtains the userId of the notification receiver. + * + * @return Returns the userId of the notification receiver. */ int32_t GetReceiverUserId() const; @@ -959,14 +1103,17 @@ private: private: /** - * Read a NotificationRequest object from a Parcel. - * @param parcel the parcel + * @brief Read a NotificationRequest object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel); /** - * Obtains the current system time in milliseconds. - * @return the current system time in milliseconds. + * @brief Obtains the current system time in milliseconds. + * + * @return Returns the current system time in milliseconds. */ int64_t GetNowSysTime(); @@ -997,8 +1144,10 @@ private: int64_t autoDeletedTime_ {0}; pid_t creatorPid_ {0}; - pid_t creatorUid_ {0}; + int32_t creatorUid_ {0}; + int32_t ownerUid_ {0}; int32_t creatorUserId_ {SUBSCRIBE_USER_INIT}; + int32_t ownerUserId_ {SUBSCRIBE_USER_INIT}; int32_t receiverUserId_ {SUBSCRIBE_USER_INIT}; std::string settingsText_ {}; @@ -1030,6 +1179,7 @@ private: bool floatingIcon_ {false}; bool onlyLocal_ {false}; bool permitted_ {true}; + bool isAgent_ {false}; std::shared_ptr wantAgent_ {}; std::shared_ptr removalWantAgent_ {}; diff --git a/interfaces/innerkits/ans/native/include/notification_slot.h b/interfaces/innerkits/ans/native/include/notification_slot.h index 6b53430328c795c1de165aef9314f7013b12bc71..c4203d8cc6ccccccf2444fe9c1d102879b299e33 100644 --- a/interfaces/innerkits/ans/native/include/notification_slot.h +++ b/interfaces/innerkits/ans/native/include/notification_slot.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -39,19 +39,16 @@ public: }; /** - * A constructor used to initialize the type of a NotificationSlot object. + * @brief A constructor used to initialize the type of a NotificationSlot object. * * @param type Specifies the type of the NotificationSlot object, */ NotificationSlot(NotificationConstant::SlotType type = NotificationConstant::SlotType::CUSTOM); - /** - * Default deconstructor used to deconstruct. - */ ~NotificationSlot(); /** - * Obtains whether the notification light is enabled in a NotificationSlot object, + * @brief Obtains whether the notification light is enabled in a NotificationSlot object, * which is set by SetEnableLight(bool). * * @return Returns true if the notification light is enabled; returns false otherwise. @@ -59,7 +56,7 @@ public: bool CanEnableLight() const; /** - * Specifies whether to enable the notification light when a notification is received on the device, + * @brief Specifies whether to enable the notification light when a notification is received on the device, * provided that this device has a notification light. * @note SetEnableLight must be set before the NotificationHelper:AddNotificationSlot(NotificationSlot) method is * called. Otherwise, the settings will not take effect. @@ -71,7 +68,7 @@ public: void SetEnableLight(bool isLightEnabled); /** - * Obtains the vibration status of a NotificationSlot object, + * @brief Obtains the vibration status of a NotificationSlot object, * which is set by SetEnableVibration(bool). * * @return Returns true if vibration is enabled; returns false otherwise. @@ -79,7 +76,7 @@ public: bool CanVibrate() const; /** - * Sets whether to enable vibration when a notification is received. + * @brief Sets whether to enable vibration when a notification is received. * @note SetEnableVibration(bool) must be set before the NotificationHelper::AddNotificationSlot(NotificationSlot) * method is called. Otherwise, the settings will not take effect. * @@ -89,25 +86,25 @@ public: void SetEnableVibration(bool vibration); /** - * Obtains the description of a NotificationSlot object, which is set by SetDescription(string). + * @brief Obtains the description of a NotificationSlot object, which is set by SetDescription(string). * * @return Returns the description of the NotificationSlot object. */ std::string GetDescription() const; /** - * Sets the description for a NotificationSlot object. + * @brief Sets the description for a NotificationSlot object. * @note The setting of setDescription is effective regardless of whether a NotificationSlot object has been created * by NotificationHelper::AddNotificationSlot(NotificationSlot). * - * @param description Describes the NotificationSlot object. + * @param description describes the NotificationSlot object. * The description is visible to users and its length must not exceed 1000 characters * (the excessive part is automatically truncated). */ void SetDescription(const std::string &description); /** - * Obtains the ID of a NotificationSlot object. + * @brief Obtains the ID of a NotificationSlot object. * * @return Returns the ID of the NotificationSlot object, * which is set by NotificationSlot(string, string, NotificationLevel). @@ -115,7 +112,7 @@ public: std::string GetId() const; /** - * Obtains the color of the notification light in a NotificationSlot object, + * @brief Obtains the color of the notification light in a NotificationSlot object, * which is set by SetLedLightColor(int32_t). * * @return Returns the color of the notification light. @@ -123,7 +120,7 @@ public: int32_t GetLedLightColor() const; /** - * Sets the color of the notification light to flash when a notification is received on the device, + * @brief Sets the color of the notification light to flash when a notification is received on the device, * provided that this device has a notification light and setEnableLight is called with the value true. * @note SetLedLightColor must be set before the NotificationHelper::AddNotificationSlot(NotificationSlot) method is * called. Otherwise, the settings will not take effect. @@ -133,14 +130,14 @@ public: void SetLedLightColor(int32_t color); /** - * Obtains the level of a NotificationSlot object, which is set by SetLevel(NotificationLevel). + * @brief Obtains the level of a NotificationSlot object, which is set by SetLevel(NotificationLevel). * * @return Returns the level of the NotificationSlot object. */ NotificationLevel GetLevel() const; /** - * Sets the level of a NotificationSlot object. + * @brief Sets the level of a NotificationSlot object. * @note SetLevel must be set before the NotificationHelper::AddNotificationSlot(NotificationSlot) method is called. * Otherwise, the settings will not take effect. * @@ -150,14 +147,14 @@ public: void SetLevel(NotificationLevel level); /** - * Obtains the type of a NotificationSlot object, which is set by SetType(SlotType). + * @brief Obtains the type of a NotificationSlot object, which is set by SetType(SlotType). * * @return Returns the Type of the NotificationSlot object. */ NotificationConstant::SlotType GetType() const; /** - * Sets the type of a NotificationSlot object. + * @brief Sets the type of a NotificationSlot object. * @note Settype must be set before the NotificationHelper::AddNotificationSlot(NotificationSlot) method is called. * Otherwise, the settings will not take effect. * @@ -167,7 +164,7 @@ public: void SetType(NotificationConstant::SlotType type); /** - * Obtains the notification display effect of a NotificationSlot object on the lock screen, + * @brief Obtains the notification display effect of a NotificationSlot object on the lock screen, * which is set by SetLockscreenVisibleness(int32_t). * @note This method specifies different effects for displaying notifications on the lock screen in order to protect * user privacy. The setting takes effect only when the lock screen notifications function is enabled for an @@ -178,7 +175,7 @@ public: NotificationConstant::VisiblenessType GetLockScreenVisibleness() const; /** - * Sets whether and how to display notifications on the lock screen. + * @brief Sets whether and how to display notifications on the lock screen. * * @param visibleness Specifies the notification display effect on the lock screen, which can be set to * NO_OVERRIDE, PUBLIC, PRIVATE, or SECRET. @@ -186,14 +183,14 @@ public: void SetLockscreenVisibleness(NotificationConstant::VisiblenessType visibleness); /** - * Obtains the name of a NotificationSlot object. + * @brief Obtains the name of a NotificationSlot object. * * @return Returns the name of the NotificationSlot object, which is set by SetName(string). */ std::string GetName() const; /** - * Obtains the ID of the NotificationSlotGroup object to which this NotificationSlot object belongs, + * @brief Obtains the ID of the NotificationSlotGroup object to which this NotificationSlot object belongs, * which is set by SetSlotGroup(string). * * @return Returns the ID of the NotificationSlotGroup to which this NotificationSlot object belongs. @@ -201,9 +198,10 @@ public: std::string GetSlotGroup() const; /** - * Binds a NotificationSlot object to a specified NotificationSlotGroup. + * @brief Binds a NotificationSlot object to a specified NotificationSlotGroup. * @note SetSlotGroup must be called before the NotificationHelper::AddNotificationSlot(NotificationSlot) method is * called. Otherwise, this method will not take effect. + * * @param groupId Indicates the ID of the NotificationSlotGroup object to bind, * which must have been created by calling * NotificationHelper::AddNotificationSlotGroup(NotificationSlotGroup). @@ -211,14 +209,14 @@ public: void SetSlotGroup(const std::string &groupId); /** - * Obtains the prompt tone of a NotificationSlot object, which is set by SetSound(Uri). + * @brief Obtains the prompt tone of a NotificationSlot object, which is set by SetSound(Uri). * * @return Returns the prompt tone of the NotificationSlot object. */ Uri GetSound() const; /** - * Sets a prompt tone for a NotificationSlot object, which will be played after a notification is received. + * @brief Sets a prompt tone for a NotificationSlot object, which will be played after a notification is received. * @note SetSound must be set before the NotificationHelper:AddNotificationSlot(NotificationSlot) method is called. * Otherwise, the settings will not take effect. * @@ -227,14 +225,14 @@ public: void SetSound(const Uri &sound); /** - * Obtains the vibration style of notifications in this NotificationSlot. + * @brief Obtains the vibration style of notifications in this NotificationSlot. * * @return Returns the vibration style of this NotificationSlot. */ std::vector GetVibrationStyle() const; /** - * Sets the vibration style for notifications in this NotificationSlot. + * @brief Sets the vibration style for notifications in this NotificationSlot. * @note If an empty array or null is passed to this method, the system then calls * SetEnableVibration(bool) with the input parameter set to false. * If a valid value is passed to this method, the system calls SetEnableVibration(bool) with the input @@ -246,7 +244,7 @@ public: void SetVibrationStyle(const std::vector &vibration); /** - * Obtains whether DND mode is bypassed for a NotificationSlot object, + * @brief Obtains whether DND mode is bypassed for a NotificationSlot object, * which is set by EnableBypassDnd(bool). * * @return Returns true if DND mode is bypassed; returns false otherwise. @@ -254,7 +252,7 @@ public: bool IsEnableBypassDnd() const; /** - * Sets whether to bypass Do not disturb (DND) mode in the system. + * @brief Sets whether to bypass Do not disturb (DND) mode in the system. * @note The setting of EnableBypassDnd takes effect only when the Allow interruptions function * is enabled for an application in system notification settings. * @@ -265,7 +263,7 @@ public: void EnableBypassDnd(bool isBypassDnd); /** - * Obtains the application icon badge status of a NotificationSlot object, + * @brief Obtains the application icon badge status of a NotificationSlot object, * which is set by EnableBadge(bool). * * @return Returns true if the application icon badge is enabled; returns false otherwise. @@ -273,7 +271,7 @@ public: bool IsShowBadge() const; /** - * Sets whether to display application icon badges (digits or dots in the corner of the application icon) + * @brief Sets whether to display application icon badges (digits or dots in the corner of the application icon) * on the home screen after a notification is received. * @note EnableBadge must be set before the NotificationHelper:AddNotificationSlot(NotificationSlot) method is * called. Otherwise, the settings will not take effect. @@ -285,14 +283,29 @@ public: void EnableBadge(bool isShowBadge); /** - * Dumps a string representation of the object. + * @brief Set whether the application slot enable. + * @note If the slot enable status is false, the notification cannot be publish. + * + * @param enabled Specifies whether to enable slot. + */ + void SetEnable(bool enabled); + + /** + * @brief Obtains whether the application slot is enabled. + * + * @return Returns true if the slot enabled; returns false otherwise. + */ + bool GetEnable() const; + + /** + * @brief Dumps a string representation of the object. * - * @return A string representation of the object. + * @return Returns a string representation of the object. */ std::string Dump() const; /** - * Marshals a NotificationSlot object into a Parcel. + * @brief Marshals a NotificationSlot object into a Parcel. * * @param parcel Indicates the Parcel object for marshalling. * @return Returns true if the marshalling is successful; returns false otherwise. @@ -300,40 +313,40 @@ public: virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshals a NotificationSlot object from a Parcel. + * @brief Unmarshals a NotificationSlot object from a Parcel. * * @param parcel Indicates the Parcel object for unmarshalling. - * @return Returns true if the unmarshalling is successful; returns false otherwise. + * @return Returns the NotificationSlot object. */ static NotificationSlot *Unmarshalling(Parcel &parcel); private: /** - * Read NotificationSlot object from a Parcel. + * @brief Read NotificationSlot object from a Parcel. * - * @param parcel the parcel - * @return read from parcel success or fail + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel); /** - * Merge the contents of vector and output a string + * @brief Merge the contents of vector and output a string * - * @param mergeVector The vector which will be merged + * @param mergeVector Indicates the vector which will be merged * @return Returns the string that has contents of the vector */ std::string MergeVectorToString(const std::vector &mergeVector) const; /** - * If string length exceed 1000 characters, the excessive part is automatically truncated. + * @brief If string length exceed 1000 characters, the excessive part is automatically truncated. * - * @param in The sting which will be truncated + * @param in Indicates the sting which will be truncated * @return Returns the string that has been truncated. */ std::string TruncateString(const std::string &in); /** - * Sets the name of a NotificationSlot object. + * @brief Sets the name of a NotificationSlot object. * @note The setting of SetName is effective regardless of whether a NotificationSlot object has been created by * NotificationHelper:AddNotificationSlot(NotificationSlot). * @@ -358,11 +371,12 @@ private: std::string groupId_ {}; Uri sound_; std::vector vibrationValues_ {}; + bool enabled_ {true}; // no object in parcel - static constexpr int VALUE_NULL = -1; + static constexpr int32_t VALUE_NULL = -1; // object exist in parcel - static constexpr int VALUE_OBJECT = 1; + static constexpr int32_t VALUE_OBJECT = 1; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_slot_group.h b/interfaces/innerkits/ans/native/include/notification_slot_group.h index 7becacaaef4e782e29809db053c3e68c82b5460e..874f9c9a00abb075d24a34d7cb4e0e49fece3df7 100644 --- a/interfaces/innerkits/ans/native/include/notification_slot_group.h +++ b/interfaces/innerkits/ans/native/include/notification_slot_group.h @@ -24,7 +24,7 @@ class NotificationSlotGroup : public Parcelable { public: /** - * A constructor used to create a NotificationSlotGroup instance with the group ID and name initialized. + * @brief A constructor used to create a NotificationSlotGroup instance with the group ID and name initialized. * * @param id Indicates the ID of the NotificationSlotGroup. * The ID must be unique and its length must not exceed 1000 characters (the excess part is automatically @@ -34,42 +34,41 @@ public: */ NotificationSlotGroup(const std::string &id, const std::string &name); - /** - * Default deconstructor used to deconstruct. - */ ~NotificationSlotGroup(); /** - * Obtains the description of this NotificationSlotGroup object, which is set by SetDescription(string). + * @brief Obtains the description of this NotificationSlotGroup object, which is set by SetDescription(string). * * @return Returns the description of this NotificationSlotGroup. */ std::string GetDescription() const; /** - * Obtains the ID of this NotificationSlotGroup object, which is set by NotificationSlotGroup(string, string). + * @brief Obtains the ID of this NotificationSlotGroup object, which is set by + * NotificationSlotGroup(string, string). * * @return Returns the ID of this NotificationSlotGroup. */ std::string GetId() const; /** - * Obtains the name of this NotificationSlotGroup object, which is set by NotificationSlotGroup(string, string). + * @brief Obtains the name of this NotificationSlotGroup object, which is set by + * NotificationSlotGroup(string, string). * * @return Returns the name of this NotificationSlotGroup. */ std::string GetName() const; /** - * Obtains a list of notification slots bound to this NotificationSlotGroup object. + * @brief Obtains a list of notification slots bound to this NotificationSlotGroup object. * @note NotificationSlot::SetSlotGroup(string) is used to bind a notification slot to a notification slot group. - * @param slots Indicates the slots which to set to the slotgroup. * + * @param slots Indicates the slots which to set to the slotgroup. */ void SetSlots(const std::vector &slots); /** - * Sets a list of notification slots bound to this NotificationSlotGroup object. + * @brief Sets a list of notification slots bound to this NotificationSlotGroup object. * @note NotificationSlot::SetSlotGroup(string) is used to bind a notification slot to a notification slot group. * * @return Returns the list of notification slots bound to this NotificationSlotGroup. @@ -77,29 +76,29 @@ public: std::vector GetSlots() const; /** - * Checks whether this NotificationSlotGroup is disabled. + * @brief Checks whether this NotificationSlotGroup is disabled. * * @return Returns true if this NotificationSlotGroup is disabled; returns false otherwise. */ bool IsDisabled() const; /** - * Sets the description for this NotificationSlotGroup object. + * @brief Sets the description for this NotificationSlotGroup object. * - * @param description Describes this NotificationSlotGroup object. + * @param description describes this NotificationSlotGroup object. * Its length must not exceed 1000 characters (the excess part is automatically truncated). */ void SetDescription(const std::string &description); /** - * Dumps a string representation of the object. + * @brief Dumps a string representation of the object. * - * @return A string representation of the object. + * @return Returns a string representation of the object. */ std::string Dump() const; /** - * Marshals NotificationSlotGroup objects and writes them into Parcel. + * @brief Marshals NotificationSlotGroup objects and writes them into Parcel. * * @param parcel Indicates the Parcel object for marshalling. * @return Returns true if the marshalling is successful; returns false otherwise. @@ -107,33 +106,29 @@ public: virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshals a NotificationSlotGroup object from a Parcel. + * @brief Unmarshals a NotificationSlotGroup object from a Parcel. * * @param parcel Indicates the Parcel object for unmarshalling. - * @return Returns true if the unmarshalling is successful; returns false otherwise. + * @return Returns the NotificationSlotGroup object. */ static NotificationSlotGroup *Unmarshalling(Parcel &parcel); /** - * If string length exceed 1000 characters, the excessive part is automatically truncated. + * @brief If string length exceed 1000 characters, the excessive part is automatically truncated. * - * @param truncatedString The sting which will be truncated + * @param truncatedString Indicates the sting which will be truncated * @return Returns the string that has been truncated. */ std::string TruncateString(const std::string &inPutString); private: - - /** - * Default constructor used to create a NotificationSlotGroup instance. - */ NotificationSlotGroup(); /** - * Read NotificationSlotGroup object from a Parcel. + * @brief Read NotificationSlotGroup object from a Parcel. * - * @param parcel the parcel - * @return read from parcel success or fail + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel); diff --git a/interfaces/innerkits/ans/native/include/notification_sorting.h b/interfaces/innerkits/ans/native/include/notification_sorting.h index ca38d5bb09ccea4d0923959d94e70de2bc0aa396..d904a9475789d8583907a38bce8fda21c552d693 100644 --- a/interfaces/innerkits/ans/native/include/notification_sorting.h +++ b/interfaces/innerkits/ans/native/include/notification_sorting.h @@ -25,14 +25,8 @@ namespace OHOS { namespace Notification { class NotificationSorting final : public Parcelable { public: - /** - * @brief Default constructor used to create an empty NotificationSorting instance. - */ NotificationSorting(); - /** - * @brief Default deconstructor used to deconstruct. - */ ~NotificationSorting(); /** @@ -43,11 +37,11 @@ public: NotificationSorting(const NotificationSorting &sorting); /** - * @brief Obtains the sequence number of a notification among all the active notifications. + * @brief Obtains the sequence number of a notification among all the active notifications. * - * @return Returns the sequence number of the notification. + * @return Returns the sequence number of the notification. */ - inline int32_t GetRanking() const + inline uint64_t GetRanking() const { return ranking_; }; @@ -131,7 +125,6 @@ public: * @brief Marshals a NotificationSorting object into a Parcel. * * @param parcel Indicates the Parcel object for marshalling. - * * @return Returns true if the marshalling is successful; returns false otherwise. */ bool Marshalling(Parcel &parcel) const override; @@ -139,16 +132,15 @@ public: /** * @brief Unmarshals a NotificationSorting object from a Parcel. * - * @param Indicates the Parcel object for unmarshalling. - * - * @return Returns true if the unmarshalling is successful; returns false otherwise. + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns the NotificationSorting object. */ static NotificationSorting *Unmarshalling(Parcel &parcel); /** - * @brief Dump sorting info + * @brief Dumps sorting info * - * @return Sorting info + * @return Returns sorting info. */ std::string Dump() const; @@ -156,7 +148,7 @@ private: void SetGroupKeyOverride(const std::string &str); void SetKey(const std::string &key); void SetImportance(const int32_t &importance); - void SetRanking(const int32_t &ranking); + void SetRanking(const uint64_t &ranking); void SetSlot(const sptr &slot); void SetVisiblenessOverride(const int32_t &visibleness); void SetDisplayBadge(const bool &isDisplayBadge); @@ -165,7 +157,7 @@ private: private: std::string key_ {}; - int32_t ranking_ {-1}; + uint64_t ranking_ {0}; int32_t importance_ {-1}; bool isDisplayBadge_ {true}; bool isHiddenNotification_ {}; diff --git a/interfaces/innerkits/ans/native/include/notification_sorting_map.h b/interfaces/innerkits/ans/native/include/notification_sorting_map.h index cd7d83a1204fca7f1029012bdef80d808e2bd705..8051365b5f6111909c80243cf728c4e2d6643bc3 100644 --- a/interfaces/innerkits/ans/native/include/notification_sorting_map.h +++ b/interfaces/innerkits/ans/native/include/notification_sorting_map.h @@ -23,20 +23,14 @@ namespace OHOS { namespace Notification { class NotificationSortingMap final : public Parcelable { public: - /** - * @brief Default constructor used to create an empty NotificationMap instance. - */ NotificationSortingMap(); - /** - * @brief Default deconstructor used to deconstruct. - */ ~NotificationSortingMap(); /** * @brief A constructor used to create a NotificationSortingMap instance by copying parameters from an existing one. * - * @param Indicates the NotificationSortingMap object. + * @param sortingList Indicates the NotificationSortingMap object. */ NotificationSortingMap(const std::vector &sortingList); @@ -54,9 +48,8 @@ public: * @brief Obtains NotificationSorting based on the hash codes. * * @param key Indicates the hash codes obtained by using getkey(). - * * @param sorting Indicates the sorting information about the hash codes. - * + * @return Returns true if succeed; returns false otherwise. */ bool GetNotificationSorting(const std::string &key, NotificationSorting &sorting) const; @@ -64,7 +57,6 @@ public: * @brief Marshals a NotificationSortingMap object into a Parcel. * * @param parcel Indicates the Parcel object for marshalling. - * * @return Returns true if the marshalling is successful; returns false otherwise. */ bool Marshalling(Parcel &parcel) const override; @@ -72,14 +64,15 @@ public: /** * @brief Unmarshals a NotificationSortingMap object from a Parcel. * - * @param Indicates the Parcel object for unmarshalling. + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns the NotificationSortingMap object. */ static NotificationSortingMap *Unmarshalling(Parcel &parcel); /** - * @brief Dump sorting map info + * @brief Dumps sorting map info * - * @return Return sorting map info to string. + * @return Returns sorting map info to string. */ std::string Dump() const; diff --git a/interfaces/innerkits/ans/native/include/notification_subscribe_info.h b/interfaces/innerkits/ans/native/include/notification_subscribe_info.h index 7da904f412bc51169575290fe6375e245be6b0d2..05c5899729f007308077047d1bc589ea85f55822 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscribe_info.h +++ b/interfaces/innerkits/ans/native/include/notification_subscribe_info.h @@ -22,21 +22,15 @@ namespace OHOS { namespace Notification { class NotificationSubscribeInfo final : public Parcelable { public: - /** - * @brief Default constructor used to create a instance. - */ NotificationSubscribeInfo(); - /** - * @brief Default deconstructor used to deconstruct. - */ ~NotificationSubscribeInfo(); /** * @brief A constructor used to create a NotificationSubscribeInfo instance by copying parameters from an existing * one. * - * @param Indicates the NotificationSubscribeInfo object. + * @param subscribeInfo Indicates the NotificationSubscribeInfo object. */ NotificationSubscribeInfo(const NotificationSubscribeInfo &subscribeInfo); @@ -65,7 +59,7 @@ public: std::vector GetAppNames() const; /** - * @brief application current userid. + * @brief Adds application userid. * * @param appNames Indicates the userid of application. **/ @@ -82,6 +76,7 @@ public: * @brief Marshals a NotificationSubscribeInfo object into a Parcel. * * @param parcel Indicates the Parcel object for marshalling. + * @return Returns true if the marshalling is successful; returns false otherwise. */ bool Marshalling(Parcel &parcel) const override; @@ -89,13 +84,14 @@ public: * @brief Unmarshals a NotificationSubscribeInfo object from a Parcel. * * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns the NotificationSubscribeInfo object. */ static NotificationSubscribeInfo *Unmarshalling(Parcel &parcel); /** - * @brief Dump subscribe info. + * @brief Dumps subscribe info. * - * @return Return subscribe info. + * @return Returns subscribe info. */ std::string Dump(); diff --git a/interfaces/innerkits/ans/native/include/notification_subscriber.h b/interfaces/innerkits/ans/native/include/notification_subscriber.h index 84333bb975d92a55be9726c3db1b6b19256be9a4..5bf1f3b0d4ec3699b1e80315264754c3588e8819 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscriber.h +++ b/interfaces/innerkits/ans/native/include/notification_subscriber.h @@ -26,14 +26,8 @@ namespace OHOS { namespace Notification { class NotificationSubscriber { public: - /** - * @brief Default constructor used to create a instance. - */ NotificationSubscriber(); - /** - * @brief Default destructor. - */ virtual ~NotificationSubscriber(); /** @@ -52,10 +46,10 @@ public: * @param deleteReason Indicates the reason for the deletion. For details, see NotificationConstant. **/ virtual void OnCanceled(const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason) = 0; + const std::shared_ptr &sortingMap, int32_t deleteReason) = 0; /** - * Called back when the subscriber is connected to the Advanced Notification Service (ANS). + * @brief Called back when the subscriber is connected to the Advanced Notification Service (ANS). **/ virtual void OnConnected() = 0; @@ -77,7 +71,7 @@ public: const std::shared_ptr &request, const std::shared_ptr &sortingMap) = 0; /** - * Called back when the subscriber is disconnected from the ANS. + * @brief Called back when the subscriber is disconnected from the ANS. **/ virtual void OnDisconnected() = 0; @@ -138,7 +132,7 @@ private: void OnCanceled(const sptr ¬ification) override; void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, - int deleteReason) override; + int32_t deleteReason) override; void OnUpdated(const sptr ¬ificationMap) override; diff --git a/interfaces/innerkits/ans/native/include/notification_template.h b/interfaces/innerkits/ans/native/include/notification_template.h index 0b56be3373617c70a946805b4e0d02ad3a035833..497bc813245ca4eb3a5c672ebe5ec6428e5508f2 100644 --- a/interfaces/innerkits/ans/native/include/notification_template.h +++ b/interfaces/innerkits/ans/native/include/notification_template.h @@ -19,7 +19,7 @@ #include #include #include "parcel.h" -#include "ohos/aafwk/content/want_params.h" +#include "want_params.h" namespace OHOS { namespace Notification { @@ -29,7 +29,7 @@ public: * Default constructor used to create an empty NotificationTemplate instance. */ NotificationTemplate() = default; - + /** * Default deconstructor used to deconstruct. */ diff --git a/interfaces/innerkits/ans/native/include/notification_user_input.h b/interfaces/innerkits/ans/native/include/notification_user_input.h index 2e68134dcd223b881947c9a6d78c73872d89f8cf..f3e913935997e3c03d8f96471073f527a3b941b3 100644 --- a/interfaces/innerkits/ans/native/include/notification_user_input.h +++ b/interfaces/innerkits/ans/native/include/notification_user_input.h @@ -27,23 +27,26 @@ namespace Notification { class NotificationUserInput : public Parcelable, public NotificationJsonConvertionBase { public: /** - * Sets the input source of this NotificationUserInput object. + * @brief Sets the input source of this NotificationUserInput object. + * * @param want Indicates the Want to which the input result is to be added. * @param source Indicates the input source. For available values, see NotificationConstant::InputSource. */ static void SetInputsSource(AAFwk::Want &want, NotificationConstant::InputsSource source); /** - * Obtains the input source of this NotificationUserInput object. + * @brief Obtains the input source of this NotificationUserInput object. + * * @param want Indicates the Want containing the input result. - * @return the input source of this NotificationUserInput object, - * as enumerated in NotificationConstant::InputSource. + * @return Returns the input source of this NotificationUserInput object, as enumerated in + * NotificationConstant::InputSource. */ static NotificationConstant::InputsSource GetInputsSource(const AAFwk::Want &want); /** - * Adds a list of NotificationUserInput objects to a Want. This method should only be called by user input + * @brief Adds a list of NotificationUserInput objects to a Want. This method should only be called by user input * collection services when sending input results to an WantAgent. + * * @param userInputs Indicates the list of NotificationUserInput objects for which the input results are provided. * @param want Indicates the Want to which the input results are to be added. * @param additional Indicates the AAFwk::WantParams object holding the input results. @@ -53,15 +56,17 @@ public: AAFwk::Want &want, const AAFwk::WantParams &additional); /** - * Obtains the input text results from a specified Want. + * @brief Obtains the input text results from a specified Want. + * * @param want Indicates the Want object containing one or more user input results. - * @return the AAFwk::WantParams object containing the input text results. + * @return Returns the AAFwk::WantParams object containing the input text results. */ static std::shared_ptr GetInputsFromWant(const AAFwk::Want &want); /** - * Adds the given NotificationUserInput object of a specified MIME type to an Want. This method is similar to + * @brief Adds the given NotificationUserInput object of a specified MIME type to an Want. This method is similar to * addInputsToWant(NotificationUserInput, Want, AAFwk::WantParams) except that the MIME type must be specified. + * * @param userInput Indicates the NotificationUserInput object for which the input results are provided. * @param want Indicates the Want to which the input results are to be added. * @param results Indicates a map containing the MIME type and its URI result. @@ -70,27 +75,30 @@ public: const std::map> &results); /** - * Obtains the input results of a particular MIME type from a specified Want. This method is similar to + * @brief Obtains the input results of a particular MIME type from a specified Want. This method is similar to * GetInputsFromWant(Want) but uses the key of the NotificationUserInput. + * * @param want Indicates the Want object containing one or more user input results. * @param inputKey Indicates the key of the NotificationUserInput results to obtain. - * @return a map containing the MIME type and its URI result. + * @return Returns a map containing the MIME type and its URI result. */ static std::map> GetMimeInputsFromWant( const AAFwk::Want &want, const std::string &inputKey); public: /** - * A static function used to create a NotificationUserInput instance with the input parameters passed. + * @brief A static function used to create a NotificationUserInput instance with the input parameters passed. + * * @param inputKey Indicates the AAFwk::WantParams key used to identify this input * when the input is collected from the user. - * @return the shared_ptr object owns the created NotificationUserInput object otherwise return empty object if - * inputKey is empty. + * @return Returns the shared_ptr object owns the created NotificationUserInput object otherwise return empty + * object if inputKey is empty. */ static std::shared_ptr Create(const std::string &inputKey); /** - * A static function used to create a NotificationUserInput instance with the input parameters passed. + * @brief A static function used to create a NotificationUserInput instance with the input parameters passed. + * * @param inputKey Indicates the AAFwk::WantParams key used to identify this input * when the input is collected from the user. * @param tag Indicates the tag to be displayed. @@ -102,67 +110,72 @@ public: * @param additional Indicates the AAFwk::WantParams object containing the additional data. * @param editType Indicates the edit type to set. For details about available values, see * NotificationConstant::InputEditType. - * @return the shared_ptr object owns the created NotificationUserInput object otherwise return empty object if - * permitFreeFormInput is false but editType is InputEditType::EDIT_ENABLED. + * @return Returns the shared_ptr object owns the created NotificationUserInput object otherwise return empty + * object if permitFreeFormInput is false but editType is InputEditType::EDIT_ENABLED. */ static std::shared_ptr Create(const std::string &inputKey, const std::string &tag, const std::vector &options, bool permitFreeFormInput, const std::set &permitMimeTypes, const std::shared_ptr &additional, NotificationConstant::InputEditType editType); - /** - * Default deconstructor used to deconstruct. - */ ~NotificationUserInput() = default; /** - * Obtains the key of this NotificationUserInput object. - * @return the key of this NotificationUserInput object. + * @brief Obtains the key of this NotificationUserInput object. + * + * @return Returns the key of this NotificationUserInput object. */ std::string GetInputKey() const; /** - * Adds additional data to this Builder. + * @brief Adds additional data to this Builder. * The value of AAFwk::WantParams will replace the existing extras value in this Builder. + * * @param additional Indicates the AAFwk::WantParams object containing the additional data. */ void AddAdditionalData(AAFwk::WantParams &additional); /** - * Obtains the additional data included in this NotificationUserInput object. - * @return the additional data in this NotificationUserInput object. + * @brief Obtains the additional data included in this NotificationUserInput object. + * + * @return Returns the additional data in this NotificationUserInput object. */ const std::shared_ptr GetAdditionalData() const; /** - * Sets the edit type of the options provided by this NotificationUserInput object. + * @brief Sets the edit type of the options provided by this NotificationUserInput object. * The edit type determines whether an option can be edited when the user taps the option. + * * @param inputEditType Indicates the edit type to set. For details about available values, * see NotificationConstant::InputEditType. */ void SetEditType(NotificationConstant::InputEditType inputEditType); /** - * Obtains the edit type of the options provided by this NotificationUserInput object. - * @return the edit type of options. + * @brief Obtains the edit type of the options provided by this NotificationUserInput object. + * + * @return Returns the edit type of options. */ NotificationConstant::InputEditType GetEditType() const; /** - * Sets the options provided to users to satisfy user input needs. All options are displayed in a single line. - * Due to limited space, some or all of the options may be hidden if the options are too long or + * @brief Sets the options provided to users to satisfy user input needs. All options are displayed in a single + * line.Due to limited space, some or all of the options may be hidden if the options are too long or * there are too many options. + * * @param options Indicates the list of predefined options to be provided for user input. */ void SetOptions(const std::vector &options); /** - * Obtains the options provided to the user to satisfy user input needs. - * @return the list of predefined options. + * @brief Obtains the options provided to the user to satisfy user input needs. + * + * @return Returns the list of predefined options. */ std::vector GetOptions() const; /** - * Sets whether users can input values of the given MIME type. + * @brief Sets whether users can input values of the given MIME type. + * * @param mimeType Indicates the MIME type allowed. * @param doPermit Specifies whether to allow the given MIME type. * The value true means to allow it, and the value false means not. @@ -170,31 +183,36 @@ public: void SetPermitMimeTypes(const std::string &mimeType, bool doPermit); /** - * Obtains the MIME types allowed by this NotificationUserInput object. - * @return the list of allowed MIME types. + * @brief Obtains the MIME types allowed by this NotificationUserInput object. + * + * @return Returns the list of allowed MIME types. */ std::set GetPermitMimeTypes() const; /** - * Checks whether this NotificationUserInput object allows only values of particular MIME types. - * @return true if this object allows only values of particular MIME types; returns false otherwise. + * @brief Checks whether this NotificationUserInput object allows only values of particular MIME types. + * + * @return Returns true if this object allows only values of particular MIME types; returns false otherwise. */ bool IsMimeTypeOnly() const; /** - * Sets the tag to be displayed to the user when collecting this input from the user. + * @brief Sets the tag to be displayed to the user when collecting this input from the user. + * * @param tag Indicates the tag to be displayed. */ void SetTag(const std::string tag); /** - * Obtains the tag to be displayed to the user when collecting this input from the user. - * @return the tag to be displayed to the user. + * @brief Obtains the tag to be displayed to the user when collecting this input from the user. + * + * @return Returns the tag to be displayed to the user. */ std::string GetTag() const; /** - * Sets whether users can input arbitrary text values. + * @brief Sets whether users can input arbitrary text values. + * * @param permitFreeFormInput Specifies whether to allow arbitrary text values. The default value is true, * indicating that arbitrary text values are allowed. If this parameter is set to false, you must either call * SetOptions(std::vector) to set a non-null and non-empty list or call @@ -203,57 +221,65 @@ public: void SetPermitFreeFormInput(bool permitFreeFormInput); /** - * Checks whether users can provide arbitrary values for this NotificationUserInput object. - * @return true if this object allows arbitrary values; returns false otherwise. + * @brief Checks whether users can provide arbitrary values for this NotificationUserInput object. + * + * @return Returns true if this object allows arbitrary values; returns false otherwise. */ bool IsPermitFreeFormInput() const; /** - * Returns a string representation of the object. - * @return a string representation of the object. + * @brief Dumps a string representation of the object. + * + * @return Returns a string representation of the object. */ std::string Dump(); /** - * Converts a NotificationUserInput object into a Json. + * @brief Converts a NotificationUserInput object into a Json. + * * @param jsonObject Indicates the Json object. + * @return Returns true if succeed; returns false otherwise. */ bool ToJson(nlohmann::json &jsonObject) const override; /** - * Creates a NotificationUserInput object from a Json. + * @brief Creates a NotificationUserInput object from a Json. + * * @param jsonObject Indicates the Json object. - * @return the NotificationUserInput. + * @return Returns the NotificationUserInput object. */ static NotificationUserInput *FromJson(const nlohmann::json &jsonObject); /** - * Marshal a object into a Parcel. - * @param parcel the object into the parcel + * @brief Marshal a object into a Parcel. + * + * @param parcel the object into the parcel. + * @return Returns true if succeed; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const override; /** - * Unmarshal object from a Parcel. - * @return the NotificationUserInput + * @brief Unmarshal object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns the NotificationUserInput object. */ static NotificationUserInput *Unmarshalling(Parcel &parcel); private: - /** - * Default constructor used to create a NotificationUserInput instance. - */ NotificationUserInput() = default; /** - * A constructor used to create a NotificationUserInput instance with the input parameters passed. + * @brief A constructor used to create a NotificationUserInput instance with the input parameters passed. + * * @param inputKey Indicates the AAFwk::WantParams key used to identify this input * when the input is collected from the user. */ explicit NotificationUserInput(const std::string &inputKey); /** - * A constructor used to create a NotificationUserInput instance with the input parameters passed. + * @brief A constructor used to create a NotificationUserInput instance with the input parameters passed. + * * @param inputKey Indicates the AAFwk::WantParams key used to identify this input * when the input is collected from the user. * @param tag Indicates the tag to be displayed. @@ -272,8 +298,10 @@ private: const std::shared_ptr &additional, NotificationConstant::InputEditType editType); /** - * Read a NotificationUserInput object from a Parcel. - * @param parcel the parcel + * @brief Read a NotificationUserInput object from a Parcel. + * + * @param parcel Indicates the parcel object. + * @return Returns true if succeed; returns false otherwise. */ bool ReadFromParcel(Parcel &parcel); diff --git a/interfaces/innerkits/ans/native/include/reminder_helper.h b/interfaces/innerkits/ans/native/include/reminder_helper.h index 0d7f34d8880c0a3ee6fec2c2810703f5256b6473..639b2be8ccd48ccbcc3ae9ed05e37c39776380dd 100644 --- a/interfaces/innerkits/ans/native/include/reminder_helper.h +++ b/interfaces/innerkits/ans/native/include/reminder_helper.h @@ -53,7 +53,7 @@ public: /** * Cancels a specified reminder. * - * @param reminderId Indicates the ID of the reminder instace to cancel. + * @param reminderId Indicates the ID of the reminder instance to cancel. * @return Returns cancel reminder result. */ static ErrCode CancelReminder(const int32_t reminderId); @@ -69,7 +69,7 @@ public: * Obtains all valid reminder notifications set by the current application, namely, the reminders that will * still be triggered later. If a reminder will never be triggered again, it is not considered a valid reminder. * - * @param[out] validReminders Indicates an initial vector to recieve the result. + * @param[out] validReminders Indicates an initial vector to receive the result. * @return Returns an array list containing all valid reminder notifications set by the current application. */ static ErrCode GetValidReminders(std::vector> &validReminders); diff --git a/interfaces/innerkits/ans/native/include/reminder_request.h b/interfaces/innerkits/ans/native/include/reminder_request.h index 14fb032d6ff2f0af0445dfee2cc70254c92418b0..a032d6f666efc89acf6385a2601e19d5e2ebc747 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request.h +++ b/interfaces/innerkits/ans/native/include/reminder_request.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -19,8 +19,11 @@ #include #include +#include "abs_shared_result_set.h" +#include "notification_bundle_option.h" #include "notification_constant.h" #include "notification_request.h" +#include "values_bucket.h" namespace OHOS { namespace Notification { @@ -52,7 +55,7 @@ public: */ enum class ActionButtonType : uint8_t { /** - * @brief Indicates that this action button is used to close reminder's notfication. + * @brief Indicates that this action button is used to close reminder's notification. * It always works well, whether the application is running at the time. * */ @@ -75,6 +78,7 @@ public: REMOVAL_WANT_AGENT, WANT_AGENT, MAX_SCREEN_WANT_AGENT, + BUNDLE_INFO, CONTENT }; @@ -129,6 +133,14 @@ public: * @param Indicates the exist reminder. */ explicit ReminderRequest(const ReminderRequest &other); + + /** + * @brief This constructor should only be used in background proxy service process + * when reminder instance recovery from database. + * + * @param reminderId Indicates reminder id. + */ + explicit ReminderRequest(int32_t reminderId); ReminderRequest& operator = (const ReminderRequest &other); virtual ~ReminderRequest() override {}; @@ -256,6 +268,9 @@ public: */ uint64_t GetTriggerTimeInMilli() const; + int32_t GetUserId() const; + int32_t GetUid() const; + /** * @brief Obtains want agent information. * @@ -278,7 +293,17 @@ public: * * @param userId Indicates the userId which the reminder belong to. */ - void InitUserId(const int &userId); + void InitUserId(const int32_t &userId); + + /** + * @brief Inites reminder uid when publish reminder success. + * + * When system reboot and recovery from database, we cannot get the uid according user id as BMS has not be + * ready. So we need to record the uid in order to create correct bundleOption. + * + * @param uid Indicates the uid which the reminder belong to. + */ + void InitUid(const int32_t &uid); /** * @brief Check the reminder is alerting or not. @@ -343,7 +368,7 @@ public: * * 1) Updates the trigger time to the next one. * 2) Updates the notification content for "Snooze". - * 3) Switchs the state from "Showing[, Alerting]" to "Snooze". + * 3) Switches the state from "Showing[, Alerting]" to "Snooze". */ bool OnSnooze(); @@ -378,6 +403,15 @@ public: */ virtual bool OnTimeZoneChange(); + /** + * @brief Recovery reminder instance from database record. + * + * @param resultSet Indicates the resultSet with pointer to the row of record data. + */ + virtual void RecoverFromDb(const std::shared_ptr &resultSet); + void RecoverActionButton(const std::shared_ptr &resultSet); + void RecoverWantAgent(const std::string &wantAgentInfo, const uint8_t &type); + /** * @brief Sets action button. * @@ -432,7 +466,7 @@ public: /** * @brief Sets the ringing or vibration duration for this reminder, in seconds. * - * @param ringDurationInSeconds Indicates the duration. The defautl is 1 second. + * @param ringDurationInSeconds Indicates the duration. The default is 1 second. * @return Current reminder self. */ ReminderRequest& SetRingDuration(const uint64_t ringDurationInSeconds); @@ -514,7 +548,7 @@ public: virtual bool UpdateNextReminder(); /** - * @brief Update notification attibutes. + * @brief Update notification attributes. * * Some attributes need to be updated after the reminder published or before the notification publish. * For example, action button should not init until the reminder is published successfully, as the reminder id is @@ -525,6 +559,14 @@ public: */ void UpdateNotificationRequest(UpdateNotificationType type, std::string extra); + static int32_t GetActualTime(const TimeTransferType &type, int32_t cTime); + static int32_t GetCTime(const TimeTransferType &type, int32_t actualTime); + static uint64_t GetDurationSinceEpochInMilli(const time_t target); + static int32_t GetUid(const int32_t &userId, const std::string &bundleName); + static int32_t GetUserId(const int32_t &uid); + static void AppendValuesBucket(const sptr &reminder, + const sptr &bundleOption, NativeRdb::ValuesBucket &values); + static int32_t GLOBAL_ID; static const uint64_t INVALID_LONG_LONG_VALUE; static const uint16_t INVALID_U16_VALUE; @@ -558,13 +600,49 @@ public: */ static const std::string REMINDER_EVENT_REMOVE_NOTIFICATION; static const std::string PARAM_REMINDER_ID; - static int GetActualTime(const TimeTransferType &type, int cTime); - static int GetCTime(const TimeTransferType &type, int actualTime); - static uint64_t GetDurationSinceEpochInMilli(const time_t target); - static int32_t GetUid(const int &userId, const std::string &bundleName); - static int GetUserId(const int &uid); + static const uint8_t REMINDER_STATUS_INACTIVE; + static const uint8_t REMINDER_STATUS_ACTIVE; + static const uint8_t REMINDER_STATUS_ALERTING; + static const uint8_t REMINDER_STATUS_SHOWING; + static const uint8_t REMINDER_STATUS_SNOOZE; + + // For database recovery. + static void InitDbColumns(); + static const std::string REMINDER_ID; + static const std::string PKG_NAME; + static const std::string USER_ID; + static const std::string UID; + static const std::string APP_LABEL; + static const std::string REMINDER_TYPE; + static const std::string REMINDER_TIME; + static const std::string TRIGGER_TIME; + static const std::string RTC_TRIGGER_TIME; + static const std::string TIME_INTERVAL; + static const std::string SNOOZE_TIMES; + static const std::string DYNAMIC_SNOOZE_TIMES; + static const std::string RING_DURATION; + static const std::string IS_EXPIRED; + static const std::string IS_ACTIVE; + static const std::string STATE; + static const std::string ZONE_ID; + static const std::string HAS_SCHEDULED_TIMEOUT; + static const std::string ACTION_BUTTON_INFO; + static const std::string SLOT_ID; + static const std::string NOTIFICATION_ID; + static const std::string TITLE; + static const std::string CONTENT; + static const std::string SNOOZE_CONTENT; + static const std::string EXPIRED_CONTENT; + static const std::string AGENT; + static const std::string MAX_SCREEN_AGENT; + static std::string sqlOfAddColumns; + static std::vector columns; protected: + enum class DbRecoveryType : uint8_t { + INT, + LONG + }; ReminderRequest(); explicit ReminderRequest(ReminderType reminderType); std::string GetDateTimeInfo(const time_t &timeInSecond) const; @@ -572,12 +650,25 @@ protected: { return INVALID_LONG_LONG_VALUE; } - static const int BASE_YEAR; + int64_t RecoverInt64FromDb(const std::shared_ptr &resultSet, + const std::string &columnName, const DbRecoveryType &columnType); + + /** + * @brief For database recovery. + * + * Add column to create table of database. + * + * @param name Indicates the column name. + * @param type Indicates the type of the column. + * @param isEnd Indicates whether it is the last column. + */ + static void AddColumn(const std::string &name, const std::string &type, const bool &isEnd); private: void AddActionButtons(const bool includeSnooze); void AddRemovalWantAgent(); std::shared_ptr CreateWantAgent(AppExecFwk::ElementName &element) const; + std::string GetButtonInfo() const; uint64_t GetNowInstantMilli() const; std::string GetShowTime(const uint64_t showTime) const; std::string GetTimeInfoInner(const time_t &timeInSecond, const TimeFormat &format) const; @@ -585,14 +676,23 @@ private: bool HandleSysTimeChange(uint64_t oriTriggerTime, uint64_t optTriggerTime); bool HandleTimeZoneChange(uint64_t oldZoneTriggerTime, uint64_t newZoneTriggerTime, uint64_t optTriggerTime); bool InitNotificationRequest(); + void InitServerObj(); void SetMaxScreenWantAgent(AppExecFwk::ElementName &element); void SetState(bool deSet, const uint8_t newState, std::string function); void SetWantAgent(AppExecFwk::ElementName &element); + std::vector StringSplit(std::string source, const std::string &split) const; void UpdateActionButtons(const bool &setSnooze); bool UpdateNextReminder(const bool &force); void UpdateNotificationContent(const bool &setSnooze); void UpdateNotificationCommon(); + /** + * @brief Used for reminder recovery from database. + * + * @param bundleName Indicates the third part bundle name. + */ + void UpdateNotificationBundleInfo(); + /** * @brief Update the notification, which will be shown for the "Alerting" reminder. * 1. Update the notification label/content. @@ -607,25 +707,25 @@ private: */ void UpdateNotificationStateForSnooze(); - static const uint8_t REMINDER_STATUS_INACTIVE; - static const uint8_t REMINDER_STATUS_ACTIVE; - static const uint8_t REMINDER_STATUS_ALERTING; - static const uint8_t REMINDER_STATUS_SHOWING; - static const uint8_t REMINDER_STATUS_SNOOZE; static const uint32_t MIN_TIME_INTERVAL_IN_MILLI; + static const std::string SEP_BUTTON_SINGLE; + static const std::string SEP_BUTTON_MULTI; + static const std::string SEP_WANT_AGENT; std::string content_ {}; std::string expiredContent_ {}; std::string snoozeContent_ {}; std::string displayContent_ {}; std::string title_ {}; + std::string bundleName_ {}; bool isExpired_ {false}; uint8_t snoozeTimes_ {0}; uint8_t snoozeTimesDynamic_ {0}; uint8_t state_ {0}; int32_t notificationId_ {0}; int32_t reminderId_ {-1}; - int userId_ {-1}; + int32_t userId_ {-1}; + int32_t uid_ {-1}; // Indicates the reminder has been shown in the past time. // When the reminder has been created but not showed, it is equals to 0. diff --git a/interfaces/innerkits/ans/native/include/reminder_request_alarm.h b/interfaces/innerkits/ans/native/include/reminder_request_alarm.h index 07239f1ea3b9cb57afcee7db461a6fc0d04969cf..e0dd931f72fc1880a97dd912c3c26411d202a68d 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_alarm.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_alarm.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -40,6 +40,14 @@ public: */ ReminderRequestAlarm(uint8_t hour, uint8_t minute, std::vector daysOfWeek); + /** + * @brief This constructor should only be used in background proxy service process + * when reminder instance recovery from database. + * + * @param reminderId Indicates reminder id. + */ + explicit ReminderRequestAlarm(int32_t reminderId) : ReminderRequest(reminderId) {}; + /** * @brief Copy construct from an exist reminder. * @@ -54,7 +62,7 @@ public: * * @return vector of repeat days. */ - std::vector GetDaysOfWeek() const; + std::vector GetDaysOfWeek() const; /** * @brief Obtains the setted {@link hour_}. @@ -96,6 +104,12 @@ public: * @return true if read parcel success. */ bool ReadFromParcel(Parcel &parcel) override; + virtual void RecoverFromDb(const std::shared_ptr &resultSet) override; + static void AppendValuesBucket(const sptr &reminder, + const sptr &bundleOption, NativeRdb::ValuesBucket &values); + + // For database recovery. + static void InitDbColumns(); protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const override; @@ -123,7 +137,7 @@ private: * @param day Indicates the day of week. * @return true if it is a repeat day. */ - bool IsRepeatDay(int day) const; + bool IsRepeatDay(int32_t day) const; bool IsRepeatReminder() const; void SetDaysOfWeek(bool set, std::vector daysOfWeek); @@ -148,6 +162,11 @@ private: uint8_t hour_ = {0}; uint8_t minute_ = {0}; uint8_t repeatDays_ = {0}; + + // For database recovery. + static const std::string REPEAT_DAYS_OF_WEEK; + static const std::string ALARM_HOUR; + static const std::string ALARM_MINUTE; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/reminder_request_calendar.h b/interfaces/innerkits/ans/native/include/reminder_request_calendar.h index b675abed73f24e01371abcb93f46880451c2d2f4..1023f233267ecb5a5f0d71525d4fa5edd5ff1e61 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_calendar.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_calendar.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -52,6 +52,14 @@ public: ReminderRequestCalendar(const tm &dateTime, const std::vector &repeatMonths, const std::vector &repeatDays); + /** + * @brief This constructor should only be used in background proxy service process + * when reminder instance recovery from database. + * + * @param reminderId Indicates reminder id. + */ + explicit ReminderRequestCalendar(int32_t reminderId) : ReminderRequest(reminderId) {}; + explicit ReminderRequestCalendar(const ReminderRequestCalendar &other); ReminderRequestCalendar& operator = (const ReminderRequestCalendar &other); ~ReminderRequestCalendar() override {} @@ -133,8 +141,14 @@ public: static const uint8_t MAX_MONTHS_OF_YEAR; static const uint8_t MAX_DAYS_OF_MONTH; + virtual void RecoverFromDb(const std::shared_ptr &resultSet) override; + static void AppendValuesBucket(const sptr &reminder, + const sptr &bundleOption, NativeRdb::ValuesBucket &values); static uint8_t GetDaysOfMonth(const uint16_t &year, const uint8_t &month); + // For database recovery. + static void InitDbColumns(); + protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const override; @@ -144,6 +158,14 @@ private: uint8_t GetNextDay(const uint16_t &settedYear, const uint8_t &settedMonth, const tm &now, const tm &target) const; uint64_t GetNextTriggerTime() const; uint64_t GetNextTriggerTimeAsRepeatReminder(const tm &nowTime, const tm &tarTime) const; + uint32_t GetRepeatDay() const + { + return repeatDay_; + } + uint16_t GetRepeatMonth() const + { + return repeatMonth_; + } uint64_t GetTimeInstantMilli( uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) const; @@ -164,7 +186,17 @@ private: static const uint8_t DECEMBER; static const uint8_t DEFAULT_SNOOZE_TIMES; - tm dateTime_; + tm dateTime_ = { + .tm_sec = 0, + .tm_min = 0, + .tm_hour = 0, + .tm_mday = 1, + .tm_mon = 0, + .tm_year = 0, + .tm_wday = 0, + .tm_yday = 0, + .tm_isdst = -1 + }; uint16_t firstDesignateYear_ {1}; uint8_t firstDesignateMonth_ {1}; uint8_t firstDesignateDay_ {1}; @@ -176,6 +208,18 @@ private: uint8_t second_ {0}; uint16_t repeatMonth_ {0}; uint32_t repeatDay_ {0}; + + // For database recovery. + static const std::string REPEAT_DAYS; + static const std::string REPEAT_MONTHS; + static const std::string FIRST_DESIGNATE_YEAR; + static const std::string FIRST_DESIGNATE_MONTH; + static const std::string FIRST_DESIGNATE_DAY; + static const std::string CALENDAR_YEAR; + static const std::string CALENDAR_MONTH; + static const std::string CALENDAR_DAY; + static const std::string CALENDAR_HOUR; + static const std::string CALENDAR_MINUTE; }; } } diff --git a/interfaces/innerkits/ans/native/include/reminder_request_timer.h b/interfaces/innerkits/ans/native/include/reminder_request_timer.h index 9fc2362f2effe12f4758313624e55562c48318cd..0b703709c65d414a3ce7862bad9e6fe97202a5b2 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_timer.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_timer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -31,7 +31,15 @@ public: * * @param countDownTimeInSeconds Indicates the duration after which this timer reminder will be triggered. */ - ReminderRequestTimer(uint64_t countDownTimeInSeconds); + explicit ReminderRequestTimer(uint64_t countDownTimeInSeconds); + + /** + * @brief This constructor should only be used in background proxy service process + * when reminder instance recovery from database. + * + * @param reminderId Indicates reminder id. + */ + explicit ReminderRequestTimer(int32_t reminderId) : ReminderRequest(reminderId) {}; /** * @brief Copy construct from an exist reminder. @@ -67,10 +75,10 @@ protected: private: ReminderRequestTimer() {}; void CheckParamsValid(const uint64_t countDownTimeInSeconds) const; - void UpdateTimeInfo(const std::string description); + void UpdateTimeInfo(const std::string &description); uint64_t countDownTimeInSeconds_ {0}; - uint64_t firstRealTimeInMilliSeconds_ {-1}; - uint64_t whenToChangeSysTime_ {-1}; + uint64_t firstRealTimeInMilliSeconds_ {0}; + uint64_t whenToChangeSysTime_ {0}; }; } // namespace Reminder } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/reminder_store.h b/interfaces/innerkits/ans/native/include/reminder_store.h new file mode 100644 index 0000000000000000000000000000000000000000..da29146063e5e07131e219d2fc4fb3605b00ee2b --- /dev/null +++ b/interfaces/innerkits/ans/native/include/reminder_store.h @@ -0,0 +1,83 @@ +/* + * 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 BASE_NOTIFICATION_ANS_STANDARD_INTERFACES_INNERKITS_ANS_NATIVE_INCLUDE_REMINDER_STORE_H +#define BASE_NOTIFICATION_ANS_STANDARD_INTERFACES_INNERKITS_ANS_NATIVE_INCLUDE_REMINDER_STORE_H + +#include + +#include "notification_bundle_option.h" +#include "reminder_request.h" +#include "rdb_errno.h" +#include "rdb_helper.h" +#include "rdb_open_callback.h" +#include "rdb_store_config.h" + +namespace OHOS { +namespace Notification { +class ReminderStore { +public: + ReminderStore() {}; + virtual ~ReminderStore() {}; + int32_t Init(); + int32_t Delete(int32_t reminderId); + int32_t Delete(const std::string &pkg, int32_t userId); + int32_t DeleteUser(int32_t userId); + std::vector> GetAllValidReminders(); + bool GetBundleOption(const int32_t &reminderId, sptr &bundleOption) const; + int32_t GetMaxId(); + int64_t UpdateOrInsert(const sptr &reminder, const sptr &bundleOption); + static uint8_t GetColumnIndex(const std::string& name); + + static const int32_t STATE_OK; + +private: + /** + * @brief Inits the data in database when system boot on or proxy process reboot on. + * + * 1. Deletes all the reminders which IS_EXPIRED is true. + * 2. Sets all the value of STATE to ReminderRequest::REMINDER_STATUS_INACTIVE + * 3. Sets all the value of IS_ACTIVE to false. + * 4. Sets all the value of HAS_SCHEDULED_TIMEOUT to false. + * + * @return int32_t result code. + */ + int32_t InitData(); + sptr BuildReminder(const std::shared_ptr &resultSet); + int32_t Delete(const std::string &deleteCondition); + void GetInt32Val(std::shared_ptr &resultSet, + const std::string &name, int32_t &value) const; + void GetStringVal(std::shared_ptr &resultSet, + const std::string &name, std::string &value) const; + std::vector> GetReminders(const std::string &queryCondition); + void GenerateData(const sptr &remindert, + const sptr &bundleOption, NativeRdb::ValuesBucket &values) const; + bool IsReminderExist(const sptr &reminder); + int64_t Insert(const sptr &reminder, const sptr &bundleOption); + std::shared_ptr Query(const std::string &queryCondition) const; + int64_t Update(const sptr &reminder, const sptr &bundleOption); + +class ReminderStoreDataCallBack : public NativeRdb::RdbOpenCallback { +public: + int32_t OnCreate(NativeRdb::RdbStore &rdbStore) override; + int32_t OnUpgrade(NativeRdb::RdbStore &rdbStore, int32_t oldVersion, int32_t newVersion) override; +}; + +private: + std::shared_ptr rdbStore_ = nullptr; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_INTERFACES_INNERKITS_ANS_NATIVE_INCLUDE_REMINDER_STORE_H \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.reminderAgent.d.ts b/interfaces/kits/js/@ohos.reminderAgent.d.ts index 4fb85da2d034e6d8c7eac1bc592d663d3653b17b..2c23aa3adcfef7cd621363340fa41727491599de 100644 --- a/interfaces/kits/js/@ohos.reminderAgent.d.ts +++ b/interfaces/kits/js/@ohos.reminderAgent.d.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -198,14 +198,14 @@ declare namespace reminderAgent { /** * Name of the package that is automatically started when the reminder arrives and the device is not in use. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ pkgName: string; /** * Name of the ability that is automatically started when the reminder arrives and the device is not in use. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ abilityName: string; } @@ -250,21 +250,21 @@ declare namespace reminderAgent { /** * Ringing duration. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ ringDuration?: number; /** * Number of reminder snooze times. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ snoozeTimes?: number; /** * Reminder snooze interval. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ timeInterval?: number; @@ -292,7 +292,7 @@ declare namespace reminderAgent { /** * Content to be displayed when the reminder is snoozing. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ snoozeContent?: string; @@ -315,21 +315,21 @@ declare namespace reminderAgent { /** * Reminder time. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ dateTime: LocalDateTime; /** * Month in which the reminder repeats. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ repeatMonths?: Array; /** * Date on which the reminder repeats. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ repeatDays?: Array; } @@ -377,37 +377,44 @@ declare namespace reminderAgent { /** * value of year. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ year: number; /** * value of month. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ month: number; /** * value of day. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ day: number; /** * value of hour. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ hour: number; /** * value of minute. * @since 7 - * @syscap SystemCapability.Notification.ReminderAgent. + * @syscap SystemCapability.Notification.ReminderAgent */ minute: number; + + /** + * value of minute. + * @since 7 + * @syscap SystemCapability.Notification.ReminderAgent + */ + second: number; } } export default reminderAgent; \ No newline at end of file diff --git a/interfaces/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn index 74ee9b5353690729dd4a84199c9b9d2025979b2f..28bb4746557f6e2099c5398cbbeb287963a665c2 100644 --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -76,13 +76,13 @@ ohos_shared_library("notification") { external_deps = [ "ability_base:base", "ability_base:want", + "ability_base:zuri", "ability_runtime:abilitykit_native", "ability_runtime:wantagent_innerkits", - "bundle_framework:appexecfwk_base", - "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", + "native_appdatamgr:native_rdb", ] relative_install_dir = "module" diff --git a/interfaces/kits/napi/ans/include/cancel.h b/interfaces/kits/napi/ans/include/cancel.h index 4cdc87e7953f2396d8cf7d7e69c59f7b8d0ac93e..49b306db5e3226e820fa4aa6efbbb8a00ca35c3e 100644 --- a/interfaces/kits/napi/ans/include/cancel.h +++ b/interfaces/kits/napi/ans/include/cancel.h @@ -25,6 +25,7 @@ using namespace OHOS::Notification; napi_value Cancel(napi_env env, napi_callback_info info); napi_value CancelAll(napi_env env, napi_callback_info info); napi_value CancelGroup(napi_env env, napi_callback_info info); +napi_value CancelAsBundle(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index 297cd4132575822c8e6167e18157a60481dd933f..b79276d4a9bf841e8cdf33000e9f718ca9239c6f 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -24,13 +24,14 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -const std::int32_t STR_MAX_SIZE = 64; -const std::int32_t LONG_STR_MAX_SIZE = 1024; -const int NO_ERROR = 0; -const int ERROR = -1; -const int PARAM0 = 0; -const int PARAM1 = 1; -const int PARAM2 = 2; +constexpr int32_t STR_MAX_SIZE = 200; +constexpr int32_t LONG_STR_MAX_SIZE = 1024; +constexpr uint8_t NO_ERROR = 0; +constexpr uint8_t ERROR = -1; +constexpr uint8_t PARAM0 = 0; +constexpr uint8_t PARAM1 = 1; +constexpr uint8_t PARAM2 = 2; +constexpr uint8_t PARAM3 = 3; enum class ContentType { NOTIFICATION_CONTENT_BASIC_TEXT, @@ -128,12 +129,12 @@ enum class NotificationFlagStatus { struct NotificationSubscribeInfo { std::vector bundleNames; - int userId = 0; + int32_t userId = 0; bool hasSubscribeInfo = false; }; struct NotificationKey { - int id {}; + int32_t id {}; std::string label {}; }; @@ -141,7 +142,7 @@ struct CallbackPromiseInfo { napi_ref callback = nullptr; napi_deferred deferred = nullptr; bool isCallback = false; - int errorCode = 0; + int32_t errorCode = 0; }; class Common { @@ -150,303 +151,1388 @@ class Common { ~Common(); public: + /** + * @brief Gets a napi value that is used to represent specified bool value + * + * @param env Indicates the environment that the API is invoked under + * @param isValue Indicates a bool value + * @return Returns a napi value that is used to represent specified bool value + */ static napi_value NapiGetBoolean(napi_env env, const bool &isValue); + /** + * @brief Gets the napi value that is used to represent the null object + * + * @param env Indicates the environment that the API is invoked under + * @return Returns the napi value that is used to represent the null object + */ static napi_value NapiGetNull(napi_env env); + /** + * @brief Gets the napi value that is used to represent the undefined object + * + * @param env Indicates the environment that the API is invoked under + * @return Returns the napi value that is used to represent the undefined object + */ static napi_value NapiGetUndefined(napi_env env); - static napi_value GetCallbackErrorValue(napi_env env, int errCode); - + /** + * @brief Gets a napi value with specified error code for callback + * + * @param env Indicates the environment that the API is invoked under + * @param errCode Indicates specified err code + * @return Returns a napi value with specified error code for callback + */ + static napi_value GetCallbackErrorValue(napi_env env, int32_t errCode); + + /** + * @brief Pads the CallbackPromiseInfo struct + * + * @param env Indicates the environment that the API is invoked under + * @param callback Indicates a napi_ref for callback + * @param info Indicates the CallbackPromiseInfo struct to be padded + * @param promise Indicates the promise to be created when the callback is null + */ static void PaddingCallbackPromiseInfo( const napi_env &env, const napi_ref &callback, CallbackPromiseInfo &info, napi_value &promise); + /** + * @brief Gets the returned result by the CallbackPromiseInfo struct + * + * @param env Indicates the environment that the API is invoked under + * @param info Indicates the CallbackPromiseInfo struct + * @param result Indicates the returned result + */ static void ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result); + /** + * @brief Calls the callback with the result and error code + * + * @param env Indicates the environment that the API is invoked under + * @param callbackIn Indicates the callback to be called + * @param errCode Indicates the error code returned by the callback + * @param result Indicates the result returned by the callback + */ static void SetCallback( - const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result); - + const napi_env &env, const napi_ref &callbackIn, const int32_t &errorCode, const napi_value &result); + + /** + * @brief Calls the callback with the result + * + * @param env Indicates the environment that the API is invoked under + * @param callbackIn Indicates the callback to be called + * @param result Indicates the result returned by the callback + */ static void SetCallback( const napi_env &env, const napi_ref &callbackIn, const napi_value &result); + /** + * @brief Processes the promise with the result and error code + * + * @param env Indicates the environment that the API is invoked under + * @param deferred Indicates the deferred object whose associated promise to resolve + * @param errorCode Indicates the error code returned by the callback + * @param result Indicates the result returned by the callback + */ static void SetPromise( - const napi_env &env, const napi_deferred &deferred, const int &errorCode, const napi_value &result); - + const napi_env &env, const napi_deferred &deferred, const int32_t &errorCode, const napi_value &result); + + /** + * @brief Gets the returned result by the callback when an error occurs + * + * @param env Indicates the environment that the API is invoked under + * @param callback Indicates a napi_ref for callback + * @return Returns the null object + */ static napi_value JSParaError(const napi_env &env, const napi_ref &callback); + /** + * @brief Parses a single parameter for callback + * + * @param env Indicates the environment that the API is invoked under + * @param info Indicates the callback info passed into the callback function + * @param callback Indicates the napi_ref for the callback parameter + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value ParseParaOnlyCallback(const napi_env &env, const napi_callback_info &info, napi_ref &callback); + /** + * @brief Sets a js object by specified Notification object + * + * @param env Indicates the environment that the API is invoked under + * @param notification Indicates a Notification object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotification( const napi_env &env, const OHOS::Notification::Notification *notification, napi_value &result); + /** + * @brief Sets a js object by specified NotificationRequest object + * + * @param env Indicates the environment that the API is invoked under + * @param request Indicates a NotificationRequest object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationRequest( const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + + /** + * @brief Sets a js object by the string obejcts of specified NotificationRequest object + * + * @param env Indicates the environment that the API is invoked under + * @param request Indicates a NotificationRequest object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationRequestByString( const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + + /** + * @brief Sets a js object by the number obejcts of specified NotificationRequest object + * + * @param env Indicates the environment that the API is invoked under + * @param request Indicates a NotificationRequest object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationRequestByNumber( const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + + /** + * @brief Sets a js object by the bool obejcts of specified NotificationRequest object + * + * @param env Indicates the environment that the API is invoked under + * @param request Indicates a NotificationRequest object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationRequestByBool( const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + + /** + * @brief Sets a js object by the WantAgent obejct of specified NotificationRequest object + * + * @param env Indicates the environment that the API is invoked under + * @param request Indicates a NotificationRequest object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationRequestByWantAgent( const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + + /** + * @brief Sets a js object by the PixelMap obejct of specified NotificationRequest object + * + * @param env Indicates the environment that the API is invoked under + * @param request Indicates a NotificationRequest object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationRequestByPixelMap( const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + + /** + * @brief Sets a js object by the custom obejcts of specified NotificationRequest object + * + * @param env Indicates the environment that the API is invoked under + * @param request Indicates a NotificationRequest object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationRequestByCustom( const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + /** + * @brief Sets a js object by the Distributed Options object of specified Notification object + * + * @param env Indicates the environment that the API is invoked under + * @param notification Indicates a Notification object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationByDistributedOptions( const napi_env &env, const OHOS::Notification::Notification *notification, napi_value &result); + /** + * @brief Sets a js object by specified NotificationSortingMap object + * + * @param env Indicates the environment that the API is invoked under + * @param sortingMap Indicates a NotificationSortingMap object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationSortingMap( const napi_env &env, const std::shared_ptr &sortingMap, napi_value &result); + /** + * @brief Sets a js object by specified NotificationSorting object + * + * @param env Indicates the environment that the API is invoked under + * @param sorting Indicates a NotificationSorting object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationSorting( const napi_env &env, const NotificationSorting &sorting, napi_value &result); + /** + * @brief Sets a js object by specified NotificationSlot object + * + * @param env Indicates the environment that the API is invoked under + * @param slot Indicates a NotificationSlot object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationSlot(const napi_env &env, const NotificationSlot &slot, napi_value &result); + /** + * @brief Sets a js object by specified NotificationContent object + * + * @param env Indicates the environment that the API is invoked under + * @param content Indicates a NotificationContent object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationContent( const napi_env &env, const std::shared_ptr &content, napi_value &result); + + /** + * @brief Sets a js object by the object of specified type in specified NotificationContent object + * + * @param env Indicates the environment that the API is invoked under + * @param type Indicates the content type + * @param content Indicates a NotificationContent object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationContentDetailed(const napi_env &env, const ContentType &type, const std::shared_ptr &content, napi_value &result); + + /** + * @brief Sets a js NotificationBasicContent object by specified NotificationBasicContent object + * + * @param env Indicates the environment that the API is invoked under + * @param basicContent Indicates a NotificationBasicContent object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationBasicContent( const napi_env &env, const NotificationBasicContent *basicContent, napi_value &result); + + /** + * @brief Sets a js NotificationLongTextContent object by specified NotificationBasicContent object + * + * @param env Indicates the environment that the API is invoked under + * @param basicContent Indicates a NotificationBasicContent object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationLongTextContent( const napi_env &env, NotificationBasicContent *basicContent, napi_value &result); + + /** + * @brief Sets a js NotificationPictureContent object by specified NotificationBasicContent object + * + * @param env Indicates the environment that the API is invoked under + * @param basicContent Indicates a NotificationBasicContent object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationPictureContent( const napi_env &env, NotificationBasicContent *basicContent, napi_value &result); + + /** + * @brief Sets a js NotificationConversationalContent object by specified NotificationBasicContent object + * + * @param env Indicates the environment that the API is invoked under + * @param basicContent Indicates a NotificationBasicContent object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationConversationalContent(const napi_env &env, NotificationBasicContent *basicContent, napi_value &result); + + /** + * @brief Sets a js NotificationMultiLineContent object by specified NotificationBasicContent object + * + * @param env Indicates the environment that the API is invoked under + * @param basicContent Indicates a NotificationBasicContent object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationMultiLineContent( const napi_env &env, NotificationBasicContent *basicContent, napi_value &result); + /** + * @brief Sets a js object by specified MessageUser object + * + * @param env Indicates the environment that the API is invoked under + * @param messageUser Indicates a MessageUser object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetMessageUser(const napi_env &env, const MessageUser &messageUser, napi_value &result); + /** + * @brief Sets a js object by specified NotificationConversationalContent object + * + * @param env Indicates the environment that the API is invoked under + * @param conversationalContent Indicates a NotificationConversationalContent object to be converted + * @param arr Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetConversationalMessages(const napi_env &env, const OHOS::Notification::NotificationConversationalContent *conversationalContent, napi_value &arr); + /** + * @brief Sets a js object by specified NotificationConversationalMessage object + * + * @param env Indicates the environment that the API is invoked under + * @param conversationalMessage Indicates a NotificationConversationalMessage object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetConversationalMessage(const napi_env &env, const std::shared_ptr &conversationalMessage, napi_value &result); + /** + * @brief Sets a js object by specified NotificationActionButton object + * + * @param env Indicates the environment that the API is invoked under + * @param actionButton Indicates a NotificationActionButton object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationActionButton( const napi_env &env, const std::shared_ptr &actionButton, napi_value &result); + + /** + * @brief Sets a js object by the extra objects of specified NotificationActionButton object + * + * @param env Indicates the environment that the API is invoked under + * @param actionButton Indicates a NotificationActionButton object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationActionButtonByExtras( const napi_env &env, const std::shared_ptr &actionButton, napi_value &result); + + /** + * @brief Sets a js object by specified NotificationUserInput object + * + * @param env Indicates the environment that the API is invoked under + * @param userInput Indicates a NotificationUserInput object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationActionButtonByUserInput( const napi_env &env, const std::shared_ptr &userInput, napi_value &result); + /** + * @brief Sets a js object by specified NotificationDoNotDisturbDate object + * + * @param env Indicates the environment that the API is invoked under + * @param date Indicates a NotificationDoNotDisturbDate object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetDoNotDisturbDate( const napi_env &env, const NotificationDoNotDisturbDate &date, napi_value &result); + /** + * @brief Sets a js object by specified EnabledNotificationCallbackData object + * + * @param env Indicates the environment that the API is invoked under + * @param date Indicates a EnabledNotificationCallbackData object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetEnabledNotificationCallbackData(const napi_env &env, const EnabledNotificationCallbackData &data, napi_value &result); + /** + * @brief Gets a NotificationSubscribeInfo object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param result Indicates a NotificationSubscribeInfo object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationSubscriberInfo( const napi_env &env, const napi_value &value, NotificationSubscribeInfo &result); + /** + * @brief Gets a NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param result Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationRequest( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets a NotificationRequest object by number type from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationRequestByNumber( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets a NotificationRequest object by string type from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationRequestByString( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets a NotificationRequest object by bool type from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationRequestByBool( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets a NotificationRequest object by custom type from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationRequestByCustom( const napi_env &env, const napi_value &value, NotificationRequest &request); + /** + * @brief Gets the id of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationId(const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the slot type of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationSlotType( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the isOngoing flag of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationIsOngoing( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the isUnremovable flag of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationIsUnremovable( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the delivery time of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationDeliveryTime( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the tapDismissed flag of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationtapDismissed( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the extra information of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationExtraInfo( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the group name of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationGroupName( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the removal WantAgent object of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationRemovalWantAgent( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the max screen WantAgent object of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationMaxScreenWantAgent( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the auto deleted time of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationAutoDeletedTime( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the classification of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationClassification( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the color of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationColor(const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the colorEnabled flag of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationColorEnabled( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the isAlertOnce flag of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationIsAlertOnce( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the isStopwatch flag of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationIsStopwatch( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the isCountDown flag of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationIsCountDown( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the status bar text of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationStatusBarText( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the label of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the badge icon style of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationBadgeIconStyle( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the showDeliveryTime flag of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationShowDeliveryTime( const napi_env &env, const napi_value &value, NotificationRequest &request); + /** + * @brief Gets the content of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationContent( const napi_env &env, const napi_value &value, NotificationRequest &request); + /** + * @brief Gets the WantAgent object of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationWantAgent( const napi_env &env, const napi_value &value, NotificationRequest &request); + /** + * @brief Gets a NotificationSlot object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param slot Indicates a NotificationSlot object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationSlot( const napi_env &env, const napi_value &value, NotificationSlot &slot); + + /** + * @brief Gets the string objects of NotificationSlot object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param slot Indicates a NotificationSlot object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationSlotByString( const napi_env &env, const napi_value &value, NotificationSlot &slot); + + /** + * @brief Gets the bool objects of NotificationSlot object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param slot Indicates a NotificationSlot object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationSlotByBool( const napi_env &env, const napi_value &value, NotificationSlot &slot); + + /** + * @brief Gets the number objects of NotificationSlot object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param slot Indicates a NotificationSlot object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationSlotByNumber( const napi_env &env, const napi_value &value, NotificationSlot &slot); + + /** + * @brief Gets the vibration of NotificationSlot object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param slot Indicates a NotificationSlot object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationSlotByVibration( const napi_env &env, const napi_value &value, NotificationSlot &slot); + /** + * @brief Gets the action buttons of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationActionButtons( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets a NotificationActionButton object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param actionButton Indicates a js object to be converted + * @param pActionButton Indicates a NotificationActionButton object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationActionButtonsDetailed( const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton); + + /** + * @brief Gets the basic information of NotificationActionButton object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param actionButton Indicates a js object to be converted + * @param pActionButton Indicates a NotificationActionButton object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationActionButtonsDetailedBasicInfo( const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton); + + /** + * @brief Gets the extras of NotificationActionButton object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param actionButton Indicates a js object to be converted + * @param pActionButton Indicates a NotificationActionButton object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationActionButtonsDetailedByExtras( const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton); + + /** + * @brief Gets the user input of NotificationActionButton object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param actionButton Indicates a js object to be converted + * @param pActionButton Indicates a NotificationActionButton object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationUserInput( const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton); + + /** + * @brief Gets the input key of NotificationUserInput object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param userInputResult Indicates a js object to be converted + * @param userInput Indicates a NotificationUserInput object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationUserInputByInputKey( const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + + /** + * @brief Gets the tag of NotificationUserInput object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param userInputResult Indicates a js object to be converted + * @param userInput Indicates a NotificationUserInput object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationUserInputByTag( const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + + /** + * @brief Gets the options of NotificationUserInput object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param userInputResult Indicates a js object to be converted + * @param userInput Indicates a NotificationUserInput object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationUserInputByOptions( const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + + /** + * @brief Gets the permit mime types of NotificationUserInput object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param userInputResult Indicates a js object to be converted + * @param userInput Indicates a NotificationUserInput object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationUserInputByPermitMimeTypes( const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + + /** + * @brief Gets the permit free from input of NotificationUserInput object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param userInputResult Indicates a js object to be converted + * @param userInput Indicates a NotificationUserInput object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationUserInputByPermitFreeFormInput( const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + + /** + * @brief Gets the edit type of NotificationUserInput object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param userInputResult Indicates a js object to be converted + * @param userInput Indicates a NotificationUserInput object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationUserInputByEditType( const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + + /** + * @brief Gets the additional data of NotificationUserInput object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param userInputResult Indicates a js object to be converted + * @param userInput Indicates a NotificationUserInput object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationUserInputByAdditionalData( const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + /** + * @brief Gets the small icon of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationSmallIcon( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the large icon of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationLargeIcon( const napi_env &env, const napi_value &value, NotificationRequest &request); + /** + * @brief Gets the distributed options of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationRequestDistributedOptions( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the isDistributed flag of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationIsDistributed( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the devices that support display of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationSupportDisplayDevices( const napi_env &env, const napi_value &value, NotificationRequest &request); + + /** + * @brief Gets the devices that support operation of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationSupportOperateDevices( const napi_env &env, const napi_value &value, NotificationRequest &request); + /** + * @brief Gets a content type of notification from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param type Indicates a the content type of notification from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationContentType(const napi_env &env, const napi_value &result, int32_t &type); + + /** + * @brief Gets a basic content of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationBasicContent( const napi_env &env, const napi_value &result, NotificationRequest &request); + + /** + * @brief Gets a NotificationBasicContent object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param contentResult Indicates a js object to be converted + * @param basicContent Indicates a NotificationBasicContent object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationBasicContentDetailed( const napi_env &env, const napi_value &contentResult, std::shared_ptr basicContent); + /** + * @brief Gets a long-text content of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationLongTextContent( const napi_env &env, const napi_value &result, NotificationRequest &request); + + /** + * @brief Gets a NotificationLongTextContent object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param contentResult Indicates a js object to be converted + * @param longContent Indicates a NotificationLongTextContent object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationLongTextContentDetailed( const napi_env &env, const napi_value &contentResult, std::shared_ptr &longContent); + /** + * @brief Gets a picture content of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param result Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationPictureContent( const napi_env &env, const napi_value &result, NotificationRequest &request); + + /** + * @brief Gets a NotificationPictureContent object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param contentResult Indicates a js object to be converted + * @param pictureContent Indicates a NotificationPictureContent object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationPictureContentDetailed( const napi_env &env, const napi_value &contentResult, std::shared_ptr &pictureContent); + /** + * @brief Gets a conversational content of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param result Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationConversationalContent( const napi_env &env, const napi_value &result, NotificationRequest &request); + + /** + * @brief Gets the user of NotificationConversationalContent object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param contentResult Indicates a js object to be converted + * @param user Indicates a MessageUser object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationConversationalContentByUser( const napi_env &env, const napi_value &contentResult, MessageUser &user); + + /** + * @brief Gets the title of NotificationConversationalContent object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param contentResult Indicates a js object to be converted + * @param conversationalContent Indicates a NotificationConversationalContent object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationConversationalContentTitle( const napi_env &env, const napi_value &contentResult, std::shared_ptr &conversationalContent); + + /** + * @brief Gets the group of NotificationConversationalContent object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param contentResult Indicates a js object to be converted + * @param conversationalContent Indicates a NotificationConversationalContent object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationConversationalContentGroup( const napi_env &env, const napi_value &contentResult, std::shared_ptr &conversationalContent); + + /** + * @brief Gets the messages of NotificationConversationalContent object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param contentResult Indicates a js object to be converted + * @param conversationalContent Indicates a NotificationConversationalContent object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationConversationalContentMessages( const napi_env &env, const napi_value &contentResult, std::shared_ptr &conversationalContent); + + /** + * @brief Gets a NotificationConversationalMessage object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param conversationalMessage Indicates a js object to be converted + * @param message Indicates a NotificationConversationalMessage object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetConversationalMessage( const napi_env &env, const napi_value &conversationalMessage, std::shared_ptr &message); + + /** + * @brief Gets the basic information of NotificationConversationalMessage object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param conversationalMessage Indicates a js object to be converted + * @param message Indicates a NotificationConversationalMessage object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetConversationalMessageBasicInfo( const napi_env &env, const napi_value &conversationalMessage, std::shared_ptr &message); + + /** + * @brief Gets the other information of NotificationConversationalMessage object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param conversationalMessage Indicates a js object to be converted + * @param message Indicates a NotificationConversationalMessage object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetConversationalMessageOtherInfo( const napi_env &env, const napi_value &conversationalMessage, std::shared_ptr &message); + + /** + * @brief Gets a MessageUser object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param result Indicates a js object to be converted + * @param messageUser Indicates a MessageUser object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetMessageUser(const napi_env &env, const napi_value &result, MessageUser &messageUser); + + /** + * @brief Gets a MessageUser object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param result Indicates a js object to be converted + * @param messageUser Indicates a MessageUser object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetMessageUserByString(const napi_env &env, const napi_value &result, MessageUser &messageUser); + + /** + * @brief Gets the bool objects of MessageUser object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param result Indicates a js object to be converted + * @param messageUser Indicates a MessageUser object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetMessageUserByBool(const napi_env &env, const napi_value &result, MessageUser &messageUser); + + /** + * @brief Gets the custom objects of MessageUser object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param result Indicates a js object to be converted + * @param messageUser Indicates a MessageUser object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetMessageUserByCustom(const napi_env &env, const napi_value &result, MessageUser &messageUser); + /** + * @brief Gets the multi-line content of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param result Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationMultiLineContent( const napi_env &env, const napi_value &result, NotificationRequest &request); + + /** + * @brief Gets the lines of NotificationMultiLineContent object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param result Indicates a js object to be converted + * @param multiLineContent Indicates a NotificationMultiLineContent object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationMultiLineContentLines(const napi_env &env, const napi_value &result, std::shared_ptr &multiLineContent); + /** + * @brief Gets a NotificationBundleOption object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param option Indicates a NotificationBundleOption object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetBundleOption(const napi_env &env, const napi_value &value, NotificationBundleOption &option); + /** + * @brief Gets a NotificationKey object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param key Indicates a NotificationKey object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationKey(const napi_env &env, const napi_value &value, NotificationKey &key); + /** + * @brief Converts content type from js to native + * + * @param inType Indicates a js ContentType object + * @param outType Indicates a NotificationContent object + * @return Returns true if success, returns false otherwise + */ static bool ContentTypeJSToC(const ContentType &inType, NotificationContent::Type &outType); + /** + * @brief Converts content type from native to js + * + * @param inType Indicates a NotificationContent object + * @param outType Indicates a js ContentType object + * @return Returns true if success, returns false otherwise + */ static bool ContentTypeCToJS(const NotificationContent::Type &inType, ContentType &outType); + /** + * @brief Converts slot type from js to native + * + * @param inType Indicates a native SlotType object + * @param outType Indicates a js SlotType object + * @return Returns true if success, returns false otherwise + */ static bool SlotTypeJSToC(const SlotType &inType, NotificationConstant::SlotType &outType); + /** + * @brief Converts slot type from native to js + * + * @param inType Indicates a js SlotType object + * @param outType Indicates a native SlotType object + * @return Returns true if success, returns false otherwise + */ static bool SlotTypeCToJS(const NotificationConstant::SlotType &inType, SlotType &outType); + /** + * @brief Converts slot level from js to native + * + * @param inType Indicates a native SlotLevel object + * @param outType Indicates a js NotificationLevel object + * @return Returns true if success, returns false otherwise + */ static bool SlotLevelJSToC(const SlotLevel &inLevel, NotificationSlot::NotificationLevel &outLevel); + /** + * @brief Converts slot level from native to js + * + * @param inType Indicates a js NotificationLevel object + * @param outType Indicates a native SlotLevel object + * @return Returns true if success, returns false otherwise + */ static bool SlotLevelCToJS(const NotificationSlot::NotificationLevel &inLevel, SlotLevel &outLevel); - static bool ReasonCToJS(const int &inType, int &outType); - + /** + * @brief Converts reason type from native to js + * + * @param inType Indicates a native reason type + * @param outType Indicates a js reason type + * @return Returns true if success, returns false otherwise + */ + static bool ReasonCToJS(const int32_t &inType, int32_t &outType); + + /** + * @brief Converts do-not-disturb type from js to native + * + * @param inType Indicates a js DoNotDisturbType object + * @param outType Indicates a native DoNotDisturbType object + * @return Returns true if success, returns false otherwise + */ static bool DoNotDisturbTypeJSToC(const DoNotDisturbType &inType, NotificationConstant::DoNotDisturbType &outType); + /** + * @brief Converts do-not-disturb type from native to js + * + * @param inType Indicates a native DoNotDisturbType object + * @param outType Indicates a js DoNotDisturbType object + * @return Returns true if success, returns false otherwise + */ static bool DoNotDisturbTypeCToJS(const NotificationConstant::DoNotDisturbType &inType, DoNotDisturbType &outType); + /** + * @brief Converts remind type from native to js + * + * @param inType Indicates a native RemindType object + * @param outType Indicates a js DeviceRemindType object + * @return Returns true if success, returns false otherwise + */ static bool DeviceRemindTypeCToJS(const NotificationConstant::RemindType &inType, DeviceRemindType &outType); + /** + * @brief Converts source type from native to js + * + * @param inType Indicates a native SourceType object + * @param outType Indicates a js SourceType object + * @return Returns true if success, returns false otherwise + */ static bool SourceTypeCToJS(const NotificationConstant::SourceType &inType, SourceType &outType); + /** + * @brief Creates a js object from specified WantAgent object + * + * @param env Indicates the environment that the API is invoked under + * @param agent Indicates specified WantAgent object + * @return Returns a js object from specified WantAgent object + */ static napi_value CreateWantAgentByJS(const napi_env &env, const std::shared_ptr &agent); + /** + * @brief Gets the template of NotificationRequest object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param request Indicates a NotificationRequest object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationTemplate( const napi_env &env, const napi_value &value, NotificationRequest &request); + /** + * @brief Gets a NotificationTemplate object from specified js object + * + * @param env Indicates the environment that the API is invoked under + * @param value Indicates a js object to be converted + * @param templ Indicates a NotificationTemplate object from specified js object + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value GetNotificationTemplateInfo(const napi_env &env, const napi_value &value, std::shared_ptr &templ); + /** + * @brief Sets a js object by specified NotificationTemplate object + * + * @param env Indicates the environment that the API is invoked under + * @param templ Indicates a NotificationTemplate object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationTemplateInfo( const napi_env &env, const std::shared_ptr &templ, napi_value &result); + /** + * @brief Sets a js object by specified NotificationFlags object + * + * @param env Indicates the environment that the API is invoked under + * @param flags Indicates a NotificationFlags object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ static napi_value SetNotificationFlags( const napi_env &env, const std::shared_ptr &flags, napi_value &result); private: - static const int ARGS_ONE = 1; - static const int ARGS_TWO = 2; - static const int ONLY_CALLBACK_MAX_PARA = 1; - static const int ONLY_CALLBACK_MIN_PARA = 0; + static const int32_t ARGS_ONE = 1; + static const int32_t ARGS_TWO = 2; + static const int32_t ONLY_CALLBACK_MAX_PARA = 1; + static const int32_t ONLY_CALLBACK_MIN_PARA = 0; static std::set> wantAgent_; }; } // namespace NotificationNapi diff --git a/interfaces/kits/napi/ans/include/publish.h b/interfaces/kits/napi/ans/include/publish.h index 6d8405209b1d24bdfadfd4ef6ffc2c8a5d776204..40db6ba7fe200cd322e98e6aecbe90afb2824297 100644 --- a/interfaces/kits/napi/ans/include/publish.h +++ b/interfaces/kits/napi/ans/include/publish.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -21,6 +21,8 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; napi_value Publish(napi_env env, napi_callback_info info); +napi_value ShowNotification(napi_env env, napi_callback_info info); +napi_value PublishAsBundle(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/reminder/publish.h b/interfaces/kits/napi/ans/include/reminder/publish.h index bb312474615cbf8a898af5f8983d892fa18bf37d..c9a824c963a239240a5ee5f388acdbacbc6f9d4b 100644 --- a/interfaces/kits/napi/ans/include/reminder/publish.h +++ b/interfaces/kits/napi/ans/include/reminder/publish.h @@ -54,6 +54,15 @@ napi_value GetValidReminders(napi_env env, napi_callback_info info); * @return opaque pointer that is used to represent a JavaScript value */ napi_value PublishReminder(napi_env env, napi_callback_info info); + +/** + * @brief Adds a slot type. + * + * @param env Indicates the context. + * @param info Indicates the opaque datatype about the context. + * @return opaque pointer that is used to represent a JavaScript value. + */ +napi_value AddSlot(napi_env env, napi_callback_info info); } // namespace ReminderAgentNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/include/reminder/reminder_common.h b/interfaces/kits/napi/ans/include/reminder/reminder_common.h index 63b1d0f796e16be16994fb08cf4814b07b22c48d..3a6821603fb0016e40788bd8411c5c79d6d8c775 100644 --- a/interfaces/kits/napi/ans/include/reminder/reminder_common.h +++ b/interfaces/kits/napi/ans/include/reminder/reminder_common.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 diff --git a/interfaces/kits/napi/ans/include/slot.h b/interfaces/kits/napi/ans/include/slot.h index d7aaca4d26f0b899668c6e616abe185e0f4223a0..5ea7ec97b078b91fc3b2137ea42989bc45d70036 100644 --- a/interfaces/kits/napi/ans/include/slot.h +++ b/interfaces/kits/napi/ans/include/slot.h @@ -30,6 +30,8 @@ napi_value GetSlots(napi_env env, napi_callback_info info); napi_value GetSlotsByBundle(napi_env env, napi_callback_info info); napi_value RemoveSlot(napi_env env, napi_callback_info info); napi_value RemoveAllSlots(napi_env env, napi_callback_info info); +napi_value EnableNotificationSlot(napi_env env, napi_callback_info info); +napi_value IsEnableNotificationSlot(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/include/subscribe.h b/interfaces/kits/napi/ans/include/subscribe.h index 193de4582d67a284e65dcf57e9b00e5da27ac466..c06a546025a24e7985271688bb71ce975bf36af3 100644 --- a/interfaces/kits/napi/ans/include/subscribe.h +++ b/interfaces/kits/napi/ans/include/subscribe.h @@ -24,34 +24,100 @@ using namespace OHOS::Notification; class SubscriberInstance : public NotificationSubscriber { public: SubscriberInstance(); - virtual ~SubscriberInstance(); + /** + * @brief Called back when a notification is canceled. + * + * @param request Indicates the canceled NotificationRequest object. + */ virtual void OnCanceled(const std::shared_ptr &request) override; + /** + * @brief Called back when a notification is canceled. + * + * @param request Indicates the canceled NotificationRequest object. + * @param sortingMap Indicates the sorting map used by the current subscriber to obtain notification ranking + * information. + * @param deleteReason Indicates the reason for the deletion. For details, see NotificationConstant. + */ virtual void OnCanceled(const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason) override; + const std::shared_ptr &sortingMap, int32_t deleteReason) override; + /** + * @brief Called back when a notification is canceled. + * + * @param request Indicates the received NotificationRequest object. + */ virtual void OnConsumed(const std::shared_ptr &request) override; + /** + * @brief Called back when a notification is canceled. + * + * @param request Indicates the received NotificationRequest object. + * @param sortingMap Indicates the sorting map used by the current subscriber to obtain notification ranking + * information. + */ virtual void OnConsumed(const std::shared_ptr &request, const std::shared_ptr &sortingMap) override; + /** + * @brief Called back when a notification is canceled. + * + * @param sortingMap Indicates the sorting map used to obtain notification ranking information. + */ virtual void OnUpdate(const std::shared_ptr &sortingMap) override; + /** + * @brief Called back when a notification is canceled. + * + */ virtual void OnConnected() override; + /** + * @brief Called back when the subscriber is disconnected from the ANS. + * + */ virtual void OnDisconnected() override; + /** + * @brief Called back when connection to the ANS has died. + * + */ virtual void OnDied() override; + /** + * @brief Called when the Do Not Disturb mode type changes. + * + * @param date Indicates the NotificationDoNotDisturbDate object. + */ virtual void OnDoNotDisturbDateChange(const std::shared_ptr &date) override; + /** + * @brief Called when the enabled notification changes. + * + * @param callbackData Indicates the EnabledNotificationCallbackData object. + */ virtual void OnEnabledNotificationChanged( const std::shared_ptr &callbackData) override; + /** + * @brief Sets the callback information by type. + * + * @param env Indicates the environment that the API is invoked under. + * @param type Indicates the type of callback. + * @param ref Indicates the napi_ref of callback. + */ void SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref); + /** + * @brief Sets the object deleting status. + * + * @param status Indicates the deleting status. + * @return Returns true if success, returns false otherwise + */ + bool SetObjectDeleting(bool status); + private: void SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref); @@ -86,6 +152,9 @@ private: CallbackInfo disturbModeCallbackInfo_; CallbackInfo disturbDateCallbackInfo_; CallbackInfo enabledNotificationCallbackInfo_; + + std::mutex delMutex_; + bool isDelete_ = false; }; struct SubscriberInstancesInfo { diff --git a/interfaces/kits/napi/ans/src/ans_template.cpp b/interfaces/kits/napi/ans/src/ans_template.cpp index 8c33a73f75dda73d4f59f4474657d91cdff55736..ebce81e33f4c92902602ec880aa8e5ebbce9d387 100644 --- a/interfaces/kits/napi/ans/src/ans_template.cpp +++ b/interfaces/kits/napi/ans/src/ans_template.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -87,25 +87,24 @@ napi_value IsSupportTemplate(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("IsSupportTemplate napi_create_async_work start"); - AsyncCallbackInfoTemplate *asyncCallbackinfo = (AsyncCallbackInfoTemplate *)data; + AsyncCallbackInfoTemplate *asyncCallbackinfo = static_cast(data); - asyncCallbackinfo->info.errorCode = NotificationHelper::IsSupportTemplate( - asyncCallbackinfo->params.templateName, asyncCallbackinfo->params.support); + if (asyncCallbackinfo) { + asyncCallbackinfo->info.errorCode = NotificationHelper::IsSupportTemplate( + asyncCallbackinfo->params.templateName, asyncCallbackinfo->params.support); + } }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("IsSupportTemplate napi_create_async_work end"); - AsyncCallbackInfoTemplate *asyncCallbackinfo = (AsyncCallbackInfoTemplate *)data; - - napi_value result = nullptr; - napi_get_boolean(env, asyncCallbackinfo->params.support, &result); - Common::ReturnCallbackPromise(env, asyncCallbackinfo->info, result); - - if (asyncCallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asyncCallbackinfo->info.callback); - } - - napi_delete_async_work(env, asyncCallbackinfo->asyncWork); - if (asyncCallbackinfo != nullptr) { + AsyncCallbackInfoTemplate *asyncCallbackinfo = static_cast(data); + if (asyncCallbackinfo) { + napi_value result = nullptr; + napi_get_boolean(env, asyncCallbackinfo->params.support, &result); + Common::ReturnCallbackPromise(env, asyncCallbackinfo->info, result); + if (asyncCallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asyncCallbackinfo->info.callback); + } + napi_delete_async_work(env, asyncCallbackinfo->asyncWork); delete asyncCallbackinfo; asyncCallbackinfo = nullptr; } diff --git a/interfaces/kits/napi/ans/src/cancel.cpp b/interfaces/kits/napi/ans/src/cancel.cpp index 799bc5cd8fd6861ccc5600d76cd9c17589af786f..becba51297e1859d90aef416a9204a8616ad0707 100644 --- a/interfaces/kits/napi/ans/src/cancel.cpp +++ b/interfaces/kits/napi/ans/src/cancel.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -17,12 +17,13 @@ namespace OHOS { namespace NotificationNapi { -const int CANCEL_MAX_PARA = 3; -const int CANCEL_GROUP_MAX_PARA = 2; -const int CANCEL_GROUP_MIN_PARA = 1; +constexpr int8_t CANCEL_MAX_PARA = 3; +constexpr int8_t CANCEL_GROUP_MAX_PARA = 2; +constexpr int8_t CANCEL_GROUP_MIN_PARA = 1; +constexpr int8_t CANCEL_AS_BUNDLE_MAX_PARA = 4; struct ParametersInfoCancel { - int id = 0; + int32_t id = 0; std::string label = ""; napi_ref callback = nullptr; }; @@ -30,7 +31,7 @@ struct ParametersInfoCancel { struct AsyncCallbackInfoCancel { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - int id = 0; + int32_t id = 0; std::string label; CallbackPromiseInfo info; }; @@ -47,6 +48,22 @@ struct AsyncCallbackInfoCancelGroup { ParametersInfoCancelGroup params {}; }; +struct ParametersInfoCancelAsBundle { + int32_t id = 0; + std::string representativeBundle = ""; + int32_t userId = 0; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoCancelAsBundle { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + int32_t id = 0; + std::string representativeBundle = ""; + int32_t userId = 0; + CallbackPromiseInfo info; +}; + napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, ParametersInfoCancel ¶s) { ANS_LOGI("enter"); @@ -55,20 +72,27 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[CANCEL_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + if (argc < 1) { + ANS_LOGW("Wrong number of arguments"); + return nullptr; + } napi_valuetype valuetype = napi_undefined; // argv[0]: id: number NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + if (valuetype != napi_number) { + ANS_LOGW("Wrong argument type. Number expected."); + return nullptr; + } NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM0], ¶s.id)); // argv[1]: label: string / callback if (argc >= CANCEL_MAX_PARA - 1) { NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, - (valuetype == napi_string || valuetype == napi_function), - "Wrong argument type. String or function expected."); + if (valuetype != napi_string && valuetype != napi_function) { + ANS_LOGW("Wrong argument type. String or function expected."); + return nullptr; + } if (valuetype == napi_string) { char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; @@ -82,7 +106,10 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[2]: callback if (argc >= CANCEL_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, argv[PARAM2], 1, ¶s.callback); } @@ -97,12 +124,18 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[CANCEL_GROUP_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= CANCEL_GROUP_MIN_PARA, "Wrong number of arguments"); + if (argc < CANCEL_GROUP_MIN_PARA) { + ANS_LOGW("Wrong number of arguments"); + return nullptr; + } napi_valuetype valuetype = napi_undefined; // argv[0]: groupName: string NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + if (valuetype != napi_string) { + ANS_LOGW("Wrong argument type. String expected."); + return nullptr; + } char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; NAPI_CALL(env, napi_get_value_string_utf8(env, argv[PARAM0], str, STR_MAX_SIZE - 1, &strLen)); @@ -111,7 +144,10 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[1]: callback if (argc >= CANCEL_GROUP_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, argv[PARAM1], 1, ¶s.callback); } @@ -143,23 +179,22 @@ napi_value Cancel(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("Cancel napi_create_async_work start"); - AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; + AsyncCallbackInfoCancel *asynccallbackinfo = static_cast(data); - asynccallbackinfo->info.errorCode = - NotificationHelper::CancelNotification(asynccallbackinfo->label, asynccallbackinfo->id); + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = + NotificationHelper::CancelNotification(asynccallbackinfo->label, asynccallbackinfo->id); + } }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("Cancel napi_create_async_work end"); - AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + AsyncCallbackInfoCancel *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -201,21 +236,20 @@ napi_value CancelAll(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("CancelAll napi_create_async_work start"); - AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; - asynccallbackinfo->info.errorCode = NotificationHelper::CancelAllNotifications(); + AsyncCallbackInfoCancel *asynccallbackinfo = static_cast(data); + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = NotificationHelper::CancelAllNotifications(); + } }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("CancelAll napi_create_async_work end"); - AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + AsyncCallbackInfoCancel *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -257,23 +291,139 @@ napi_value CancelGroup(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("CancelGroup napi_create_async_work start"); - AsyncCallbackInfoCancelGroup *asynccallbackinfo = (AsyncCallbackInfoCancelGroup *)data; - ANS_LOGI("asynccallbackinfo->params.groupName = %{public}s", asynccallbackinfo->params.groupName.c_str()); - asynccallbackinfo->info.errorCode = - NotificationHelper::CancelGroup(asynccallbackinfo->params.groupName); + AsyncCallbackInfoCancelGroup *asynccallbackinfo = static_cast(data); + if (asynccallbackinfo) { + ANS_LOGI("asynccallbackinfo->params.groupName = %{public}s", + asynccallbackinfo->params.groupName.c_str()); + asynccallbackinfo->info.errorCode = + NotificationHelper::CancelGroup(asynccallbackinfo->params.groupName); + } }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("CancelGroup napi_create_async_work end"); - AsyncCallbackInfoCancelGroup *asynccallbackinfo = (AsyncCallbackInfoCancelGroup *)data; + AsyncCallbackInfoCancelGroup *asynccallbackinfo = static_cast(data); + if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, ParametersInfoCancelAsBundle ¶s) +{ + ANS_LOGI("enter"); - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + size_t argc = CANCEL_AS_BUNDLE_MAX_PARA; + napi_value argv[CANCEL_AS_BUNDLE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + if (argc < 1) { + ANS_LOGW("Wrong number of arguments"); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + // argv[0]: id: number + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if (valuetype != napi_number) { + ANS_LOGW("Wrong argument type. Number expected."); + return nullptr; + } + NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM0], ¶s.id)); + + // argv[1]: representativeBundle: string + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if (valuetype != napi_string) { + ANS_LOGW("Wrong argument type. String expected."); + return nullptr; + } + + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + napi_get_value_string_utf8(env, argv[PARAM1], str, STR_MAX_SIZE - 1, &strLen); + paras.representativeBundle = str; + + // argv[2] : userId + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); + if (valuetype != napi_number) { + ANS_LOGW("Wrong argument type. Number expected."); + return nullptr; + } + napi_get_value_int32(env, argv[PARAM2], ¶s.userId); + + // argv[3]: callback + if (argc >= CANCEL_AS_BUNDLE_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM3], &valuetype)); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } + napi_create_reference(env, argv[PARAM2], 1, ¶s.callback); + } + + return Common::NapiGetNull(env); +} + +napi_value CancelAsBundle(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + ParametersInfoCancelAsBundle paras; + if (ParseParameters(env, info, paras) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoCancelAsBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoCancelAsBundle { + .env = env, .asyncWork = nullptr, + .id = paras.id, + .representativeBundle = paras.representativeBundle, + .userId = paras.userId + }; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "cancelasbundle", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("Cancel napi_create_async_work start"); + AsyncCallbackInfoCancelAsBundle *asynccallbackinfo = static_cast(data); + + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = NotificationHelper::CancelAsBundle( + asynccallbackinfo->id, asynccallbackinfo->representativeBundle, asynccallbackinfo->userId); + } + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("Cancel napi_create_async_work end"); + AsyncCallbackInfoCancelAsBundle *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 3590331e913567285aea7d7e11e7442a225cbcc7..e03ebc096316afc059f342f16bfa859925f69f4d 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -48,7 +48,7 @@ napi_value Common::NapiGetUndefined(napi_env env) return result; } -napi_value Common::GetCallbackErrorValue(napi_env env, int errCode) +napi_value Common::GetCallbackErrorValue(napi_env env, int32_t errCode) { napi_value result = nullptr; napi_value eCode = nullptr; @@ -86,7 +86,7 @@ void Common::ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInf } void Common::SetCallback( - const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result) + const napi_env &env, const napi_ref &callbackIn, const int32_t &errorCode, const napi_value &result) { ANS_LOGI("enter"); napi_value undefined = nullptr; @@ -117,7 +117,7 @@ void Common::SetCallback( } void Common::SetPromise( - const napi_env &env, const napi_deferred &deferred, const int &errorCode, const napi_value &result) + const napi_env &env, const napi_deferred &deferred, const int32_t &errorCode, const napi_value &result) { ANS_LOGI("enter"); if (errorCode == ERR_OK) { @@ -132,13 +132,12 @@ napi_value Common::JSParaError(const napi_env &env, const napi_ref &callback) { if (callback) { return Common::NapiGetNull(env); - } else { - napi_value promise = nullptr; - napi_deferred deferred = nullptr; - napi_create_promise(env, &deferred, &promise); - SetPromise(env, deferred, ERROR, Common::NapiGetNull(env)); - return promise; } + napi_value promise = nullptr; + napi_deferred deferred = nullptr; + napi_create_promise(env, &deferred, &promise); + SetPromise(env, deferred, ERROR, Common::NapiGetNull(env)); + return promise; } napi_value Common::ParseParaOnlyCallback(const napi_env &env, const napi_callback_info &info, napi_ref &callback) @@ -174,11 +173,15 @@ napi_value Common::SetNotificationByDistributedOptions( NotificationDistributedOptions options = notification->GetNotificationRequest().GetNotificationDistributedOptions(); napi_value value = nullptr; // isDistributed?: boolean - napi_get_boolean(env, options.IsDistributed(), &value); + if (notification->GetDeviceId().empty()) { + napi_get_boolean(env, false, &value); + } else { + napi_get_boolean(env, options.IsDistributed(), &value); + } napi_set_named_property(env, result, "isDistributed", value); // supportDisplayDevices?: Array - int count = 0; + uint32_t count = 0; napi_value arrSupportDisplayDevices = nullptr; napi_create_array(env, &arrSupportDisplayDevices); std::vector displayDevices = options.GetDevicesSupportDisplay(); @@ -239,22 +242,38 @@ napi_value Common::SetNotification( napi_get_boolean(env, notification->IsFloatingIcon(), &value); napi_set_named_property(env, result, "isFloatingIcon", value); - // readonly creatorBundleName?: string - napi_create_string_utf8(env, notification->GetCreateBundle().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "creatorBundleName", value); + if (notification->GetNotificationRequest().IsAgentNotification()) { + // Agent notification, replace creator with owner + // readonly creatorBundleName?: string + napi_create_string_utf8( + env, notification->GetNotificationRequest().GetOwnerBundleName().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "creatorBundleName", value); - // readonly creatorUid?: number - napi_create_int32(env, notification->GetUid(), &value); - napi_set_named_property(env, result, "creatorUid", value); + // readonly creatorUid?: number + napi_create_int32(env, notification->GetNotificationRequest().GetOwnerUid(), &value); + napi_set_named_property(env, result, "creatorUid", value); + + // readonly creatorUserId?: number + napi_create_int32(env, notification->GetNotificationRequest().GetOwnerUserId(), &value); + napi_set_named_property(env, result, "creatorUserId", value); + } else { + // readonly creatorBundleName?: string + napi_create_string_utf8(env, notification->GetCreateBundle().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "creatorBundleName", value); + + // readonly creatorUid?: number + napi_create_int32(env, notification->GetUid(), &value); + napi_set_named_property(env, result, "creatorUid", value); + + // readonly creatorUserId?: number + napi_create_int32(env, notification->GetUserId(), &value); + napi_set_named_property(env, result, "creatorUserId", value); + } // readonly creatorPid?: number napi_create_int32(env, notification->GetPid(), &value); napi_set_named_property(env, result, "creatorPid", value); - // readonly creatorUserId?: number - napi_create_int32(env, notification->GetUserId(), &value); - napi_set_named_property(env, result, "creatorUserId", value); - // distributedOption?:DistributedOptions napi_value distributedResult = nullptr; napi_create_object(env, &distributedResult); @@ -354,7 +373,7 @@ napi_value Common::SetNotificationRequestByNumber( napi_set_named_property(env, result, "color", value); // badgeIconStyle ?: number - int badgeIconStyle = (int)request->GetBadgeIconStyle(); + auto badgeIconStyle = static_cast(request->GetBadgeIconStyle()); napi_create_int32(env, badgeIconStyle, &value); napi_set_named_property(env, result, "badgeIconStyle", value); @@ -538,7 +557,7 @@ napi_value Common::SetNotificationRequestByCustom( // actionButtons?: Array napi_value arr = nullptr; - int count = 0; + uint32_t count = 0; napi_create_array(env, &arr); for (auto vec : request->GetActionButtons()) { if (vec) { @@ -767,6 +786,10 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl } napi_set_named_property(env, result, "vibrationValues", arr); + // enabled?: boolean + napi_get_boolean(env, slot.GetEnable(), &value); + napi_set_named_property(env, result, "enabled", value); + return NapiGetBoolean(env, true); } @@ -1205,14 +1228,12 @@ napi_value Common::SetNotificationActionButton( } // userInput?: NotificationUserInput - if (actionButton->GetUserInputs().size() > 0) { - napi_value userInputResult = nullptr; - napi_create_object(env, &userInputResult); - if (!SetNotificationActionButtonByUserInput(env, actionButton->GetUserInputs().front(), userInputResult)) { - return NapiGetBoolean(env, false); - } - napi_set_named_property(env, result, "userInput", userInputResult); + napi_value userInputResult = nullptr; + napi_create_object(env, &userInputResult); + if (!SetNotificationActionButtonByUserInput(env, actionButton->GetUserInput(), userInputResult)) { + return NapiGetBoolean(env, false); } + napi_set_named_property(env, result, "userInput", userInputResult); return NapiGetBoolean(env, true); } @@ -3204,7 +3225,6 @@ napi_value Common::GetConversationalMessageOtherInfo(const napi_env &env, const NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); NAPI_CALL(env, napi_get_value_string_utf8(env, uriResult, str, STR_MAX_SIZE - 1, &strLen)); uri = str; - ANS_LOGI("conversationalMessage::uri = %{public}s", str); } std::shared_ptr uriPtr = std::make_shared(uri); @@ -3273,7 +3293,6 @@ napi_value Common::GetMessageUserByString(const napi_env &env, const napi_value NAPI_CALL(env, napi_get_value_string_utf8(env, uriResult, str, STR_MAX_SIZE - 1, &strLen)); Uri uri(str); messageUser.SetUri(uri); - ANS_LOGI("MessageUser::uri = %{public}s", str); return NapiGetNull(env); } @@ -4022,9 +4041,8 @@ napi_value Common::CreateWantAgentByJS(const napi_env &env, wantAgent, (void *)agent.get(), [](napi_env env, void *data, void *hint) { - AbilityRuntime::WantAgent::WantAgent *objectInfo = (AbilityRuntime::WantAgent::WantAgent *)data; - ANS_LOGI("CreateWantAgentByJS this = %{public}p", objectInfo); - + AbilityRuntime::WantAgent::WantAgent *objectInfo = + static_cast(data); if (objectInfo) { for (auto it = wantAgent_.begin(); it != wantAgent_.end(); ++it) { if ((*it).get() == objectInfo) { diff --git a/interfaces/kits/napi/ans/src/display_badge.cpp b/interfaces/kits/napi/ans/src/display_badge.cpp index 71da17f3c3aad294f2411dd205a199a68d9c3a08..b648e0bd7b22012f1d5448128fa46c1ccc864cb7 100644 --- a/interfaces/kits/napi/ans/src/display_badge.cpp +++ b/interfaces/kits/napi/ans/src/display_badge.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -169,27 +169,26 @@ napi_value DisplayBadge(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("DisplayBadge napi_create_async_work start"); - AsyncCallbackInfoEnableBadge *asynccallbackinfo = (AsyncCallbackInfoEnableBadge *)data; - ANS_LOGI("option.bundle = %{public}s option.uid = %{public}d enable = %{public}d", - asynccallbackinfo->params.option.GetBundleName().c_str(), - asynccallbackinfo->params.option.GetUid(), - asynccallbackinfo->params.enable); - asynccallbackinfo->info.errorCode = NotificationHelper::SetShowBadgeEnabledForBundle( - asynccallbackinfo->params.option, asynccallbackinfo->params.enable); - ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); + AsyncCallbackInfoEnableBadge *asynccallbackinfo = static_cast(data); + if (asynccallbackinfo) { + ANS_LOGI("option.bundle = %{public}s option.uid = %{public}d enable = %{public}d", + asynccallbackinfo->params.option.GetBundleName().c_str(), + asynccallbackinfo->params.option.GetUid(), + asynccallbackinfo->params.enable); + asynccallbackinfo->info.errorCode = NotificationHelper::SetShowBadgeEnabledForBundle( + asynccallbackinfo->params.option, asynccallbackinfo->params.enable); + ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); + } }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("DisplayBadge napi_create_async_work end"); - AsyncCallbackInfoEnableBadge *asynccallbackinfo = (AsyncCallbackInfoEnableBadge *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + AsyncCallbackInfoEnableBadge *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -213,21 +212,16 @@ void AsyncCompleteCallbackIsBadgeDisplayed(napi_env env, napi_status status, voi ANS_LOGE("Invalid async callback data"); return; } - AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = (AsyncCallbackInfoIsDisplayBadge *)data; - + AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = static_cast(data); napi_value result = nullptr; napi_get_boolean(env, asynccallbackinfo->enabled, &result); Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value IsBadgeDisplayed(napi_env env, napi_callback_info info) @@ -256,19 +250,21 @@ napi_value IsBadgeDisplayed(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("IsBadgeDisplayed napi_create_async_work start"); - AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = (AsyncCallbackInfoIsDisplayBadge *)data; - - if (asynccallbackinfo->params.hasBundleOption) { - ANS_LOGI("option.bundle = %{public}s option.uid = %{public}d", - asynccallbackinfo->params.option.GetBundleName().c_str(), - asynccallbackinfo->params.option.GetUid()); - asynccallbackinfo->info.errorCode = NotificationHelper::GetShowBadgeEnabledForBundle( - asynccallbackinfo->params.option, asynccallbackinfo->enabled); - } else { - asynccallbackinfo->info.errorCode = NotificationHelper::GetShowBadgeEnabled(asynccallbackinfo->enabled); + AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = static_cast(data); + if (asynccallbackinfo) { + if (asynccallbackinfo->params.hasBundleOption) { + ANS_LOGI("option.bundle = %{public}s option.uid = %{public}d", + asynccallbackinfo->params.option.GetBundleName().c_str(), + asynccallbackinfo->params.option.GetUid()); + asynccallbackinfo->info.errorCode = NotificationHelper::GetShowBadgeEnabledForBundle( + asynccallbackinfo->params.option, asynccallbackinfo->enabled); + } else { + asynccallbackinfo->info.errorCode = NotificationHelper::GetShowBadgeEnabled( + asynccallbackinfo->enabled); + } + ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d, enabled = %{public}d", + asynccallbackinfo->info.errorCode, asynccallbackinfo->enabled); } - ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d, enabled = %{public}d", - asynccallbackinfo->info.errorCode, asynccallbackinfo->enabled); }, AsyncCompleteCallbackIsBadgeDisplayed, (void *)asynccallbackinfo, diff --git a/interfaces/kits/napi/ans/src/distributed.cpp b/interfaces/kits/napi/ans/src/distributed.cpp index 01e1e541de60c51c8e4d87e14da956e4c8789007..3eb314dc520389add0fdb8bcd37eb3d08e7d5dfc 100644 --- a/interfaces/kits/napi/ans/src/distributed.cpp +++ b/interfaces/kits/napi/ans/src/distributed.cpp @@ -177,25 +177,20 @@ void AsyncCompleteCallbackIsDistributedEnabled(napi_env env, napi_status status, return; } ANS_LOGI("IsDistributedEnabled napi_create_async_work end"); - AsyncCallbackInfoIsEnabled *asynccallbackinfo = (AsyncCallbackInfoIsEnabled *)data; + AsyncCallbackInfoIsEnabled *asynccallbackinfo = static_cast(data); napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { result = Common::NapiGetNull(env); } else { napi_get_boolean(env, asynccallbackinfo->enable, &result); } - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value IsDistributedEnabled(napi_env env, napi_callback_info info) @@ -224,11 +219,13 @@ napi_value IsDistributedEnabled(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("IsDistributedEnabled napi_create_async_work start"); - AsyncCallbackInfoIsEnabled *asynccallbackinfo = (AsyncCallbackInfoIsEnabled *)data; + AsyncCallbackInfoIsEnabled *asynccallbackinfo = static_cast(data); - asynccallbackinfo->info.errorCode = - NotificationHelper::IsDistributedEnabled(asynccallbackinfo->enable); - ANS_LOGI("IsDistributedEnabled enable = %{public}d", asynccallbackinfo->enable); + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = + NotificationHelper::IsDistributedEnabled(asynccallbackinfo->enable); + ANS_LOGI("IsDistributedEnabled enable = %{public}d", asynccallbackinfo->enable); + } }, AsyncCompleteCallbackIsDistributedEnabled, (void *)asynccallbackinfo, @@ -269,23 +266,22 @@ napi_value EnableDistributed(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("EnableDistributed napi_create_async_work start"); - AsyncCallbackInfoEnabled *asynccallbackinfo = (AsyncCallbackInfoEnabled *)data; + AsyncCallbackInfoEnabled *asynccallbackinfo = static_cast(data); - asynccallbackinfo->info.errorCode = - NotificationHelper::EnableDistributed(asynccallbackinfo->params.enable); + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = + NotificationHelper::EnableDistributed(asynccallbackinfo->params.enable); + } }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("EnableDistributed napi_create_async_work end"); - AsyncCallbackInfoEnabled *asynccallbackinfo = (AsyncCallbackInfoEnabled *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + AsyncCallbackInfoEnabled *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -328,23 +324,20 @@ napi_value EnableDistributedByBundle(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("EnableDistributedByBundle napi_create_async_work start"); - AsyncCallbackInfoEnabledByBundle *asynccallbackinfo = (AsyncCallbackInfoEnabledByBundle *)data; + AsyncCallbackInfoEnabledByBundle *asynccallbackinfo = static_cast(data); asynccallbackinfo->info.errorCode = NotificationHelper::EnableDistributedByBundle( asynccallbackinfo->params.option, asynccallbackinfo->params.enable); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("EnableDistributedByBundle napi_create_async_work end"); - AsyncCallbackInfoEnabledByBundle *asynccallbackinfo = (AsyncCallbackInfoEnabledByBundle *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + AsyncCallbackInfoEnabledByBundle *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -396,15 +389,12 @@ napi_value EnableDistributedSelf(napi_env env, napi_callback_info info) [](napi_env env, napi_status status, void *data) { ANS_LOGI("EnableDistributedSelf napi_create_async_work end"); AsyncCallbackInfoEnabled *asynccallbackinfo = (AsyncCallbackInfoEnabled *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -429,7 +419,7 @@ void AsyncCompleteCallbackIsDistributedEnableByBundle(napi_env env, napi_status return; } ANS_LOGI("IsDistributedEnableByBundle napi_create_async_work end"); - AsyncCallbackInfoIsEnabledByBundle *asynccallbackinfo = (AsyncCallbackInfoIsEnabledByBundle *)data; + AsyncCallbackInfoIsEnabledByBundle *asynccallbackinfo = static_cast(data); napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { result = Common::NapiGetNull(env); @@ -437,16 +427,12 @@ void AsyncCompleteCallbackIsDistributedEnableByBundle(napi_env env, napi_status napi_get_boolean(env, asynccallbackinfo->enable, &result); } Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value IsDistributedEnableByBundle(napi_env env, napi_callback_info info) @@ -501,7 +487,7 @@ void AsyncCompleteCallbackGetDeviceRemindType(napi_env env, napi_status status, return; } ANS_LOGI("GetDeviceRemindType napi_create_async_work end"); - AsyncCallbackInfoGetRemindType *asynccallbackinfo = (AsyncCallbackInfoGetRemindType *)data; + AsyncCallbackInfoGetRemindType *asynccallbackinfo = static_cast(data); napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { result = Common::NapiGetNull(env); @@ -514,16 +500,12 @@ void AsyncCompleteCallbackGetDeviceRemindType(napi_env env, napi_status status, napi_create_int32(env, (int32_t)outType, &result); } Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value GetDeviceRemindType(napi_env env, napi_callback_info info) diff --git a/interfaces/kits/napi/ans/src/disturb_mode.cpp b/interfaces/kits/napi/ans/src/disturb_mode.cpp index 0bf8a47fb891dbf44868103c485cba7a3c79eafb..e901f02856a25a8e521599ea723d8a0150d5721f 100644 --- a/interfaces/kits/napi/ans/src/disturb_mode.cpp +++ b/interfaces/kits/napi/ans/src/disturb_mode.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -197,7 +197,7 @@ napi_value SetDoNotDisturbDate(napi_env env, napi_callback_info info) napi_create_async_work(env, nullptr, resourceName, [](napi_env env, void *data) { ANS_LOGI("SetDoNotDisturbDate napi_create_async_work start"); - AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoSetDoNotDisturb *)data; + AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = static_cast(data); if (asynccallbackinfo->params.hasUserId) { asynccallbackinfo->info.errorCode = NotificationHelper::SetDoNotDisturbDate( asynccallbackinfo->params.userId, asynccallbackinfo->params.date); @@ -205,23 +205,20 @@ napi_value SetDoNotDisturbDate(napi_env env, napi_callback_info info) asynccallbackinfo->info.errorCode = NotificationHelper::SetDoNotDisturbDate( asynccallbackinfo->params.date); } - + ANS_LOGI("SetDoNotDisturbDate date=%{public}s errorCode=%{public}d, hasUserId=%{public}d", asynccallbackinfo->params.date.Dump().c_str(), asynccallbackinfo->info.errorCode, asynccallbackinfo->params.hasUserId); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("SetDoNotDisturbDate napi_create_async_work end"); - AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoSetDoNotDisturb *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -244,7 +241,7 @@ void AsyncCompleteCallbackGetDoNotDisturbDate(napi_env env, napi_status status, ANS_LOGE("Invalid async callback data"); return; } - AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoGetDoNotDisturb *)data; + AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = static_cast(data); napi_value result = Common::NapiGetNull(env); if (asynccallbackinfo->info.errorCode == ERR_OK) { napi_create_object(env, &result); @@ -252,18 +249,13 @@ void AsyncCompleteCallbackGetDoNotDisturbDate(napi_env env, napi_status status, asynccallbackinfo->info.errorCode = ERROR; } } - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetDoNotDisturbDateParams ¶ms) @@ -308,13 +300,13 @@ napi_value GetDoNotDisturbDate(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); - SetDoNotDisturbDateParams params {}; + GetDoNotDisturbDateParams params {}; if (ParseParameters(env, info, params) == nullptr) { return Common::NapiGetUndefined(env); } - AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoSetDoNotDisturb {.env = env, .asyncWork = nullptr, .params = params}; + AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetDoNotDisturb {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { return Common::JSParaError(env, params.callback); } @@ -329,7 +321,7 @@ napi_value GetDoNotDisturbDate(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetDoNotDisturbDate napi_create_async_work start"); - AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoGetDoNotDisturb *)data; + AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = static_cast(data); if (asynccallbackinfo->params.hasUserId) { asynccallbackinfo->info.errorCode = NotificationHelper::GetDoNotDisturbDate( asynccallbackinfo->params.userId, asynccallbackinfo->date); @@ -381,7 +373,8 @@ napi_value SupportDoNotDisturbMode(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("SupportDoNotDisturbMode napi_create_async_work start"); - AsyncCallbackInfoSupportDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoSupportDoNotDisturb *)data; + AsyncCallbackInfoSupportDoNotDisturb *asynccallbackinfo = + static_cast(data); asynccallbackinfo->info.errorCode = NotificationHelper::DoesSupportDoNotDisturbMode(asynccallbackinfo->isSupported); ANS_LOGI("SupportDoNotDisturbMode errorCode=%{public}d isSupported=%{public}d", @@ -389,18 +382,16 @@ napi_value SupportDoNotDisturbMode(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("SupportDoNotDisturbMode napi_create_async_work end"); - AsyncCallbackInfoSupportDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoSupportDoNotDisturb *)data; - - napi_value result = nullptr; - napi_get_boolean(env, asynccallbackinfo->isSupported, &result); - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + AsyncCallbackInfoSupportDoNotDisturb *asynccallbackinfo = + static_cast(data); if (asynccallbackinfo) { + napi_value result = nullptr; + napi_get_boolean(env, asynccallbackinfo->isSupported, &result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } diff --git a/interfaces/kits/napi/ans/src/enable_notification.cpp b/interfaces/kits/napi/ans/src/enable_notification.cpp index ee5f3299000e22439a3963d51a10b02a21765ef5..de7e99a4e2b61ce7fd8d74f088f870d29e4a4e3f 100644 --- a/interfaces/kits/napi/ans/src/enable_notification.cpp +++ b/interfaces/kits/napi/ans/src/enable_notification.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -151,19 +151,14 @@ void AsyncCompleteCallbackEnableNotification(napi_env env, napi_status status, v ANS_LOGE("Invalid async callback data"); return; } - AsyncCallbackInfoEnable *asynccallbackinfo = (AsyncCallbackInfoEnable *)data; - + AsyncCallbackInfoEnable *asynccallbackinfo = static_cast(data); Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value EnableNotification(napi_env env, napi_callback_info info) @@ -191,7 +186,7 @@ napi_value EnableNotification(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("EnableNotification napi_create_async_work start"); - AsyncCallbackInfoEnable *asynccallbackinfo = (AsyncCallbackInfoEnable *)data; + AsyncCallbackInfoEnable *asynccallbackinfo = static_cast(data); std::string deviceId {""}; asynccallbackinfo->info.errorCode = NotificationHelper::SetNotificationsEnabledForSpecifiedBundle( asynccallbackinfo->params.option, deviceId, asynccallbackinfo->params.enable); @@ -217,21 +212,16 @@ void AsyncCompleteCallbackIsNotificationEnabled(napi_env env, napi_status status ANS_LOGE("Invalid async callback data"); return; } - AsyncCallbackInfoIsEnable *asynccallbackinfo = (AsyncCallbackInfoIsEnable *)data; - + AsyncCallbackInfoIsEnable *asynccallbackinfo = static_cast(data); napi_value result = nullptr; napi_get_boolean(env, asynccallbackinfo->allowed, &result); Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value IsNotificationEnabled(napi_env env, napi_callback_info info) @@ -259,7 +249,7 @@ napi_value IsNotificationEnabled(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("IsNotificationEnabled napi_create_async_work start"); - AsyncCallbackInfoIsEnable *asynccallbackinfo = (AsyncCallbackInfoIsEnable *)data; + AsyncCallbackInfoIsEnable *asynccallbackinfo = static_cast(data); if (asynccallbackinfo->params.hasBundleOption) { ANS_LOGI("option.bundle = %{public}s option.uid = %{public}d", @@ -315,7 +305,7 @@ napi_value IsNotificationEnabledSelf(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("IsNotificationEnabledSelf napi_create_async_work start"); - AsyncCallbackInfoIsEnable *asynccallbackinfo = (AsyncCallbackInfoIsEnable *)data; + AsyncCallbackInfoIsEnable *asynccallbackinfo = static_cast(data); if (asynccallbackinfo->params.hasBundleOption) { ANS_LOGE("Not allowed to query another application"); @@ -364,7 +354,7 @@ napi_value RequestEnableNotification(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("RequestEnableNotification napi_create_async_work start"); - AsyncCallbackInfoIsEnable *asynccallbackinfo = (AsyncCallbackInfoIsEnable *)data; + AsyncCallbackInfoIsEnable *asynccallbackinfo = static_cast(data); std::string deviceId {""}; asynccallbackinfo->info.errorCode = NotificationHelper::RequestEnableNotification(deviceId); diff --git a/interfaces/kits/napi/ans/src/get_active.cpp b/interfaces/kits/napi/ans/src/get_active.cpp index f924d7f8fab40f1f46069a824d92fb8a447a2b96..ad798f0fac08a2c2eaec264ebad99d6370ca1ab6 100644 --- a/interfaces/kits/napi/ans/src/get_active.cpp +++ b/interfaces/kits/napi/ans/src/get_active.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -23,7 +23,7 @@ struct AsyncCallbackInfoActive { CallbackPromiseInfo info; std::vector> notifications; std::vector> requests; - int32_t num = 0; + uint64_t num = 0; }; void AsyncCompleteCallbackGetAllActiveNotifications(napi_env env, napi_status status, void *data) @@ -35,13 +35,13 @@ void AsyncCompleteCallbackGetAllActiveNotifications(napi_env env, napi_status st return; } - auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = static_cast(data); napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { result = Common::NapiGetNull(env); } else { napi_value arr = nullptr; - int count = 0; + int32_t count = 0; napi_create_array(env, &arr); for (auto vec : asynccallbackinfo->notifications) { if (!vec) { @@ -64,18 +64,13 @@ void AsyncCompleteCallbackGetAllActiveNotifications(napi_env env, napi_status st result = Common::NapiGetNull(env); } } - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) @@ -104,7 +99,7 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetAllActiveNotifications napi_create_async_work start"); - auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = static_cast(data); asynccallbackinfo->info.errorCode = NotificationHelper::GetAllActiveNotifications(asynccallbackinfo->notifications); @@ -131,13 +126,13 @@ void AsyncCompleteCallbackGetActiveNotifications(napi_env env, napi_status statu return; } - auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = static_cast(data); napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { result = Common::NapiGetNull(env); } else { napi_value arr = nullptr; - int count = 0; + int32_t count = 0; napi_create_array(env, &arr); for (auto vec : asynccallbackinfo->requests) { if (!vec) { @@ -161,16 +156,12 @@ void AsyncCompleteCallbackGetActiveNotifications(napi_env env, napi_status statu } } Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value GetActiveNotifications(napi_env env, napi_callback_info info) @@ -199,7 +190,7 @@ napi_value GetActiveNotifications(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetActiveNotifications napi_create_async_work start"); - auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = static_cast(data); asynccallbackinfo->info.errorCode = NotificationHelper::GetActiveNotifications(asynccallbackinfo->requests); @@ -226,25 +217,20 @@ void AsyncCompleteCallbackGetActiveNotificationCount(napi_env env, napi_status s return; } - auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = static_cast(data); napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { result = Common::NapiGetNull(env); } else { - napi_create_int32(env, asynccallbackinfo->num, &result); + napi_create_uint32(env, asynccallbackinfo->num, &result); } - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value GetActiveNotificationCount(napi_env env, napi_callback_info info) @@ -273,10 +259,10 @@ napi_value GetActiveNotificationCount(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetActiveNotificationCount napi_create_async_work start"); - auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = static_cast(data); asynccallbackinfo->info.errorCode = NotificationHelper::GetActiveNotificationNums(asynccallbackinfo->num); - ANS_LOGI("GetActiveNotificationCount count = %{public}d", asynccallbackinfo->num); + ANS_LOGI("GetActiveNotificationCount count = %{public}" PRIu64 "", asynccallbackinfo->num); }, AsyncCompleteCallbackGetActiveNotificationCount, (void *)asynccallbackinfo, diff --git a/interfaces/kits/napi/ans/src/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index 2a26b7ce35f7443ec3d14cf9f9d38427b8ecb1c4..e1136712bf3705e165cf945f66bb5b851f269a40 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -43,6 +43,7 @@ napi_value NotificationInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("subscribe", Subscribe), DECLARE_NAPI_FUNCTION("unsubscribe", Unsubscribe), DECLARE_NAPI_FUNCTION("publish", Publish), + DECLARE_NAPI_FUNCTION("publishAsBundle", PublishAsBundle), DECLARE_NAPI_FUNCTION("remove", Remove), DECLARE_NAPI_FUNCTION("removeAll", RemoveAll), DECLARE_NAPI_FUNCTION("getAllActiveNotifications", GetAllActiveNotifications), @@ -51,6 +52,7 @@ napi_value NotificationInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("cancel", Cancel), DECLARE_NAPI_FUNCTION("cancelAll", CancelAll), DECLARE_NAPI_FUNCTION("cancelGroup", CancelGroup), + DECLARE_NAPI_FUNCTION("cancelAsBundle", CancelAsBundle), DECLARE_NAPI_FUNCTION("addSlot", AddSlot), DECLARE_NAPI_FUNCTION("addSlots", AddSlots), DECLARE_NAPI_FUNCTION("setSlotByBundle", SetSlotByBundle), @@ -76,6 +78,9 @@ napi_value NotificationInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("enableDistributedSelf", EnableDistributedSelf), DECLARE_NAPI_FUNCTION("isDistributedEnableByBundle", IsDistributedEnableByBundle), DECLARE_NAPI_FUNCTION("getDeviceRemindType", GetDeviceRemindType), + DECLARE_NAPI_FUNCTION("show", ShowNotification), + DECLARE_NAPI_FUNCTION("enableNotificationSlot", EnableNotificationSlot), + DECLARE_NAPI_FUNCTION("isNotificationSlotEnabled", IsEnableNotificationSlot), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/interfaces/kits/napi/ans/src/publish.cpp b/interfaces/kits/napi/ans/src/publish.cpp index d099d521182fda0803d55364cf299806049307c1..05fefbeb58e53da6320670715b7f0aabc8218bb1 100644 --- a/interfaces/kits/napi/ans/src/publish.cpp +++ b/interfaces/kits/napi/ans/src/publish.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -15,9 +15,17 @@ #include "publish.h" +#include "want_agent_helper.h" + namespace OHOS { namespace NotificationNapi { -static const int32_t PUBLISH_NOTIFICATION_MAX = 3; +using namespace AbilityRuntime::WantAgent; + +namespace { +constexpr int8_t PUBLISH_NOTIFICATION_MAX = 3; +constexpr int8_t SHOW_NOTIFICATION_MAX = 1; +constexpr int8_t PUBLISH_AS_BUNDLE_MAX = 4; +} struct AsyncCallbackInfoPublish { napi_env env = nullptr; @@ -54,7 +62,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[PUBLISH_NOTIFICATION_MAX] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); if (argc < 1) { - ANS_LOGW("Wrong argument type. Function expected."); + ANS_LOGW("Wrong number of arguments."); return nullptr; } @@ -125,7 +133,7 @@ napi_value Publish(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("Publish napi_create_async_work start"); - AsyncCallbackInfoPublish *asynccallbackinfo = (AsyncCallbackInfoPublish *)data; + AsyncCallbackInfoPublish *asynccallbackinfo = static_cast(data); ANS_LOGI("Publish napi_create_async_work start notificationId = %{public}d, contentType = " "%{public}d", asynccallbackinfo->request.GetNotificationId(), @@ -136,20 +144,329 @@ napi_value Publish(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("Publish napi_create_async_work complete start"); - AsyncCallbackInfoPublish *asynccallbackinfo = (AsyncCallbackInfoPublish *)data; + AsyncCallbackInfoPublish *asynccallbackinfo = static_cast(data); + if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + ANS_LOGI("Publish napi_create_async_work complete end"); + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +bool CheckProperty(const napi_env &env, const napi_value &content, const std::string &property) +{ + ANS_LOGI("enter"); + + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, content, property.data(), &hasProperty)); + if (!hasProperty) { + ANS_LOGW("Property %{public}s expected.", property.c_str()); + } + return hasProperty; +} + +napi_value GetStringProperty( + const napi_env &env, const napi_value &content, const std::string &property, std::string &result) +{ + ANS_LOGI("enter"); + + if (!CheckProperty(env, content, property)) { + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + napi_value value = nullptr; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + napi_get_named_property(env, content, property.data(), &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + if (valuetype != napi_string) { + ANS_LOGW("Wrong argument type. String expected."); + return nullptr; + } + NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); + ANS_LOGI("normal::%{public}s = %{public}s", property.c_str(), str); + result = str; + return Common::NapiGetNull(env); +} + +napi_value GetObjectProperty( + const napi_env &env, const napi_value &content, const std::string &property, napi_value &result) +{ + ANS_LOGI("enter"); + + if (!CheckProperty(env, content, property)) { + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + napi_get_named_property(env, content, property.data(), &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + if (valuetype != napi_object) { + ANS_LOGW("Wrong argument type. Object expected."); + return nullptr; + } + return Common::NapiGetNull(env); +} + +napi_value ParseShowOptions(const napi_env &env, const napi_callback_info &info, ParametersInfoPublish ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = SHOW_NOTIFICATION_MAX; + napi_value argv[SHOW_NOTIFICATION_MAX] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + if (argc == 0) { + ANS_LOGW("Wrong number of arguments."); + return nullptr; + } + + // argv[0] : ShowNotificationOptions + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if (valuetype != napi_object) { + ANS_LOGW("Wrong argument type. Object expected."); + return nullptr; + } + + std::shared_ptr normalContent = std::make_shared(); + + // contentTitle + std::string contentTitle; + if (GetStringProperty(env, argv[PARAM0], "contentTitle", contentTitle) != nullptr) { + normalContent->SetTitle(contentTitle); + } + + // contentText + std::string contentText; + if (GetStringProperty(env, argv[PARAM0], "contentText", contentText) != nullptr) { + normalContent->SetText(contentText); + } + + std::shared_ptr content = std::make_shared(normalContent); + params.request.SetContent(content); + + // clickAction + napi_value clickAction = nullptr; + if (GetObjectProperty(env, argv[PARAM0], "clickAction", clickAction) != nullptr) { + ANS_LOGD("create wantagent"); + // bundleName & abilityName + std::shared_ptr want = std::make_shared(); + std::string bundleName; + std::string abilityName; + if (GetStringProperty(env, clickAction, "bundleName", bundleName) == nullptr) { + return nullptr; + } + if (GetStringProperty(env, clickAction, "abilityName", abilityName) == nullptr) { + return nullptr; + } + want->SetElementName(bundleName, abilityName); + // uri + std::string uri; + if (GetStringProperty(env, clickAction, "uri", uri) == nullptr) { + return nullptr; + } + want->SetUri(uri); + + std::vector> wants = {}; + std::vector wantAgentFlags = {}; + std::shared_ptr extraInfo = std::make_shared(); + wants.emplace_back(want); + WantAgentInfo wantAgentInfo(-1, WantAgentConstant::OperationType::START_ABILITY, wantAgentFlags, + wants, extraInfo); + std::shared_ptr context = AbilityRuntime::Context::GetApplicationContext(); + + std::shared_ptr wantAgent = + WantAgentHelper::GetWantAgent(context, wantAgentInfo); + params.request.SetWantAgent(wantAgent); + } + + ANS_LOGI("end"); + return Common::NapiGetNull(env); +} + +napi_value ShowNotification(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + ParametersInfoPublish params; + if (ParseShowOptions(env, info, params) == nullptr) { + ANS_LOGW("parse showOptions failed"); + return Common::NapiGetUndefined(env); + } - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + AsyncCallbackInfoPublish *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoPublish {.env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + ANS_LOGW("failed to create asynccallbackinfo"); + return Common::JSParaError(env, params.callback); + } + + asynccallbackinfo->request = params.request; - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "show", NAPI_AUTO_LENGTH, &resourceName); + + ANS_LOGI("before napi_create_async_work"); + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("Show napi_create_async_work start"); + AsyncCallbackInfoPublish *asynccallbackinfo = static_cast(data); + ANS_LOGI("Show napi_create_async_work start notificationId = %{public}d, contentType = " + "%{public}d", + asynccallbackinfo->request.GetNotificationId(), + asynccallbackinfo->request.GetContent()->GetContentType()); + + asynccallbackinfo->info.errorCode = + NotificationHelper::PublishNotification(asynccallbackinfo->request); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("Show napi_create_async_work complete start"); + AsyncCallbackInfoPublish *asynccallbackinfo = static_cast(data); + if (asynccallbackinfo) { + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } + ANS_LOGI("Show napi_create_async_work complete end"); + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + return nullptr; +} + +napi_value ParsePublishAsBundleParameters( + const napi_env &env, const napi_callback_info &info, ParametersInfoPublish ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = PUBLISH_AS_BUNDLE_MAX; + napi_value argv[PUBLISH_AS_BUNDLE_MAX] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + if (argc < 1) { + ANS_LOGW("Wrong number of arguments"); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if (valuetype != napi_object) { + ANS_LOGW("Wrong argument type. Object expected."); + return nullptr; + } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + // argv[0] : NotificationRequest + if (Common::GetNotificationRequest(env, argv[PARAM0], params.request) == nullptr) { + return nullptr; + } + + // argv[1] : bundleName + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if (valuetype != napi_string) { + ANS_LOGW("Wrong argument type. String expected."); + return nullptr; + } + + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + napi_get_value_string_utf8(env, argv[PARAM1], str, STR_MAX_SIZE - 1, &strLen); + params.request.SetOwnerBundleName(str); + + // argv[2] : userId + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); + if (valuetype != napi_number) { + ANS_LOGW("Wrong argument type. Number expected."); + return nullptr; + } + int32_t userId = 0; + napi_get_value_int32(env, argv[PARAM2], &userId); + params.request.SetOwnerUserId(userId); + params.request.SetIsAgentNotification(true); + + // argv[3] : callback + if (argc >= PUBLISH_AS_BUNDLE_MAX) { + if (GetCallback(env, argv[PARAM3], params) == nullptr) { + return nullptr; + } + } + + ANS_LOGI("end"); + return Common::NapiGetNull(env); +} + +napi_value PublishAsBundle(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + ParametersInfoPublish params; + if (ParsePublishAsBundleParameters(env, info, params) == nullptr) { + return Common::NapiGetUndefined(env); + } + + napi_value promise = nullptr; + AsyncCallbackInfoPublish *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoPublish {.env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + + asynccallbackinfo->request = params.request; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "publishasbundle", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("PublishAsBundle napi_create_async_work start"); + AsyncCallbackInfoPublish *asynccallbackinfo = static_cast(data); + ANS_LOGI("PublishAsBundle napi_create_async_work start notificationId = %{public}d, contentType = " + "%{public}d", + asynccallbackinfo->request.GetNotificationId(), + asynccallbackinfo->request.GetContent()->GetContentType()); + + asynccallbackinfo->info.errorCode = + NotificationHelper::PublishNotification(asynccallbackinfo->request); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("PublishAsBundle napi_create_async_work complete start"); + AsyncCallbackInfoPublish *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } - ANS_LOGI("Publish napi_create_async_work complete end"); + ANS_LOGI("PublishAsBundle napi_create_async_work complete end"); }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); diff --git a/interfaces/kits/napi/ans/src/reminder/BUILD.gn b/interfaces/kits/napi/ans/src/reminder/BUILD.gn index 0cabca8676568126fb3ed7463b7b8e2ba48e39e3..48106543389ea60f85058a7383aa88e0454f24e1 100644 --- a/interfaces/kits/napi/ans/src/reminder/BUILD.gn +++ b/interfaces/kits/napi/ans/src/reminder/BUILD.gn @@ -64,13 +64,14 @@ ohos_shared_library("reminderagent") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:abilitykit_native", "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", - "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", + "native_appdatamgr:native_rdb", ] relative_install_dir = "module" diff --git a/interfaces/kits/napi/ans/src/reminder/native_module.cpp b/interfaces/kits/napi/ans/src/reminder/native_module.cpp index f4fe3650ba080b8ce115245cd6fed1f18e68a762..613202a83059f0f84c5f040296d759516d5ae8ec 100644 --- a/interfaces/kits/napi/ans/src/reminder/native_module.cpp +++ b/interfaces/kits/napi/ans/src/reminder/native_module.cpp @@ -13,13 +13,13 @@ * limitations under the License. */ +#include "reminder/native_module.h" + #include "napi/native_api.h" #include "napi/native_node_api.h" #include "reminder/publish.h" #include "slot.h" -#include "reminder/native_module.h" - namespace OHOS { namespace ReminderAgentNapi { EXTERN_C_START @@ -31,7 +31,7 @@ napi_value ReminderAgentInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("cancelAllReminders", CancelAllReminders), DECLARE_NAPI_FUNCTION("getValidReminders", GetValidReminders), DECLARE_NAPI_FUNCTION("publishReminder", PublishReminder), - DECLARE_NAPI_FUNCTION("addNotificationSlot", NotificationNapi::AddSlot), + DECLARE_NAPI_FUNCTION("addNotificationSlot", AddSlot), DECLARE_NAPI_FUNCTION("removeNotificationSlot", NotificationNapi::RemoveSlot), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/interfaces/kits/napi/ans/src/reminder/publish.cpp b/interfaces/kits/napi/ans/src/reminder/publish.cpp index d0033726d9be2716863a4a3b6c001397d170ca1a..c0035876d4fed4b8094a6d4753c234bbf32d176e 100644 --- a/interfaces/kits/napi/ans/src/reminder/publish.cpp +++ b/interfaces/kits/napi/ans/src/reminder/publish.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -13,38 +13,57 @@ * limitations under the License. */ +#include "reminder/publish.h" + #include "ans_log_wrapper.h" #include "common.h" #include "reminder_request_alarm.h" #include "reminder_request_calendar.h" #include "reminder_request_timer.h" -#include "reminder/publish.h" - namespace OHOS { namespace ReminderAgentNapi { static const int32_t PUBLISH_PARAM_LEN = 2; static const int32_t CANCEL_PARAM_LEN = 2; static const int32_t CANCEL_ALL_PARAM_LEN = 1; static const int32_t GET_VALID_PARAM_LEN = 1; +static const int32_t ADD_SLOT_PARAM_LEN = 2; struct AsyncCallbackInfo { + explicit AsyncCallbackInfo(napi_env napiEnv) : env(napiEnv) {} + ~AsyncCallbackInfo() + { + if (asyncWork) { + napi_delete_async_work(env, asyncWork); + asyncWork = nullptr; + } + if (callback) { + napi_delete_reference(env, callback); + callback = nullptr; + } + } + napi_env env = nullptr; napi_async_work asyncWork = nullptr; + napi_ref callback = nullptr; + napi_value result = nullptr; int32_t reminderId = -1; + NotificationNapi::NotificationConstant::SlotType inType + = NotificationNapi::NotificationConstant::SlotType::CONTENT_INFORMATION; std::shared_ptr reminder = nullptr; std::vector> validReminders; NotificationNapi::CallbackPromiseInfo info; - napi_value result = nullptr; }; struct Parameters { int32_t reminderId = -1; + int32_t errCode = ERR_OK; + NotificationNapi::NotificationConstant::SlotType inType + = NotificationNapi::NotificationConstant::SlotType::CONTENT_INFORMATION; std::shared_ptr reminder = nullptr; - napi_ref callback = nullptr; }; -napi_value GetCallback(const napi_env &env, const napi_value &value, Parameters ¶ms) +napi_value GetCallback(const napi_env &env, const napi_value &value, AsyncCallbackInfo &asyncCallbackInfo) { napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, value, &valuetype)); @@ -52,28 +71,23 @@ napi_value GetCallback(const napi_env &env, const napi_value &value, Parameters ANSR_LOGW("Wrong argument type. Function expected."); return nullptr; } - napi_create_reference(env, value, 1, ¶ms.callback); + napi_create_reference(env, value, 1, &asyncCallbackInfo.callback); return NotificationNapi::Common::NapiGetNull(env); } -AsyncCallbackInfo* SetAsynccallbackinfo(const napi_env &env, Parameters& params, napi_value& promise) +void SetAsynccallbackinfo(const napi_env &env, AsyncCallbackInfo& asynccallbackinfo, napi_value& promise) { - AsyncCallbackInfo *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfo { - .env = env, .asyncWork = nullptr}; - if (!asynccallbackinfo) { - NotificationNapi::Common::JSParaError(env, params.callback); - return nullptr; - } - NotificationNapi::Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); - return asynccallbackinfo; + NotificationNapi::Common::PaddingCallbackPromiseInfo( + env, asynccallbackinfo.callback, asynccallbackinfo.info, promise); } -napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) +napi_value ParseParameters( + const napi_env &env, const napi_callback_info &info, Parameters ¶ms, AsyncCallbackInfo &asyncCallbackInfo) { size_t argc = PUBLISH_PARAM_LEN; napi_value argv[PUBLISH_PARAM_LEN] = {nullptr}; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - if (argc < 1 || argc > PUBLISH_PARAM_LEN) { + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if ((argc < 1) || (argc > PUBLISH_PARAM_LEN)) { ANSR_LOGW("Wrong number of arguments"); return nullptr; } @@ -86,7 +100,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[1]: callback if (argc == PUBLISH_PARAM_LEN) { - if (GetCallback(env, argv[1], params) == nullptr) { + if (GetCallback(env, argv[1], asyncCallbackInfo) == nullptr) { ANSR_LOGW("[reminderAgent]GetCallbak returns nullptr"); return nullptr; } @@ -94,13 +108,50 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, return NotificationNapi::Common::NapiGetNull(env); } -napi_value ParseCanCelParameter(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) +napi_value ParseSlotParameters( + const napi_env &env, const napi_callback_info &info, Parameters ¶ms, AsyncCallbackInfo &asyncCallbackInfo) +{ + size_t argc = ADD_SLOT_PARAM_LEN; + napi_value argv[ADD_SLOT_PARAM_LEN] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if ((argc < 1) || (argc > ADD_SLOT_PARAM_LEN)) { + ANSR_LOGW("Wrong number of arguments"); + return nullptr; + } + + // argv[1]: callback + if (argc == ADD_SLOT_PARAM_LEN) { + if (GetCallback(env, argv[1], asyncCallbackInfo) == nullptr) { + ANSR_LOGW("GetCallbak returns nullptr"); + return nullptr; + } + } + + // argv[0] : notificationSlot + // slotType + const char* propertyKey = "type"; + int32_t propertyVal = 0; + if (!ReminderCommon::GetInt32(env, argv[0], propertyKey, propertyVal, false)) { + ANSR_LOGW("Failed to get valid slot type."); + params.errCode = ERR_INVALID_VALUE; + return NotificationNapi::Common::NapiGetNull(env); + } + + if (!NotificationNapi::Common::SlotTypeJSToC(NotificationNapi::SlotType(propertyVal), params.inType)) { + ANSR_LOGW("Failed to get valid slot type"); + return nullptr; + } + return NotificationNapi::Common::NapiGetNull(env); +} + +napi_value ParseCanCelParameter( + const napi_env &env, const napi_callback_info &info, Parameters ¶ms, AsyncCallbackInfo &asyncCallbackInfo) { ANSR_LOGI("ParseCanCelParameter"); size_t argc = CANCEL_PARAM_LEN; napi_value argv[CANCEL_PARAM_LEN] = {nullptr}; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - if (argc < 1 || argc > CANCEL_PARAM_LEN) { + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if ((argc < 1) || (argc > CANCEL_PARAM_LEN)) { ANSR_LOGW("Wrong number of arguments"); return nullptr; } @@ -118,7 +169,7 @@ napi_value ParseCanCelParameter(const napi_env &env, const napi_callback_info &i // argv[1]: callback if (argc >= CANCEL_PARAM_LEN) { - if (GetCallback(env, argv[1], params) == nullptr) { + if (GetCallback(env, argv[1], asyncCallbackInfo) == nullptr) { ANSR_LOGW("GetCallbak is nullptr"); return nullptr; } @@ -126,12 +177,13 @@ napi_value ParseCanCelParameter(const napi_env &env, const napi_callback_info &i return NotificationNapi::Common::NapiGetNull(env); } -napi_value ParseCanCelAllParameter(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) +napi_value ParseCanCelAllParameter( + const napi_env &env, const napi_callback_info &info, Parameters ¶ms, AsyncCallbackInfo &asyncCallbackInfo) { ANSR_LOGI("ParseCanCelAllParameter"); size_t argc = CANCEL_ALL_PARAM_LEN; napi_value argv[CANCEL_ALL_PARAM_LEN] = {nullptr}; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); if (argc > CANCEL_ALL_PARAM_LEN) { ANSR_LOGW("Wrong number of arguments"); return nullptr; @@ -139,7 +191,7 @@ napi_value ParseCanCelAllParameter(const napi_env &env, const napi_callback_info // argv[0]: callback if (argc == CANCEL_ALL_PARAM_LEN) { - if (GetCallback(env, argv[0], params) == nullptr) { + if (GetCallback(env, argv[0], asyncCallbackInfo) == nullptr) { ANSR_LOGW("getCallbak is nullptr"); return nullptr; } @@ -147,19 +199,20 @@ napi_value ParseCanCelAllParameter(const napi_env &env, const napi_callback_info return NotificationNapi::Common::NapiGetNull(env); } -napi_value ParseGetValidParameter(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) +napi_value ParseGetValidParameter( + const napi_env &env, const napi_callback_info &info, Parameters ¶ms, AsyncCallbackInfo &asyncCallbackInfo) { size_t argc = GET_VALID_PARAM_LEN; napi_value argv[GET_VALID_PARAM_LEN] = {nullptr}; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - if (argc < 0 || argc > GET_VALID_PARAM_LEN) { + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > GET_VALID_PARAM_LEN) { ANSR_LOGW("Wrong number of arguments"); return nullptr; } // argv[0]: callback if (argc == GET_VALID_PARAM_LEN) { - if (GetCallback(env, argv[0], params) == nullptr) { + if (GetCallback(env, argv[0], asyncCallbackInfo) == nullptr) { ANSR_LOGW("getCallbak is nullptr"); return nullptr; } @@ -171,18 +224,22 @@ napi_value CancelReminder(napi_env env, napi_callback_info info) { ANSR_LOGI("Cancel reminder"); + AsyncCallbackInfo *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfo(env); + if (!asynccallbackinfo) { + ANSR_LOGE("Low memory."); + return NotificationNapi::Common::NapiGetNull(env); + } + std::unique_ptr callbackPtr { asynccallbackinfo }; + // param Parameters params; - if (ParseCanCelParameter(env, info, params) == nullptr) { - return NotificationNapi::Common::JSParaError(env, params.callback); + if (ParseCanCelParameter(env, info, params, *asynccallbackinfo) == nullptr) { + return NotificationNapi::Common::JSParaError(env, asynccallbackinfo->callback); } // promise napi_value promise = nullptr; - AsyncCallbackInfo *asynccallbackinfo = SetAsynccallbackinfo(env, params, promise); - if (!asynccallbackinfo) { - return NotificationNapi::Common::JSParaError(env, params.callback); - } + SetAsynccallbackinfo(env, *asynccallbackinfo, promise); asynccallbackinfo->reminderId = params.reminderId; // resource name @@ -201,19 +258,16 @@ napi_value CancelReminder(napi_env env, napi_callback_info info) [](napi_env env, napi_status status, void *data) { ANSR_LOGI("Cancel napi_create_async_work complete start"); AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + std::unique_ptr callbackPtr { asynccallbackinfo }; + NotificationNapi::Common::ReturnCallbackPromise( env, asynccallbackinfo->info, NotificationNapi::Common::NapiGetNull(env)); - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - delete asynccallbackinfo; - asynccallbackinfo = nullptr; ANSR_LOGI("Cancel napi_create_async_work complete end"); }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + callbackPtr.release(); if (asynccallbackinfo->info.isCallback) { return NotificationNapi::Common::NapiGetNull(env); @@ -226,18 +280,22 @@ napi_value CancelAllReminders(napi_env env, napi_callback_info info) { ANSR_LOGI("Cancel all reminder"); + AsyncCallbackInfo *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfo(env); + if (!asynccallbackinfo) { + ANSR_LOGE("Low memory."); + return NotificationNapi::Common::NapiGetNull(env); + } + std::unique_ptr callbackPtr { asynccallbackinfo }; + // param Parameters params; - if (ParseCanCelAllParameter(env, info, params) == nullptr) { - return NotificationNapi::Common::JSParaError(env, params.callback); + if (ParseCanCelAllParameter(env, info, params, *asynccallbackinfo) == nullptr) { + return NotificationNapi::Common::JSParaError(env, asynccallbackinfo->callback); } // promise napi_value promise = nullptr; - AsyncCallbackInfo *asynccallbackinfo = SetAsynccallbackinfo(env, params, promise); - if (!asynccallbackinfo) { - return NotificationNapi::Common::JSParaError(env, params.callback); - } + SetAsynccallbackinfo(env, *asynccallbackinfo, promise); // resource name napi_value resourceName = nullptr; @@ -255,19 +313,16 @@ napi_value CancelAllReminders(napi_env env, napi_callback_info info) [](napi_env env, napi_status status, void *data) { ANSR_LOGD("CancelAll napi_create_async_work complete start"); AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + std::unique_ptr callbackPtr { asynccallbackinfo }; + NotificationNapi::Common::ReturnCallbackPromise( env, asynccallbackinfo->info, NotificationNapi::Common::NapiGetNull(env)); - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - delete asynccallbackinfo; - asynccallbackinfo = nullptr; ANSR_LOGD("CancelAll napi_create_async_work complete end"); }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + callbackPtr.release(); if (asynccallbackinfo->info.isCallback) { return NotificationNapi::Common::NapiGetNull(env); @@ -299,7 +354,7 @@ void ParseReminderAlarm(const napi_env &env, ReminderRequest &reminder, napi_val // daysOfWeek napi_create_array(env, &value); napi_set_named_property(env, result, ALARM_DAYS_OF_WEEK, value); - int count = 0; + int32_t count = 0; for (auto day : alarm.GetDaysOfWeek()) { if (day) { napi_value napiDay = nullptr; @@ -314,29 +369,29 @@ void ParseReminderCalendar(const napi_env &env, ReminderRequest &reminder, napi_ { // dateTime napi_value value = nullptr; - ReminderRequestCalendar& calender = (ReminderRequestCalendar&)reminder; + ReminderRequestCalendar& calendar = (ReminderRequestCalendar&)reminder; napi_value dateTime = nullptr; napi_create_object(env, &dateTime); napi_set_named_property(env, result, CALENDAR_DATE_TIME, dateTime); - napi_create_uint32(env, static_cast(calender.GetYear()), &value); + napi_create_uint32(env, static_cast(calendar.GetYear()), &value); napi_set_named_property(env, dateTime, CALENDAR_YEAR, value); - napi_create_uint32(env, static_cast(calender.GetMonth()), &value); + napi_create_uint32(env, static_cast(calendar.GetMonth()), &value); napi_set_named_property(env, dateTime, CALENDAR_MONTH, value); - napi_create_uint32(env, static_cast(calender.GetDay()), &value); + napi_create_uint32(env, static_cast(calendar.GetDay()), &value); napi_set_named_property(env, dateTime, CALENDAR_DAY, value); - napi_create_uint32(env, static_cast(calender.GetHour()), &value); + napi_create_uint32(env, static_cast(calendar.GetHour()), &value); napi_set_named_property(env, dateTime, CALENDAR_HOUR, value); - napi_create_uint32(env, static_cast(calender.GetMinute()), &value); + napi_create_uint32(env, static_cast(calendar.GetMinute()), &value); napi_set_named_property(env, dateTime, CALENDAR_MINUTE, value); - napi_create_uint32(env, static_cast(calender.GetSecond()), &value); + napi_create_uint32(env, static_cast(calendar.GetSecond()), &value); napi_set_named_property(env, dateTime, CALENDAR_SECOND, value); // repeatMonths napi_create_array(env, &value); napi_set_named_property(env, result, CALENDAR_REPEAT_MONTHS, value); - int count = 0; - for (auto month : calender.GetRepeatMonths()) { + int32_t count = 0; + for (auto month : calendar.GetRepeatMonths()) { napi_value napiDay = nullptr; napi_create_int32(env, month, &napiDay); napi_set_element(env, value, count, napiDay); @@ -347,7 +402,7 @@ void ParseReminderCalendar(const napi_env &env, ReminderRequest &reminder, napi_ napi_create_array(env, &value); napi_set_named_property(env, result, CALENDAR_REPEAT_DAYS, value); count = 0; - for (auto day : calender.GetRepeatDays()) { + for (auto day : calendar.GetRepeatDays()) { napi_value napiDay = nullptr; napi_create_int32(env, day, &napiDay); napi_set_element(env, value, count, napiDay); @@ -385,7 +440,7 @@ void ParseActionButtons(const napi_env &env, ReminderRequest &reminder, napi_val napi_value array = nullptr; napi_create_array(env, &array); napi_set_named_property(env, result, ACTION_BUTTON, array); - int index = 0; + int32_t index = 0; for (std::map::iterator it = actionButtonsMap.begin(); it != actionButtonsMap.end(); ++it) { // create obj @@ -499,7 +554,7 @@ napi_value SetValidReminder(const napi_env &env, ReminderRequest &reminder, napi void GetValidRemindersInner(napi_env env, std::vector>& validReminders, napi_value& arr) { - int count = 0; + int32_t count = 0; napi_create_array(env, &arr); for (auto reminder : validReminders) { if (reminder == nullptr) { @@ -522,18 +577,22 @@ napi_value GetValidReminders(napi_env env, napi_callback_info info) { ANSR_LOGI("Get valid reminders"); + AsyncCallbackInfo *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfo(env); + if (!asynccallbackinfo) { + ANSR_LOGE("Low memory."); + return NotificationNapi::Common::NapiGetNull(env); + } + std::unique_ptr callbackPtr { asynccallbackinfo }; + // param Parameters params; - if (ParseGetValidParameter(env, info, params) == nullptr) { - return NotificationNapi::Common::JSParaError(env, params.callback); + if (ParseGetValidParameter(env, info, params, *asynccallbackinfo) == nullptr) { + return NotificationNapi::Common::JSParaError(env, asynccallbackinfo->callback); } // promise napi_value promise = nullptr; - AsyncCallbackInfo *asynccallbackinfo = SetAsynccallbackinfo(env, params, promise); - if (!asynccallbackinfo) { - return NotificationNapi::Common::JSParaError(env, params.callback); - } + SetAsynccallbackinfo(env, *asynccallbackinfo, promise); // resource name napi_value resourceName = nullptr; @@ -545,30 +604,31 @@ napi_value GetValidReminders(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANSR_LOGI("GetValid reminders napi_create_async_work start"); - AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; - asynccallbackinfo->info.errorCode = ReminderHelper::GetValidReminders(asynccallbackinfo->validReminders); + AsyncCallbackInfo *asynccallbackinfo = static_cast(data); + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = ReminderHelper::GetValidReminders( + asynccallbackinfo->validReminders); + } }, [](napi_env env, napi_status status, void *data) { - AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; - - if (asynccallbackinfo->info.errorCode != ERR_OK) { - asynccallbackinfo->result = NotificationNapi::Common::NapiGetNull(env); - } else { - GetValidRemindersInner(env, asynccallbackinfo->validReminders, asynccallbackinfo->result); + AsyncCallbackInfo *asynccallbackinfo = static_cast(data); + std::unique_ptr callbackPtr { asynccallbackinfo }; + + if (asynccallbackinfo) { + if (asynccallbackinfo->info.errorCode != ERR_OK) { + asynccallbackinfo->result = NotificationNapi::Common::NapiGetNull(env); + } else { + GetValidRemindersInner(env, asynccallbackinfo->validReminders, asynccallbackinfo->result); + } + + NotificationNapi::Common::ReturnCallbackPromise( + env, asynccallbackinfo->info, asynccallbackinfo->result); } - - NotificationNapi::Common::ReturnCallbackPromise( - env, asynccallbackinfo->info, asynccallbackinfo->result); - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - delete asynccallbackinfo; - asynccallbackinfo = nullptr; }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + callbackPtr.release(); if (asynccallbackinfo->info.isCallback) { return NotificationNapi::Common::NapiGetNull(env); @@ -581,19 +641,23 @@ napi_value PublishReminder(napi_env env, napi_callback_info info) { ANSR_LOGI("PublishReminder"); + AsyncCallbackInfo *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfo(env); + if (!asynccallbackinfo) { + ANSR_LOGE("Low memory."); + return NotificationNapi::Common::NapiGetNull(env); + } + std::unique_ptr callbackPtr { asynccallbackinfo }; + // param Parameters params; - if (ParseParameters(env, info, params) == nullptr) { + if (ParseParameters(env, info, params, *asynccallbackinfo) == nullptr) { ANSR_LOGW("Parse params error"); - return NotificationNapi::Common::JSParaError(env, params.callback); + return NotificationNapi::Common::JSParaError(env, asynccallbackinfo->callback); } // promise napi_value promise = nullptr; - AsyncCallbackInfo *asynccallbackinfo = SetAsynccallbackinfo(env, params, promise); - if (!asynccallbackinfo) { - return NotificationNapi::Common::JSParaError(env, params.callback); - } + SetAsynccallbackinfo(env, *asynccallbackinfo, promise); asynccallbackinfo->reminder = params.reminder; // resource name @@ -606,34 +670,95 @@ napi_value PublishReminder(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANSR_LOGI("Publish napi_create_async_work start"); - AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; - asynccallbackinfo->info.errorCode = ReminderHelper::PublishReminder(*(asynccallbackinfo->reminder)); - ANSR_LOGD("Return reminderId=%{public}d", asynccallbackinfo->reminder->GetReminderId()); + AsyncCallbackInfo *asynccallbackinfo = static_cast(data); + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = ReminderHelper::PublishReminder(*(asynccallbackinfo->reminder)); + ANSR_LOGD("Return reminderId=%{public}d", asynccallbackinfo->reminder->GetReminderId()); + } }, [](napi_env env, napi_status status, void *data) { ANSR_LOGI("Publish napi_create_async_work complete start"); - AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + AsyncCallbackInfo *asynccallbackinfo = static_cast(data); + std::unique_ptr callbackPtr { asynccallbackinfo }; // reminderId - if (asynccallbackinfo->info.errorCode == ERR_OK) { - napi_create_int32(env, asynccallbackinfo->reminder->GetReminderId(), &(asynccallbackinfo->result)); - } else { - napi_create_int32(env, -1, &(asynccallbackinfo->result)); + if (asynccallbackinfo) { + if (asynccallbackinfo->info.errorCode == ERR_OK) { + napi_create_int32(env, asynccallbackinfo->reminder->GetReminderId(), &(asynccallbackinfo->result)); + } else { + napi_create_int32(env, -1, &(asynccallbackinfo->result)); + } + + NotificationNapi::Common::ReturnCallbackPromise( + env, asynccallbackinfo->info, asynccallbackinfo->result); + ANSR_LOGI("Publish napi_create_async_work complete end"); } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); - NotificationNapi::Common::ReturnCallbackPromise( - env, asynccallbackinfo->info, asynccallbackinfo->result); - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + callbackPtr.release(); + + if (asynccallbackinfo->info.isCallback) { + return NotificationNapi::Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value AddSlot(napi_env env, napi_callback_info info) +{ + ANSR_LOGI("AddSlot"); + + AsyncCallbackInfo *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfo(env); + if (!asynccallbackinfo) { + ANSR_LOGE("Low memory."); + return NotificationNapi::Common::NapiGetNull(env); + } + std::unique_ptr callbackPtr { asynccallbackinfo }; + + // param + Parameters params; + if (ParseSlotParameters(env, info, params, *asynccallbackinfo) == nullptr) { + ANSR_LOGW("Parse params error"); + return NotificationNapi::Common::JSParaError(env, asynccallbackinfo->callback); + } + + // promise + napi_value promise = nullptr; + SetAsynccallbackinfo(env, *asynccallbackinfo, promise); + asynccallbackinfo->inType = params.inType; + asynccallbackinfo->info.errorCode = params.errCode; + + // resource name + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "AddSlot", NAPI_AUTO_LENGTH, &resourceName); + + // create and start async work + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANSR_LOGI("AddSlot napi_create_async_work start"); + AsyncCallbackInfo *asynccallbackinfo = static_cast(data); + if (asynccallbackinfo && (asynccallbackinfo->info.errorCode == ERR_OK)) { + asynccallbackinfo->info.errorCode = NotificationHelper::AddSlotByType(asynccallbackinfo->inType); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - ANSR_LOGI("Publish napi_create_async_work complete end"); + }, + [](napi_env env, napi_status status, void *data) { + AsyncCallbackInfo *asynccallbackinfo = static_cast(data); + std::unique_ptr callbackPtr { asynccallbackinfo }; + + NotificationNapi::Common::ReturnCallbackPromise( + env, asynccallbackinfo->info, NotificationNapi::Common::NapiGetNull(env)); + ANSR_LOGD("AddSlot napi_create_async_work complete end."); }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + callbackPtr.release(); if (asynccallbackinfo->info.isCallback) { return NotificationNapi::Common::NapiGetNull(env); diff --git a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp index 0d53108ad92bc9f1a5768ac341eeac1a354a128a..47ff49f06de78d1829dc5430341be874a1d6378f 100644 --- a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp +++ b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -13,14 +13,14 @@ * limitations under the License. */ +#include "reminder/reminder_common.h" + #include "ans_log_wrapper.h" #include "common.h" #include "reminder_request_alarm.h" #include "reminder_request_calendar.h" #include "reminder_request_timer.h" -#include "reminder/reminder_common.h" - namespace OHOS { namespace ReminderAgentNapi { using namespace OHOS::Notification; @@ -222,7 +222,7 @@ napi_value ReminderCommon::GenReminder( if (propertyVal < 0) { reminder->SetSnoozeTimes(0); } else { - uint8_t snoozeTimes = propertyVal > UINT8_MAX ? UINT8_MAX : propertyVal; + uint8_t snoozeTimes = propertyVal > UINT8_MAX ? UINT8_MAX : static_cast(propertyVal); reminder->SetSnoozeTimes(static_cast(snoozeTimes)); } } @@ -366,21 +366,24 @@ napi_value ReminderCommon::CreateReminderAlarm( { // hour int32_t propertyHourVal = 0; + const int32_t maxHour = 23; if (!GetInt32(env, value, ReminderAgentNapi::ALARM_HOUR, propertyHourVal, true)) { return nullptr; } // minute int32_t propertyMinuteVal = 0; + const int32_t maxMinute = 59; if (!GetInt32(env, value, ReminderAgentNapi::ALARM_MINUTE, propertyMinuteVal, true)) { return nullptr; } - if (propertyHourVal < 0 || propertyHourVal > 23) { + + if ((propertyHourVal < 0) || (propertyHourVal > maxHour)) { ANSR_LOGW("Create alarm reminder fail: designated %{public}s must between [0, 23].", ReminderAgentNapi::ALARM_HOUR); return nullptr; } - if (propertyMinuteVal < 0 || propertyMinuteVal > 59) { + if ((propertyMinuteVal < 0) || (propertyMinuteVal > maxMinute)) { ANSR_LOGW("Create alarm reminder fail: designated %{public}s must between [0, 59].", ReminderAgentNapi::ALARM_MINUTE); return nullptr; @@ -402,7 +405,7 @@ napi_value ReminderCommon::CreateReminderCalendar( { napi_value dateTimeObj = nullptr; if (!GetObject(env, value, ReminderAgentNapi::CALENDAR_DATE_TIME, dateTimeObj)) { - ANSR_LOGW("Create calender reminder fail: dateTime must be setted."); + ANSR_LOGW("Create calendar reminder fail: dateTime must be setted."); return nullptr; } @@ -412,11 +415,11 @@ napi_value ReminderCommon::CreateReminderCalendar( int32_t propertyDayVal = 0; int32_t propertyHourVal = 0; int32_t propertyMinteVal = 0; - if (!GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_YEAR, propertyYearVal, true) - || !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_MONTH, propertyMonthVal, true) - || !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_DAY, propertyDayVal, true) - || !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_HOUR, propertyHourVal, true) - || !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_MINUTE, propertyMinteVal, true)) { + if (!GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_YEAR, propertyYearVal, true) || + !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_MONTH, propertyMonthVal, true) || + !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_DAY, propertyDayVal, true) || + !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_HOUR, propertyHourVal, true) || + !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_MINUTE, propertyMinteVal, true)) { return nullptr; } if (!CheckCalendarParams(propertyYearVal, propertyMonthVal, propertyDayVal, @@ -453,31 +456,31 @@ napi_value ReminderCommon::CreateReminderCalendar( bool ReminderCommon::CheckCalendarParams(const int32_t &year, const int32_t &month, const int32_t &day, const int32_t &hour, const int32_t &min) { - if (year < 0 || year > UINT16_MAX) { - ANSR_LOGW("Create calender reminder fail: designated %{public}s must between [0, %{public}u]", + if ((year < 0) || (year > UINT16_MAX)) { + ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [0, %{public}d]", ReminderAgentNapi::CALENDAR_YEAR, UINT16_MAX); return false; } - if (month < 1 || month > ReminderRequestCalendar::MAX_MONTHS_OF_YEAR) { - ANSR_LOGW("Create calender reminder fail: designated %{public}s must between [1, %{public}u]", + if ((month < 1) || (month > ReminderRequestCalendar::MAX_MONTHS_OF_YEAR)) { + ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [1, %{public}hhu]", ReminderAgentNapi::CALENDAR_MONTH, ReminderRequestCalendar::MAX_MONTHS_OF_YEAR); return false; } uint8_t maxDaysOfMonth = ReminderRequestCalendar::GetDaysOfMonth(static_cast(year), month); - if (day < 1 || day > maxDaysOfMonth) { - ANSR_LOGW("Create calender reminder fail: designated %{public}s must between [1, %{public}u]", + if ((day < 1) || (day > maxDaysOfMonth)) { + ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [1, %{public}hhu]", ReminderAgentNapi::CALENDAR_DAY, maxDaysOfMonth); return false; } uint8_t maxHour = 23; if (hour < 0 || hour > maxHour) { - ANSR_LOGW("Create calender reminder fail: designated %{public}s must between [0, %{public}u]", + ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [0, %{public}hhu]", ReminderAgentNapi::CALENDAR_HOUR, maxHour); return false; } uint8_t maxMinute = 59; if (min < 0 || min > maxMinute) { - ANSR_LOGW("Create calender reminder fail: designated %{public}s must between [0, %{public}u]", + ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [0, %{public}hhu]", ReminderAgentNapi::CALENDAR_MINUTE, maxMinute); return false; } @@ -501,7 +504,7 @@ napi_value ReminderCommon::ParseInt32Array(const napi_env &env, const napi_value uint32_t length = 0; napi_get_array_length(env, result, &length); if (length > maxLen) { - ANSR_LOGW("The max length of array of %{public}s is %{public}d.", propertyName, maxLen); + ANSR_LOGW("The max length of array of %{public}s is %{public}hhu.", propertyName, maxLen); return nullptr; } napi_valuetype valuetype = napi_undefined; @@ -515,7 +518,7 @@ napi_value ReminderCommon::ParseInt32Array(const napi_env &env, const napi_value return nullptr; } napi_get_value_int32(env, repeatDayVal, &propertyDayVal); - if (propertyDayVal < 1 || propertyDayVal > maxLen) { + if (propertyDayVal < 1 || propertyDayVal > static_cast(maxLen)) { ANSR_LOGW("%{public}s's element must between [1, %{public}d].", propertyName, maxLen); return nullptr; } @@ -525,4 +528,4 @@ napi_value ReminderCommon::ParseInt32Array(const napi_env &env, const napi_value return NotificationNapi::Common::NapiGetNull(env); } } -} +} \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/remove.cpp b/interfaces/kits/napi/ans/src/remove.cpp index 8d44d3219ce8d30c9f4e6eb07579c6ebfc570fbf..e59a699a608a9e45fc300c1f9be48942bef88315 100644 --- a/interfaces/kits/napi/ans/src/remove.cpp +++ b/interfaces/kits/napi/ans/src/remove.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -259,7 +259,7 @@ napi_value Remove(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("Remove napi_create_async_work start"); - AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; + AsyncCallbackInfoRemove *asynccallbackinfo = static_cast(data); if (asynccallbackinfo->params.hashcode.has_value()) { asynccallbackinfo->info.errorCode = @@ -273,16 +273,13 @@ napi_value Remove(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("Remove napi_create_async_work end"); - AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + AsyncCallbackInfoRemove *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -324,7 +321,7 @@ napi_value RemoveAll(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("RemoveAll napi_create_async_work start"); - AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; + AsyncCallbackInfoRemove *asynccallbackinfo = static_cast(data); if (asynccallbackinfo->params.bundleAndKeyInfo.has_value()) { auto &infos = asynccallbackinfo->params.bundleAndKeyInfo.value(); @@ -339,16 +336,13 @@ napi_value RemoveAll(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("RemoveAll napi_create_async_work end"); - AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + AsyncCallbackInfoRemove *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -372,19 +366,14 @@ void AsyncCompleteCallbackRemoveGroupByBundle(napi_env env, napi_status status, ANS_LOGE("Invalid async callback data"); return; } - AsyncCallbackInfoRemoveGroupByBundle *asynccallbackinfo = (AsyncCallbackInfoRemoveGroupByBundle *)data; - + AsyncCallbackInfoRemoveGroupByBundle *asynccallbackinfo = static_cast(data); Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value RemoveGroupByBundle(napi_env env, napi_callback_info info) @@ -412,7 +401,8 @@ napi_value RemoveGroupByBundle(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("RemoveGroupByBundle napi_create_async_work start"); - AsyncCallbackInfoRemoveGroupByBundle *asynccallbackinfo = (AsyncCallbackInfoRemoveGroupByBundle *)data; + AsyncCallbackInfoRemoveGroupByBundle *asynccallbackinfo = + static_cast(data); ANS_LOGI("option.bundle = %{public}s, option.uid = %{public}d, groupName = %{public}s", asynccallbackinfo->params.option.GetBundleName().c_str(), asynccallbackinfo->params.option.GetUid(), diff --git a/interfaces/kits/napi/ans/src/slot.cpp b/interfaces/kits/napi/ans/src/slot.cpp index 7eab91e8540828f2a756fe541d4eb343460ee813..71d452ef5a1b7d42b893e6d047cd842163ac4e01 100644 --- a/interfaces/kits/napi/ans/src/slot.cpp +++ b/interfaces/kits/napi/ans/src/slot.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -17,13 +17,15 @@ namespace OHOS { namespace NotificationNapi { -const int ADD_SLOT_MAX_PARA = 2; -const int ADD_SLOTS_MAX_PARA = 2; -const int SET_SLOT_AS_BUNDLE_MAX_PARA = 3; -const int GET_SLOT_MAX_PARA = 2; -const int GET_SLOT_NUM_AS_BUNDLE_MAX_PARA = 2; -const int GET_SLOTS_AS_BUNDLE_MAX_PARA = 2; -const int REMOVE_SLOT_MAX_PARA = 2; +const int32_t ADD_SLOT_MAX_PARA = 2; +const int32_t ADD_SLOTS_MAX_PARA = 2; +const int32_t SET_SLOT_AS_BUNDLE_MAX_PARA = 3; +const int32_t GET_SLOT_MAX_PARA = 2; +const int32_t GET_SLOT_NUM_AS_BUNDLE_MAX_PARA = 2; +const int32_t GET_SLOTS_AS_BUNDLE_MAX_PARA = 2; +const int32_t REMOVE_SLOT_MAX_PARA = 2; +const int32_t GET_ENABLE_SLOT_MAX_PARA = 3; +const int32_t SET_ENABLE_SLOT_MAX_PARA = 4; struct ParametersInfoAddSlot { NotificationSlot slot; @@ -89,7 +91,7 @@ struct AsyncCallbackInfoGetSlotNumByBundle { napi_async_work asyncWork = nullptr; ParametersInfoGetSlotNumByBundle params; CallbackPromiseInfo info; - int num = 0; + uint64_t num = 0; }; struct AsyncCallbackInfoGetSlots { @@ -130,6 +132,34 @@ struct AsyncCallbackInfoRemoveAllSlots { CallbackPromiseInfo info; }; +struct ParametersInfoEnableSlot { + NotificationBundleOption option; + enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; + bool enable = false; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoInfoEnableSlot { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + ParametersInfoEnableSlot params; + CallbackPromiseInfo info; +}; + +struct ParametersInfoIsEnableSlot { + NotificationBundleOption option; + enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoInfoIsEnableSlot { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + ParametersInfoIsEnableSlot params; + bool isEnable = false; + CallbackPromiseInfo info; +}; + napi_value ParseParametersByAddSlot(const napi_env &env, const napi_callback_info &info, ParametersInfoAddSlot ¶s) { ANS_LOGI("enter"); @@ -146,7 +176,7 @@ napi_value ParseParametersByAddSlot(const napi_env &env, const napi_callback_inf env, (valuetype == napi_object || valuetype == napi_number), "Wrong argument type. Object or number expected."); if (valuetype == napi_number) { paras.isAddSlotByType = true; - int slotType = 0; + int32_t slotType = 0; napi_get_value_int32(env, argv[PARAM0], &slotType); if (!Common::SlotTypeJSToC(SlotType(slotType), paras.inType)) { return nullptr; @@ -268,7 +298,7 @@ napi_value ParseParametersByGetSlot(const napi_env &env, const napi_callback_inf // argv[0]: SlotType NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int slotType = 0; + int32_t slotType = 0; napi_get_value_int32(env, argv[PARAM0], &slotType); if (!Common::SlotTypeJSToC(SlotType(slotType), paras.outType)) { return nullptr; @@ -359,7 +389,7 @@ napi_value ParseParametersByRemoveSlot( // argv[0]: SlotType NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int slotType = 0; + int32_t slotType = 0; napi_get_value_int32(env, argv[PARAM0], &slotType); if (!Common::SlotTypeJSToC(SlotType(slotType), paras.outType)) { return nullptr; @@ -404,7 +434,7 @@ napi_value AddSlot(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("AddSlot napi_create_async_work start"); - auto asynccallbackinfo = (AsyncCallbackInfoAddSlot *)data; + auto asynccallbackinfo = static_cast(data); if (asynccallbackinfo->isAddSlotByType) { asynccallbackinfo->info.errorCode = NotificationHelper::AddSlotByType(asynccallbackinfo->inType); } else { @@ -413,16 +443,13 @@ napi_value AddSlot(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("AddSlot napi_create_async_work end"); - auto asynccallbackinfo = (AsyncCallbackInfoAddSlot *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + auto asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -464,21 +491,18 @@ napi_value AddSlots(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("AddSlots napi_create_async_work start"); - auto asynccallbackinfo = (AsyncCallbackInfoAddSlots *)data; + auto asynccallbackinfo = static_cast(data); asynccallbackinfo->info.errorCode = NotificationHelper::AddNotificationSlots(asynccallbackinfo->slots); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("AddSlots napi_create_async_work end"); - auto asynccallbackinfo = (AsyncCallbackInfoAddSlots *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + auto asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -520,23 +544,20 @@ napi_value SetSlotByBundle(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("SetSlotByBundle napi_create_async_work start"); - auto asynccallbackinfo = (AsyncCallbackInfoSetSlotByBundle *)data; + auto asynccallbackinfo = static_cast(data); asynccallbackinfo->info.errorCode = NotificationHelper::UpdateNotificationSlots( asynccallbackinfo->params.option, asynccallbackinfo->params.slots); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("SetSlotByBundle napi_create_async_work end"); - auto asynccallbackinfo = (AsyncCallbackInfoSetSlotByBundle *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + auto asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -563,7 +584,7 @@ void AsyncCompleteCallbackGetSlot(napi_env env, napi_status status, void *data) return; } - auto asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; + auto asynccallbackinfo = static_cast(data); napi_value result = Common::NapiGetNull(env); if (asynccallbackinfo->info.errorCode == ERR_OK) { if (asynccallbackinfo->slot == nullptr) { @@ -577,16 +598,12 @@ void AsyncCompleteCallbackGetSlot(napi_env env, napi_status status, void *data) } } Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value GetSlot(napi_env env, napi_callback_info info) @@ -614,7 +631,7 @@ napi_value GetSlot(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetSlot napi_create_async_work start"); - auto asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; + auto asynccallbackinfo = static_cast(data); asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlot(asynccallbackinfo->outType, asynccallbackinfo->slot); @@ -664,17 +681,15 @@ napi_value GetSlotNumByBundle(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("GetSlotNumByBundle napi_create_async_work end"); - auto asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; - napi_value result = nullptr; - napi_create_int32(env, asynccallbackinfo->num, &result); - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + auto asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + napi_value result = nullptr; + napi_create_uint32(env, asynccallbackinfo->num, &result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -727,16 +742,12 @@ void AsyncCompleteCallbackGetSlots(napi_env env, napi_status status, void *data) } } Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value GetSlots(napi_env env, napi_callback_info info) @@ -816,16 +827,12 @@ void AsyncCompleteCallbackGetSlotsByBundle(napi_env env, napi_status status, voi } } Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } napi_value GetSlotsByBundle(napi_env env, napi_callback_info info) @@ -902,15 +909,12 @@ napi_value RemoveSlot(napi_env env, napi_callback_info info) [](napi_env env, napi_status status, void *data) { ANS_LOGI("removeSlot napi_create_async_work end"); auto asynccallbackinfo = (AsyncCallbackInfoRemoveSlot *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } @@ -958,15 +962,236 @@ napi_value RemoveAllSlots(napi_env env, napi_callback_info info) [](napi_env env, napi_status status, void *data) { ANS_LOGI("RemoveAllSlots napi_create_async_work end"); auto asynccallbackinfo = (AsyncCallbackInfoRemoveAllSlots *)data; + if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value ParseParametersEnableSlot( + const napi_env &env, const napi_callback_info &info, ParametersInfoEnableSlot ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = SET_ENABLE_SLOT_MAX_PARA; + napi_value argv[SET_ENABLE_SLOT_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + if (argc < SET_ENABLE_SLOT_MAX_PARA - 1) { + ANS_LOGW("Wrong number of arguments."); + return nullptr; + } + + // argv[0]: bundle + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if (valuetype != napi_object) { + ANS_LOGW("Wrong argument type. Object expected."); + return nullptr; + } + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + + // argv[1]: SlotType + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if (valuetype != napi_number) { + ANS_LOGW("Wrong argument type. Number expected."); + return nullptr; + } + int slotType = 0; + napi_get_value_int32(env, argv[PARAM1], &slotType); + if (!Common::SlotTypeJSToC(SlotType(slotType), params.outType)) { + return nullptr; + } + + // argv[2]: enable + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); + if (valuetype != napi_boolean) { + ANS_LOGW("Wrong argument type. Bool expected."); + return nullptr; + } + napi_get_value_bool(env, argv[PARAM2], ¶ms.enable); + + // argv[3]:callback + if (argc >= SET_ENABLE_SLOT_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM3], &valuetype)); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } + napi_create_reference(env, argv[PARAM3], 1, ¶ms.callback); + } + + return Common::NapiGetNull(env); +} + +napi_value EnableNotificationSlot(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + ParametersInfoEnableSlot params {}; + if (ParseParametersEnableSlot(env, info, params) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoInfoEnableSlot *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoInfoEnableSlot {.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "EnableNotificationSlot", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("EnableNotificationSlot napi_create_async_work start"); + auto asynccallbackinfo = static_cast(data); + + asynccallbackinfo->info.errorCode = NotificationHelper::SetEnabledForBundleSlot( + asynccallbackinfo->params.option, asynccallbackinfo->params.outType, asynccallbackinfo->params.enable); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("EnableNotificationSlot napi_create_async_work end"); + auto asynccallbackinfo = static_cast(data); + if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value ParseParametersIsEnableSlot( + const napi_env &env, const napi_callback_info &info, ParametersInfoIsEnableSlot ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = GET_ENABLE_SLOT_MAX_PARA; + napi_value argv[GET_ENABLE_SLOT_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + if (argc < GET_ENABLE_SLOT_MAX_PARA - 1) { + ANS_LOGW("Wrong number of arguments."); + return nullptr; + } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + // argv[0]: bundle + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if (valuetype != napi_object) { + ANS_LOGW("Wrong argument type. Object expected."); + return nullptr; + } + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + + // argv[1]: SlotType + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if (valuetype != napi_number) { + ANS_LOGW("Wrong argument type. Number expected."); + return nullptr; + } + int slotType = 0; + napi_get_value_int32(env, argv[PARAM1], &slotType); + if (!Common::SlotTypeJSToC(SlotType(slotType), params.outType)) { + return nullptr; + } + + // argv[2]:callback + if (argc >= GET_ENABLE_SLOT_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } + napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); + } + + return Common::NapiGetNull(env); +} + +napi_value IsEnableNotificationSlot(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + ParametersInfoIsEnableSlot params {}; + if (ParseParametersIsEnableSlot(env, info, params) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoInfoIsEnableSlot *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoInfoIsEnableSlot {.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "IsEnableNotificationSlot", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("IsEnableNotificationSlot napi_create_async_work start"); + auto asynccallbackinfo = static_cast(data); + + asynccallbackinfo->info.errorCode = NotificationHelper::GetEnabledForBundleSlot( + asynccallbackinfo->params.option, asynccallbackinfo->params.outType, asynccallbackinfo->isEnable); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("IsEnableNotificationSlot napi_create_async_work end"); + auto asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + napi_value result = nullptr; + napi_get_boolean(env, asynccallbackinfo->isEnable, &result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index 3f975d5a9e47425768385b7e5970d9e0e5521b1c..05a0fc856a3cd17b28c4fad9490ebe337c4eb5eb 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -20,8 +20,8 @@ namespace OHOS { namespace NotificationNapi { -const int SUBSRIBE_MAX_PARA = 3; -const int NO_DELETE_REASON = -1; +const int32_t SUBSRIBE_MAX_PARA = 3; +const int32_t NO_DELETE_REASON = -1; const std::string CONSUME = "onConsume"; const std::string CANCEL = "onCancel"; const std::string UPDATE = "onUpdate"; @@ -39,15 +39,15 @@ struct NotificationReceiveDataWorker { std::shared_ptr sortingMap; NotificationDoNotDisturbDate date; EnabledNotificationCallbackData callbackData; - int deleteReason = 0; - int result = 0; - int disturbMode = 0; + int32_t deleteReason = 0; + int32_t result = 0; + int32_t disturbMode = 0; SubscriberInstance *subscriber = nullptr; }; napi_value SetSubscribeCallbackData(const napi_env &env, const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason, napi_value &result) + const std::shared_ptr &sortingMap, int32_t deleteReason, napi_value &result) { ANS_LOGI("enter"); if (request == nullptr) { @@ -81,7 +81,7 @@ napi_value SetSubscribeCallbackData(const napi_env &env, // reason?: number if (deleteReason != NO_DELETE_REASON) { napi_value value = nullptr; - int outReason = 0; + int32_t outReason = 0; if (!Common::ReasonCToJS(deleteReason, outReason)) { return Common::NapiGetBoolean(env, false); } @@ -184,7 +184,7 @@ void UvQueueWorkOnCanceled(uv_work_t *work, int status) } void SubscriberInstance::OnCanceled(const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason) + const std::shared_ptr &sortingMap, int32_t deleteReason) { ANS_LOGI("enter"); @@ -851,6 +851,17 @@ void SubscriberInstance::SetDisturbDateCallbackInfo(const napi_env &env, const n disturbDateCallbackInfo_.ref = ref; } +bool SubscriberInstance::SetObjectDeleting(bool status) +{ + std::lock_guard lock(delMutex_); + if (isDelete_ && isDelete_ == status) { + return false; + } else { + isDelete_ = status; + return true; + } +} + void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref) { if (type == CONSUME) { @@ -1165,7 +1176,6 @@ napi_value Subscribe(napi_env env, napi_callback_info info) } return Common::NapiGetUndefined(env); } - ANS_LOGI("Subscribe objectInfo = %{public}p", objectInfo); AsyncCallbackInfoSubscribe *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoSubscribe { .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .subscriberInfo = subscriberInfo @@ -1188,6 +1198,10 @@ napi_value Subscribe(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("Subscribe napi_create_async_work start"); + if (!data) { + ANS_LOGE("Invalid asynccallbackinfo!"); + return; + } AsyncCallbackInfoSubscribe *asynccallbackinfo = (AsyncCallbackInfoSubscribe *)data; if (asynccallbackinfo->subscriberInfo.hasSubscribeInfo) { ANS_LOGI("Subscribe with NotificationSubscribeInfo"); @@ -1203,19 +1217,25 @@ napi_value Subscribe(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("Subscribe napi_create_async_work end"); + if (!data) { + ANS_LOGE("Invalid asynccallbackinfo!"); + return; + } AsyncCallbackInfoSubscribe *asynccallbackinfo = (AsyncCallbackInfoSubscribe *)data; + if (!asynccallbackinfo) { + ANS_LOGE("Invalid asynccallbackinfo!"); + return; + } Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + + delete asynccallbackinfo; + asynccallbackinfo = nullptr; }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); diff --git a/interfaces/kits/napi/ans/src/unsubscribe.cpp b/interfaces/kits/napi/ans/src/unsubscribe.cpp index 7ffc15278f2bcb79bf9ffbc11535dac7cf9951d9..9bd006a38a31464aa1e1b08da902f1e3d9b660ee 100644 --- a/interfaces/kits/napi/ans/src/unsubscribe.cpp +++ b/interfaces/kits/napi/ans/src/unsubscribe.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -100,21 +100,26 @@ napi_value Unsubscribe(napi_env env, napi_callback_info info) return; } - asynccallbackinfo->info.errorCode = - NotificationHelper::UnSubscribeNotification(*(asynccallbackinfo->objectInfo)); + bool ret = asynccallbackinfo->objectInfo->SetObjectDeleting(true); + if (ret) { + asynccallbackinfo->info.errorCode = + NotificationHelper::UnSubscribeNotification(*(asynccallbackinfo->objectInfo)); + if (asynccallbackinfo->info.errorCode != ERR_OK) { + asynccallbackinfo->objectInfo->SetObjectDeleting(false); + } + } else { + asynccallbackinfo->info.errorCode = ERR_ANS_SUBSCRIBER_ALREADY_DELETE; + } }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("Unsubscribe napi_create_async_work end"); - AsyncCallbackInfoUnsubscribe *asynccallbackinfo = (AsyncCallbackInfoUnsubscribe *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); + AsyncCallbackInfoUnsubscribe *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); delete asynccallbackinfo; asynccallbackinfo = nullptr; } diff --git a/notification.gni b/notification.gni index d379ebca68f2c01579466d070d07bf1541996cb3..6d9434f626ff7fd05c357a22ef55eb65ee8584d7 100644 --- a/notification.gni +++ b/notification.gni @@ -32,10 +32,10 @@ aafwk_path = "//foundation/aafwk/standard" ans_standard_external_deps = [ "ability_base:base", "ability_base:want", + "ability_base:zuri", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "ces_standard:cesfwk_innerkits", - "dmsfwk_standard:zuri", + "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/sa_profile/3203.xml b/sa_profile/3203.xml old mode 100644 new mode 100755 index 55c3ff31e2aa4ff1f2bf9c2d962e27bf0cc09837..6b23aaf57a30735e861a504790aab516bbb4f5ce --- a/sa_profile/3203.xml +++ b/sa_profile/3203.xml @@ -16,7 +16,7 @@ foundation 3203 - /system/lib/libans.z.so + libans.z.so 1301 3299 5000 diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 9193489a9d9e368ec5ed1a20fff6ef1d29f2debf..bfa66da97fbb662e7ccab32497236b1aefd9c24a 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -30,6 +30,7 @@ ohos_shared_library("libans") { include_dirs = [ "include" ] sources = [ + "src/access_token_helper.cpp", "src/advanced_notification_service.cpp", "src/advanced_notification_service_ability.cpp", "src/bundle_manager_helper.cpp", @@ -53,10 +54,13 @@ ohos_shared_library("libans") { defines = [] deps = [ + ":downloadTemplate.abc", + ":downloadTemplate.js", + ":external.json", "${core_path}:ans_core", "${frameworks_path}/ans/dialog/dialog_ui/js:dialog_js_files_etc", "${frameworks_path}/ans/native:ans_innerkits", - "//foundation/ace/ace_engine/interfaces/innerkits/ui_service_manager:ui_service_mgr", + "//foundation/arkui/ace_engine/interfaces/inner_api/ui_service_manager:ui_service_mgr", "//utils/native/base:utils", ] @@ -78,7 +82,7 @@ ohos_shared_library("libans") { "distributeddatamgr:distributeddata_inner", "multimedia_image_standard:image_native", "multimedia_media_standard:media_client", - "os_account_standard:os_account_innerkits", + "os_account:os_account_innerkits", "time_native:time_service", "window_manager:libwm", ] @@ -87,3 +91,25 @@ ohos_shared_library("libans") { subsystem_name = "notification" part_name = "ans_standard" } + +ohos_prebuilt_etc("external.json") { + source = + "//base/notification/ans_standard/services/ans/resource/external.json" + relative_install_dir = "notification_template" + subsystem_name = "notification" + part_name = "ans_standard" +} + +ohos_prebuilt_etc("downloadTemplate.abc") { + source = "//base/notification/ans_standard/services/ans/resource/downloadTemplate.abc" + relative_install_dir = "notification_template/assets/js" + subsystem_name = "notification" + part_name = "ans_standard" +} + +ohos_prebuilt_etc("downloadTemplate.js") { + source = "//base/notification/ans_standard/services/ans/resource/downloadTemplate.js" + relative_install_dir = "notification_template/assets/js" + subsystem_name = "notification" + part_name = "ans_standard" +} diff --git a/services/ans/include/access_token_helper.h b/services/ans/include/access_token_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..cc8ec8fb8b0b7fdf9f02f016141ed9fa89710e51 --- /dev/null +++ b/services/ans/include/access_token_helper.h @@ -0,0 +1,40 @@ +/* + * 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 BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_ACCESS_TOKEN_HELPER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_ACCESS_TOKEN_HELPER_H + +#include + +#include "accesstoken_kit.h" + +namespace OHOS { +namespace Notification { +class AccessTokenHelper { +public: + /** + * @brief Verifies that the caller has the specified permission. + * + * @param tokenCaller The AccessTokenID of caller. + * @param permission The permission to be verified. + * @return Returns true if the caller has the specified permission, false otherwise. + */ + static bool VerifyCallerPermission( + const Security::AccessToken::AccessTokenID &tokenCaller, const std::string &permission); + static bool VerifyNativeToken(const Security::AccessToken::AccessTokenID &callerToken); +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_ACCESS_TOKEN_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 fb86fd4e03edb176fdb86f1bfb8ed486fe0115f5..bf6864d6f7b3337282a11447ff8f519a54404818 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -40,107 +40,696 @@ namespace Notification { class AdvancedNotificationService final : public AnsManagerStub { public: ~AdvancedNotificationService() override; + DISALLOW_COPY_AND_MOVE(AdvancedNotificationService); + /** + * @brief Get the instance of service. + * + * @return Returns the instance. + */ static sptr GetInstance(); // AnsManagerStub + + /** + * @brief Publishes a notification with a specified label. + * @note If a notification with the same ID has been published by the current application and has not been deleted, + * this method will update the notification. + * + * @param label Indicates the label of the notification to publish. + * @param notification Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode Publish(const std::string &label, const sptr &request) override; - ErrCode Cancel(int notificationId, const std::string &label) override; + + /** + * @brief Cancels a published notification matching the specified label and notificationId. + * + * @param notificationId Indicates the ID of the notification to cancel. + * @param label Indicates the label of the notification to cancel. + * @return Returns cancel notification result. + */ + ErrCode Cancel(int32_t notificationId, const std::string &label) override; + + /** + * @brief Cancels all the published notifications. + * + * @return Returns ERR_OK on success, others on failure. + */ ErrCode CancelAll() override; + + /** + * @brief Cancels a published agent notification. + * + * @param notificationId Indicates the unique notification ID in the application. + * The value must be the ID of a published notification. + * Otherwise, this method does not take effect. + * @param representativeBundle Indicates the name of application bundle your application is representing. + * @param userId Indicates the specific user. + * @return Returns cancel notification result. + */ + ErrCode CancelAsBundle( + int32_t notificationId, const std::string &representativeBundle, int32_t userId) override; + + /** + * @brief Adds a notification slot by type. + * + * @param slotType Indicates the notification slot type to be added. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode AddSlotByType(NotificationConstant::SlotType slotType) override; + + /** + * @brief Creates multiple notification slots. + * + * @param slots Indicates the notification slots to create. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode AddSlots(const std::vector> &slots) override; + + /** + * @brief Deletes a created notification slot based on the slot ID. + * + * @param slotType Indicates the type of the slot, which is created by AddNotificationSlot + * This parameter must be specified. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode RemoveSlotByType(const NotificationConstant::SlotType &slotType) override; + + /** + * @brief Deletes all notification slots. + * + * @return Returns ERR_OK on success, others on failure. + */ ErrCode RemoveAllSlots() override; + + /** + * @brief Creates multiple notification slot groups. + * @note The precautions for using this method are similar to those for + * AddNotificationSlotGroup(NotificationSlotGroup). + * + * @param groups Indicates a list of NotificationSlotGroup objects to create. This parameter cannot be null. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode AddSlotGroups(std::vector> groups) override; + + /** + * @brief Queries a created notification slot. + * + * @param slotType Indicates the ID of the slot, which is created by AddNotificationSlot(NotificationSlot). This + * parameter must be specified. + * @param slot Indicates the created NotificationSlot. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetSlotByType(const NotificationConstant::SlotType &slotType, sptr &slot) override; + + /** + * @brief Obtains all notification slots of this application. + * + * @param slots Indicates the created NotificationSlot. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetSlots(std::vector> &slots) override; + + /** + * @brief Queries a created notification slot group. + * + * @param groupId Indicates the ID of the slot group. + * @param group Indicates the created NotificationSlotGroup. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetSlotGroup(const std::string &groupId, sptr &group) override; + + /** + * @brief Obtains a list of created notification slot groups. + * + * @param groups Indicates a list of created notification slot groups. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetSlotGroups(std::vector> &groups) override; - ErrCode GetSlotNumAsBundle(const sptr &bundleOption, int &num) override; + + /** + * @brief Obtains the number of slot. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param num Indicates the number of slot. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetSlotNumAsBundle(const sptr &bundleOption, uint64_t &num) override; + + /** + * @brief Deletes multiple notification slot groups. + * + * @param groupIds Indicates the IDs of the notification slot groups, which is created by + * AddNotificationSlotGroup(NotificationSlotGroup) This parameter must be specified. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode RemoveSlotGroups(const std::vector &groupIds) override; + + /** + * @brief Obtains active notifications of the current application in the system. + * + * @param notifications Indicates active NotificationRequest objects of the current application. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetActiveNotifications(std::vector> ¬ifications) override; - ErrCode GetActiveNotificationNums(int &num) override; + + /** + * @brief Obtains the number of active notifications of the current application in the system. + * + * @param num Indicates the number of active notifications of the current application. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetActiveNotificationNums(uint64_t &num) override; + + /** + * @brief Obtains all active notifications in the current system. The caller must have system permissions to + * call this method. + * + * @param notifications Indicates all active notifications of this application. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetAllActiveNotifications(std::vector> ¬ifications) override; + + /** + * @brief Obtains the active notifications corresponding to the specified key in the system. To call this method + * to obtain particular active notifications, you must have received the notifications and obtained the key + * via {Notification::GetKey()}. + * + * @param key Indicates the key array for querying corresponding active notifications. + * If this parameter is null, this method returns all active notifications in the system. + * @param notification Indicates the set of active notifications corresponding to the specified key. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetSpecialActiveNotifications( const std::vector &key, std::vector> ¬ifications) override; + + /** + * @brief Allows another application to act as an agent to publish notifications in the name of your application + * bundle. + * + * @param agent Indicates the name of the application bundle that can publish notifications for your application. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode SetNotificationAgent(const std::string &agent) override; + + /** + * @brief Obtains the name of the application bundle that can publish notifications in the name of your application. + * + * @param agent Indicates the name of the application bundle that can publish notifications for your application if + * any; returns null otherwise. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetNotificationAgent(std::string &agent) override; + + /** + * @brief Checks whether your application has permission to publish notifications by calling + * PublishNotificationAsBundle(string, NotificationRequest) in the name of another application indicated by the + * given representativeBundle. + * + * @param representativeBundle Indicates the name of application bundle your application is representing. + * @param canPublish Indicates whether your application has permission to publish notifications. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) override; + + /** + * @brief Publishes a notification in the name of a specified application bundle. + * @note If the notification to be published has the same ID as a published notification that has not been canceled, + * the existing notification will be replaced by the new one. + * + * @param notification Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @param representativeBundle Indicates the name of the application bundle that allows your application to publish + * notifications for it by calling setNotificationAgent. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode PublishAsBundle( const sptr notification, const std::string &representativeBundle) override; - ErrCode SetNotificationBadgeNum(int num) override; - ErrCode GetBundleImportance(int &importance) override; + + /** + * @brief Sets the number of active notifications of the current application as the number to be displayed on the + * notification badge. + * + * @param num Indicates the badge number. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode SetNotificationBadgeNum(int32_t num) override; + + /** + * @brief Obtains the importance level of this application. + * + * @param importance Indicates the importance level of this application, which can be LEVEL_NONE, + LEVEL_MIN, LEVEL_LOW, LEVEL_DEFAULT, LEVEL_HIGH, or LEVEL_UNDEFINED. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetBundleImportance(int32_t &importance) override; + + /** + * @brief Checks whether this application has permission to modify the Do Not Disturb (DND) notification policy. + * + * @param granted True if the application has permission; false for otherwise. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; + + /** + * @brief Set whether to allow private notifications. + * + * @param allow Indicates the flag that allows private notification. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode SetPrivateNotificationsAllowed(bool allow) override; + + /** + * @brief Get whether to allow private notifications. + * + * @param allow Indicates the flag that allows private notification. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetPrivateNotificationsAllowed(bool &allow) override; + + /** + * @brief Delete notification. + * + * @param bundleOption Indicates the NotificationBundleOption of the notification. + * @param notificationId Indicates the id of the notification. + * @param label Indicates the label of the notification. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode RemoveNotification( - const sptr &bundleOption, int notificationId, const std::string &label) override; + const sptr &bundleOption, int32_t notificationId, const std::string &label) override; + + /** + * @brief Delete all notifications. + * + * @param bundleOption Indicates the NotificationBundleOption of notifications. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode RemoveAllNotifications(const sptr &bundleOption) override; + + /** + * @brief Delete notification based on key. + * + * @param key Indicates the key to delete notification. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode Delete(const std::string &key) override; + + /** + * @brief Remove notifications based on bundle. + * + * @param bundleOption Indicates the NotificationBundleOption of notifications. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode DeleteByBundle(const sptr &bundleOption) override; + + /** + * @brief Remove all notifications. + * + * @return Returns ERR_OK on success, others on failure. + */ ErrCode DeleteAll() override; + /** + * @brief Get all the slots corresponding to the bundle. + * + * @param bundleOption Indicates the NotificationBundleOption object. + * @param slots Indicates the notification slots. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetSlotsByBundle( const sptr &bundleOption, std::vector> &slots) override; + + /** + * @brief Update slots according to bundle. + * + * @param bundleOption Indicates the NotificationBundleOption object. + * @param slots Indicates the notification slots to be updated. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode UpdateSlots( const sptr &bundleOption, const std::vector> &slots) override; + + /** + * @brief Update slotgroup according to bundle. + * + * @param bundleOption Indicates the NotificationBundleOption object. + * @param groups Indicates the notification slots to be updated. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode UpdateSlotGroups(const sptr &bundleOption, const std::vector> &groups) override; + + /** + * @brief Allow notifications to be sent based on the deviceId. + * + * @param deviceId Indicates the device Id. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode RequestEnableNotification(const std::string &deviceId) override; - ErrCode SetNotificationsEnabledForBundle(const std::string &bundle, bool enabled) override; + + /** + * @brief Set whether to allow the specified deviceId to send notifications for current bundle. + * + * @param deviceId Indicates the device Id. + * @param enabled Indicates the flag that allows notification to be pulished. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) override; + + /** + * @brief Set whether to allow the specified deviceId to send notifications for all bundles. + * + * @param deviceId Indicates the device Id. + * @param enabled Indicates the flag that allows notification to be pulished. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) override; + + /** + * @brief Set whether to allow the specified bundle to send notifications. + * + * @param bundleOption Indicates the NotificationBundleOption object. + * @param enabled Indicates the flag that allows notification to be pulished. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode SetNotificationsEnabledForSpecialBundle( const std::string &deviceId, const sptr &bundleOption, bool enabled) override; + + /** + * @brief Sets whether the bundle allows the banner to display notification. + * + * @param bundleOption Indicates the NotificationBundleOption object. + * @param enabled Indicates the flag that allows badge to be shown. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode SetShowBadgeEnabledForBundle(const sptr &bundleOption, bool enabled) override; + + /** + * @brief Gets whether the bundle allows the badge to display the status of notifications. + * + * @param bundleOption Indicates the NotificationBundleOption object. + * @param enabled Indicates the flag that allows badge to be shown. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetShowBadgeEnabledForBundle(const sptr &bundleOption, bool &enabled) override; + + /** + * @brief Gets whether allows the badge to display the status of notifications. + * + * @param enabled Indicates the flag that allows badge to be shown. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetShowBadgeEnabled(bool &enabled) override; + + /** + * @brief Subscribes notifications. + * + * @param subscriber Indicates the subscriber. + * @param info Indicates the NotificationSubscribeInfo object. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode Subscribe(const sptr &subscriber, const sptr &info) override; + + /** + * @brief Unsubscribes notifications. + * + * @param subscriber Indicates the subscriber. + * @param info Indicates the NotificationSubscribeInfo object. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode Unsubscribe(const sptr &subscriber, const sptr &info) override; + + /** + * @brief Checks whether this device is allowed to publish notifications. + * + * @param allowed Indicates the flag that allows notification. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode IsAllowedNotify(bool &allowed) override; + + /** + * @brief Checks whether this application is allowed to publish notifications. + * + * @param allowed Indicates the flag that allows notification. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode IsAllowedNotifySelf(bool &allowed) override; + + /** + * @brief Checks whether notifications are allowed for a specific bundle. + * + * @param bundleOption Indicates the NotificationBundleOption object. + * @param allowed Indicates the flag that allows notification. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override; + /** + * @brief Set do not disturb date. + * + * @param date Indicates the NotificationDoNotDisturbDate object. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode SetDoNotDisturbDate(const sptr &date) override; + + /** + * @brief Get do not disturb date. + * + * @param date Indicates the NotificationDoNotDisturbDate object. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetDoNotDisturbDate(sptr &date) override; + + /** + * @brief Get whether Do Not Disturb mode is supported. + * + * @param doesSupport Indicates the flag that supports DND mode. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override; + + /** + * @brief Cancel notifications according to group. + * + * @param groupName Indicates the group name. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode CancelGroup(const std::string &groupName) override; + + /** + * @brief Delete notifications according to bundle and group. + * + * @param bundleOption Indicates the NotificationBundleOption object. + * @param groupName Indicates the group name. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode RemoveGroupByBundle( const sptr &bundleOption, const std::string &groupName) override; + /** + * @brief Gets whether distributed notification is enabled. + * + * @param enabled Indicates the enabled flag. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode IsDistributedEnabled(bool &enabled) override; + + /** + * @brief Sets distributed notification enabled or disabled. + * + * @param enabled Indicates the enabled flag. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode EnableDistributed(bool enabled) override; + + /** + * @brief Sets distributed notification enabled or disabled for specific bundle. + * + * @param bundleOption Indicates the NotificationBundleOption object. + * @param enabled Indicates the enabled flag. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode EnableDistributedByBundle(const sptr &bundleOption, bool enabled) override; + + /** + * @brief Sets distributed notification enabled or disabled for current bundle. + * + * @param enabled Indicates the enabled flag. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode EnableDistributedSelf(bool enabled) override; + + /** + * @brief Gets whether distributed notification is enabled for specific bundle. + * + * @param bundleOption Indicates the NotificationBundleOption object. + * @param enabled Indicates the enabled flag. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode IsDistributedEnableByBundle(const sptr &bundleOption, bool &enabled) override; + + /** + * @brief Get the reminder type of the current device. + * + * @param remindType Reminder type for the device. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetDeviceRemindType(NotificationConstant::RemindType &remindType) override; + /** + * @brief Dump current running status for debuging. + * + * @param dumpOption Indicates the dump action that needs to be performed. + * @param dumpInfo Indicates the dump information. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; + + /** + * @brief Publishes a continuous notification. + * + * @param request Notification requests that need to be posted. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode PublishContinuousTaskNotification(const sptr &request) override; + + /** + * @brief Cancels a continuous notification. + * + * @param label Identifies the label of the specified notification. + * @param notificationId Identifies the id of the specified notification. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) override; + + /** + * @brief Publishes a reminder notification. + * + * @param reminder Identifies the reminder notification request that needs to be published. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode PublishReminder(sptr &reminder) override; + + /** + * @brief Cancel a reminder notifications. + * + * @param reminderId Identifies the reminders id that needs to be canceled. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode CancelReminder(const int32_t reminderId) override; + + /** + * @brief Get all valid reminder notifications. + * + * @param reminders Identifies the list of all valid notifications. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetValidReminders(std::vector> &reminders) override; + + /** + * @brief Cancel all reminder notifications. + * + * @return Returns ERR_OK on success, others on failure. + */ ErrCode CancelAllReminders() override; + + /** + * @brief Checks whether this device is support template. + * + * @param templateName Identifies the template name for searching as a condition. + * @param support Identifies the support flag. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode IsSupportTemplate(const std::string &templateName, bool &support) override; + + /** + * @brief Checks Whether the specified users is allowed to publish notifications. + * + * @param userId Identifies the user's id. + * @param allowed Identifies the allowed flag. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed) override; + + /** + * @brief Sets whether to allow all applications to publish notifications on a specified device. The caller must + * have system permissions to call this method. + * + * @param deviceId Indicates the ID of the device running the application. At present, this parameter can only + * be null or an empty string, indicating the current device. + * @param enabled Specifies whether to allow all applications to publish notifications. The value true + * indicates that notifications are allowed, and the value false indicates that notifications + * are not allowed. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode SetNotificationsEnabledByUser(const int32_t &deviceId, bool enabled) override; + + /** + * @brief Delete all notifications by user. + * + * @param userId Indicates the user id. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode DeleteAllByUser(const int32_t &userId) override; + + /** + * @brief Set do not disturb date by user. + * + * @param userId Indicates the user id. + * @param date Indicates NotificationDoNotDisturbDate object. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode SetDoNotDisturbDate(const int32_t &userId, const sptr &date) override; + + /** + * @brief Get the do not disturb date by user. + * + * @param userId Indicates the user id. + * @param date Indicates the NotificationDoNotDisturbDate object. + * @return Returns ERR_OK on success, others on failure. + */ ErrCode GetDoNotDisturbDate(const int32_t &userId, sptr &date) override; + ErrCode SetEnabledForBundleSlot(const sptr &bundleOption, + const NotificationConstant::SlotType &slotType, bool enabled) override; + ErrCode GetEnabledForBundleSlot(const sptr &bundleOption, + const NotificationConstant::SlotType &slotType, bool &enabled) override; // SystemEvent + + /** + * @brief Obtains the event of bundle removed. + * + * @param bundleOption Indicates the bundle info. + */ void OnBundleRemoved(const sptr &bundleOption); + #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + /** + * @brief Obtains the event of turn on screen. + */ void OnScreenOn(); + + /** + * @brief Obtains the event of turn off screen. + */ void OnScreenOff(); #endif void OnResourceRemove(int32_t userId); + void OnBundleDataCleared(const sptr &bundleOption); // Distributed KvStore + + /** + * @brief Obtains the death event of the Distributed KvStore service. + */ void OnDistributedKvStoreDeathRecipient(); + ErrCode CancelPreparedNotification( - int notificationId, const std::string &label, const sptr &bundleOption); + int32_t notificationId, const std::string &label, const sptr &bundleOption); ErrCode PrepareNotificationInfo( const sptr &request, sptr &bundleOption); ErrCode PublishPreparedNotification( @@ -158,10 +747,10 @@ private: void UpdateInNotificationList(const std::shared_ptr &record); ErrCode AssignToNotificationList(const std::shared_ptr &record); ErrCode RemoveFromNotificationList(const sptr &bundleOption, const std::string &label, - int notificationId, sptr ¬ification, bool isCancel = false); + int32_t notificationId, sptr ¬ification, bool isCancel = false); ErrCode RemoveFromNotificationList(const std::string &key, sptr ¬ification, bool isCancel = false); ErrCode RemoveFromNotificationListForDeleteAll(const std::string &key, - const int &userId, sptr ¬ification); + const int32_t &userId, sptr ¬ification); std::vector GetNotificationKeys(const sptr &bundleOption); bool IsNotificationExists(const std::string &key); void SortNotificationList(); @@ -181,14 +770,17 @@ private: ErrCode DistributedNotificationDump(std::vector &dumpInfo); #endif ErrCode SetRecentNotificationCount(const std::string arg); - void UpdateRecentNotification(sptr ¬ification, bool isDelete, int reason); + void UpdateRecentNotification(sptr ¬ification, bool isDelete, int32_t reason); void AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate); - bool CheckPermission(const std::string &bundleName); - ErrCode PrepereContinuousTaskNotificationRequest(const sptr &request, const int &uid); + bool CheckPermission(const std::string &permission); + ErrCode PrepareNotificationRequest(const sptr &request); + ErrCode PrepareContinuousTaskNotificationRequest(const sptr &request, const int32_t &uid); bool GetActiveUserId(int& userId); void TriggerRemoveWantAgent(const sptr &request); bool CheckApiCompatibility(const sptr &bundleOption); + ErrCode IsAllowedNotifySelf(const sptr &bundleOption, bool &allowed); + void GetDisplayPosition(int& offsetX, int& offsetY, int& width, int& height, bool& wideScreen); ErrCode SetNotificationRemindType(sptr notification, bool isLocal); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -198,6 +790,7 @@ private: const sptr bundleOption, const std::shared_ptr record); ErrCode DoDistributedDelete(const std::string deviceId, const sptr notification); std::string GetNotificationDeviceId(const std::string &key); + bool CheckDistributedNotificationType(const sptr &request); void OnDistributedPublish( const std::string &deviceId, const std::string &bundleName, sptr &request); void OnDistributedUpdate( @@ -211,6 +804,10 @@ private: ErrCode GetDoNotDisturbDateByUser(const int32_t &userId, sptr &date); ErrCode SetHasPoppedDialog(const sptr bundleOption, bool hasPopped); ErrCode GetHasPoppedDialog(const sptr bundleOption, bool &hasPopped); + ErrCode GetAppTargetBundle(const sptr &bundleOption, + sptr &targetBundle); + bool PublishSlotChangeCommonEvent( + const sptr &bundleOption, const NotificationConstant::SlotType &slotType); private: static sptr instance_; diff --git a/services/ans/include/advanced_notification_service_ability.h b/services/ans/include/advanced_notification_service_ability.h index ec5c866d8169672394e40ff6507a2da72a8a1df4..65e872ca4c1c7ee9e2799cdda4b408bd6d5de6f0 100644 --- a/services/ans/include/advanced_notification_service_ability.h +++ b/services/ans/include/advanced_notification_service_ability.h @@ -19,14 +19,26 @@ #include "system_ability.h" #include "advanced_notification_service.h" +#include "reminder_data_manager.h" #include "system_ability_definition.h" namespace OHOS { namespace Notification { class AdvancedNotificationServiceAbility final : public SystemAbility { public: + /** + * @brief The constructor of service ability. + * + * @param systemAbilityId Indicates the system ability id. + * @param runOnCreate Run the system ability on created. + */ AdvancedNotificationServiceAbility(const int32_t systemAbilityId, bool runOnCreate); + + /** + * @brief The deconstructor. + */ ~AdvancedNotificationServiceAbility() final; + DISALLOW_COPY_AND_MOVE(AdvancedNotificationServiceAbility); DECLARE_SYSTEM_ABILITY(AdvancedNotificationServiceAbility); @@ -36,6 +48,7 @@ private: private: sptr service_; + std::shared_ptr reminderAgent_; }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index 1ddaf79187f5f1425ad4ea59f700b659af2da745..12a53f37a8c052b4d27f08797a6f7fa87736f7df 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -23,6 +23,7 @@ #include "bundle_mgr_interface.h" #include "ipc_skeleton.h" #include "iremote_object.h" +#include "notification_bundle_option.h" #include "refbase.h" #include "remote_death_recipient.h" #include "singleton.h" @@ -31,12 +32,58 @@ namespace OHOS { namespace Notification { class BundleManagerHelper : public DelayedSingleton { public: - std::string GetBundleNameByUid(int uid); - bool IsSystemApp(int uid); - int GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId); + /** + * @brief Obtains the bundle name base on the specified uid. + * + * @param uid Indicates the specified uid. + * @return Returns the bundle name. + */ + std::string GetBundleNameByUid(int32_t uid); + + /** + * @brief Check whether the caller is a system application base on the specified uid. + * + * @param uid Indicates the specified uid. + * @return Returns the check result. + */ + bool IsSystemApp(int32_t uid); + + /** + * @brief Check API compatibility. + * + * @param bundleOption Indicates the bundle option. + * @return Returns the check result. + */ + bool CheckApiCompatibility(const sptr &bundleOption); + + /** + * @brief Obtains the default uid. + * + * @param bundle Indicates the bundle name. + * @param userId Indicates the user id. + * @return Returns the uid. + */ + int32_t GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId); + + /** + * @brief Obtains the bundle info. + * + * @param bundle Indicates the bundle name. + * @param userId Indicates the user id. + * @param bundleInfo Indicates the bundle info. + * @return Returns the uid. + */ bool GetBundleInfoByBundleName(const std::string bundle, const int32_t userId, AppExecFwk::BundleInfo &bundleInfo); + #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED - bool GetDistributedNotificationEnabled(const std::string &bundleName, const int userId); + /** + * @brief Check whether the specified bundle has the distributed notification supported. + * + * @param bundleName Indicates the bundle name. + * @param userId Indicates the user id. + * @return Returns the check result. + */ + bool GetDistributedNotificationEnabled(const std::string &bundleName, const int32_t userId); #endif private: diff --git a/services/ans/include/distributed_kvstore_death_recipient.h b/services/ans/include/distributed_kvstore_death_recipient.h index a023318892e01241f667bc2fddcaa37746b13bb5..d886d171d62813d0421a22346fea223c3a10d121 100644 --- a/services/ans/include/distributed_kvstore_death_recipient.h +++ b/services/ans/include/distributed_kvstore_death_recipient.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -24,14 +24,25 @@ namespace OHOS { namespace Notification { class DistributedKvStoreDeathRecipient : public DistributedKv::KvStoreDeathRecipient { public: - DistributedKvStoreDeathRecipient(const std::function &callback) + /** + * @brief The constructor. + * + * @param callback Indicates the callback. + */ + explicit DistributedKvStoreDeathRecipient(const std::function &callback) { callback_ = callback; } + /** + * @brief The deconstructor. + */ virtual ~DistributedKvStoreDeathRecipient() {} + /** + * @brief Obtains the death event. Inherited from DistributedKv::KvStoreDeathRecipient. + */ void OnRemoteDied() override { if (callback_ != nullptr) { diff --git a/services/ans/include/interface_system_event.h b/services/ans/include/interface_system_event.h index a68618e0894a2f0499ba3ddca76451346acbdb1f..9d8513c1297b3bb4f46ba45269760fdeb5ee30b0 100644 --- a/services/ans/include/interface_system_event.h +++ b/services/ans/include/interface_system_event.h @@ -30,6 +30,7 @@ struct ISystemEvent { std::function onScreenOff; #endif std::function onResourceRemove; + std::function &)> onBundleDataCleared; }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_filter.h b/services/ans/include/notification_filter.h index 4c229109e32e821e8895c07f879e21aff5490c91..1d98a0e1fff9695af7d92590b99c7163aff8ded8 100644 --- a/services/ans/include/notification_filter.h +++ b/services/ans/include/notification_filter.h @@ -29,9 +29,22 @@ public: INotificationFilter() {}; virtual ~INotificationFilter() {}; + /** + * @brief Start the filter. + */ virtual void OnStart() = 0; + + /** + * @brief Stop the filter. + */ virtual void OnStop() = 0; + /** + * @brief Filters the publish operation. + * + * @param record Indicates the NotificationRecord. + * @return Returns the filter result. + */ virtual ErrCode OnPublish(const std::shared_ptr &record) = 0; }; } // namespace Notification diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 63d6053779f2f7c6f528cc246e7ab9c024c3b85a..717f50261b2d7a6048b02194594bd54284e6f90c 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -27,53 +27,298 @@ namespace Notification { class NotificationPreferences final { public: DISALLOW_COPY_AND_MOVE(NotificationPreferences); + + /** + * @brief Get NotificationPreferences instance object. + */ static NotificationPreferences &GetInstance(); + + /** + * @brief Add notification slots into DB. + * + * @param bundleOption Indicates bunlde info label. + * @param slots Indicates add notification slots. + * @return Return ERR_OK on success, others on failure. + */ ErrCode AddNotificationSlots( const sptr &bundleOption, const std::vector> &slots); + + /** + * @brief Add notification slot groups into DB. + * + * @param bundleOption Indicates bunlde info label. + * @param groups Indicates add notification slot groups. + * @return Return ERR_OK on success, others on failure. + */ ErrCode AddNotificationSlotGroups( const sptr &bundleOption, const std::vector> &groups); + + /** + * @brief Add notification bunle info into DB. + * + * @param bundleOption Indicates bunlde info. + * @return Return ERR_OK on success, others on failure. + */ ErrCode AddNotificationBundleProperty(const sptr &bundleOption); + + /** + * @brief Remove notification a slot in the of bundle from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param slotType Indicates slot type. + * @return Return ERR_OK on success, others on failure. + */ ErrCode RemoveNotificationSlot( const sptr &bundleOption, const NotificationConstant::SlotType &slotType); + + /** + * @brief Remove notification all slot in the of bundle from DB. + * + * @param bundleOption Indicates bunlde info label. + * @return Return ERR_OK on success, others on failure. + */ ErrCode RemoveNotificationAllSlots(const sptr &bundleOption); + + /** + * @brief Remove notification all slot in the of bundle from DB. + * + * @param bundleOption Indicates bunlde info label. + * @return Return ERR_OK on success, others on failure. + */ ErrCode RemoveNotificationSlotGroups( const sptr &bundleOption, const std::vector &groupIds); + + /** + * @brief Remove notification bundle from DB. + * + * @param bundleOption Indicates bunlde info label. + * @return Return ERR_OK on success, others on failure. + */ ErrCode RemoveNotificationForBundle(const sptr &bundleOption); + + /** + * @brief Update notification slot into DB. + * + * @param bundleOption Indicates bunlde info label. + * @param slot Indicates need to upadte slot. + * @return Return ERR_OK on success, others on failure. + */ ErrCode UpdateNotificationSlots( const sptr &bundleOption, const std::vector> &slot); + + /** + * @brief Update notification slot group into DB. + * + * @param bundleOption Indicates bunlde info label. + * @param slot Indicates need to upadte slot group. + * @return Return ERR_OK on success, others on failure. + */ ErrCode UpdateNotificationSlotGroups( const sptr &bundleOption, const std::vector> &groups); + + /** + * @brief Get notification slot from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param type Indicates to get slot type. + * @param slot Indicates to get slot. + * @return Return ERR_OK on success, others on failure. + */ ErrCode GetNotificationSlot(const sptr &bundleOption, const NotificationConstant::SlotType &type, sptr &slot); + + /** + * @brief Get notification all slots in a bundle from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param slots Indicates to get slots. + * @return Return ERR_OK on success, others on failure. + */ ErrCode GetNotificationAllSlots( const sptr &bundleOption, std::vector> &slots); - ErrCode GetNotificationSlotsNumForBundle(const sptr &bundleOption, int &num); + + /** + * @brief Get notification slot num in a bundle from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param num Indicates to get slot num. + * @return Return ERR_OK on success, others on failure. + */ + ErrCode GetNotificationSlotsNumForBundle(const sptr &bundleOption, uint64_t &num); + + /** + * @brief Get notification group in a bundle from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param groupId Indicates to get group id. + * @param group Indicates to get slot group. + * @return Return ERR_OK on success, others on failure. + */ ErrCode GetNotificationSlotGroup(const sptr &bundleOption, const std::string &groupId, sptr &group); + + /** + * @brief Get notification all group in a bundle from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param groups Indicates to get slot groups. + * @return Return ERR_OK on success, others on failure. + */ ErrCode GetNotificationAllSlotGroups( const sptr &bundleOption, std::vector> &groups); + + /** + * @brief Get notification all slot in a group in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param groupId Indicates to get group id. + * @param slots Indicates to get slots. + * @return Return ERR_OK on success, others on failure. + */ ErrCode GetNotificationAllSlotInSlotGroup(const sptr &bundleOption, const std::string &groupId, std::vector> &slots); + + /** + * @brief Get show badge in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param enable Indicates to whether to show badge + * @return Return ERR_OK on success, others on failure. + */ ErrCode IsShowBadge(const sptr &bundleOption, bool &enable); + + /** + * @brief Set show badge in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param enable Indicates to set show badge + * @return Return ERR_OK on success, others on failure. + */ ErrCode SetShowBadge(const sptr &bundleOption, const bool enable); - ErrCode GetImportance(const sptr &bundleOption, int &importance); - ErrCode SetImportance(const sptr &bundleOption, const int &importance); - ErrCode GetTotalBadgeNums(const sptr &bundleOption, int &totalBadgeNum); - ErrCode SetTotalBadgeNums(const sptr &bundleOption, const int num); + + /** + * @brief Get importance in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param importance Indicates to importance label which can be LEVEL_NONE, + LEVEL_MIN, LEVEL_LOW, LEVEL_DEFAULT, LEVEL_HIGH, or LEVEL_UNDEFINED. + * @return Return ERR_OK on success, others on failure. + */ + ErrCode GetImportance(const sptr &bundleOption, int32_t &importance); + + /** + * @brief Set importance in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param importance Indicates to set a importance label which can be LEVEL_NONE, + LEVEL_MIN, LEVEL_LOW, LEVEL_DEFAULT, LEVEL_HIGH, or LEVEL_UNDEFINED. + * @return Return ERR_OK on success, others on failure. + */ + ErrCode SetImportance(const sptr &bundleOption, const int32_t &importance); + + /** + * @brief Get total badge nums in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param totalBadgeNum Indicates to get badge num. + * @return Return ERR_OK on success, others on failure. + */ + ErrCode GetTotalBadgeNums(const sptr &bundleOption, int32_t &totalBadgeNum); + + /** + * @brief Set total badge nums in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param totalBadgeNum Indicates to set badge num. + * @return Return ERR_OK on success, others on failure. + */ + ErrCode SetTotalBadgeNums(const sptr &bundleOption, const int32_t num); + + /** + * @brief Get private notification allowed in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param allow Indicates to whether to allow. + * @return Return ERR_OK on success, others on failure. + */ ErrCode GetPrivateNotificationsAllowed(const sptr &bundleOption, bool &allow); + + /** + * @brief Set private notification allowed in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param allow Indicates to set allow. + * @return Return ERR_OK on success, others on failure. + */ ErrCode SetPrivateNotificationsAllowed(const sptr &bundleOption, const bool allow); + + /** + * @brief Get private notification enable in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param enabled Indicates to whether to enable. + * @return Return ERR_OK on success, others on failure. + */ ErrCode GetNotificationsEnabledForBundle(const sptr &bundleOption, bool &enabled); + + /** + * @brief Set private notification enable in the of bunlde from DB. + * + * @param bundleOption Indicates bunlde info label. + * @param enabled Indicates to set enable. + * @return Return ERR_OK on success, others on failure. + */ ErrCode SetNotificationsEnabledForBundle(const sptr &bundleOption, const bool enabled); + + /** + * @brief Get notification enable from DB. + * + * @param userId Indicates user. + * @param enabled Indicates to whether to enable. + * @return Return ERR_OK on success, others on failure. + */ ErrCode GetNotificationsEnabled(const int32_t &userId, bool &enabled); + + /** + * @brief Set notification enable from DB. + * + * @param userId Indicates user. + * @param enabled Indicates to set enable. + * @return Return ERR_OK on success, others on failure. + */ ErrCode SetNotificationsEnabled(const int32_t &userId, const bool &enabled); ErrCode GetHasPoppedDialog(const sptr &bundleOption, bool &hasPopped); ErrCode SetHasPoppedDialog(const sptr &bundleOption, bool hasPopped); + + /** + * @brief Get do not disturb date from DB. + * + * @param userId Indicates user. + * @param date Indicates to get do not disturb date. + * @return Return ERR_OK on success, others on failure. + */ ErrCode GetDoNotDisturbDate(const int32_t &userId, sptr &date); + + /** + * @brief Set do not disturb date from DB. + * + * @param userId Indicates user. + * @param date Indicates to set do not disturb date. + * @return Return ERR_OK on success, others on failure. + */ ErrCode SetDoNotDisturbDate(const int32_t &userId, const sptr date); - ErrCode GetTemplateSupported(const std::string& templateName, bool &support); + ErrCode GetTemplateSupported(const std::string &templateName, bool &support); + /** + * @brief Remove all proferences info from DB. + * + * @return Return ERR_OK on success, others on failure. + */ ErrCode ClearNotificationInRestoreFactorySettings(); + /** + * @brief Death recipient. + */ void OnDistributedKvStoreDeathRecipient(); void InitSettingFromDisturbDB(); void RemoveSettings(int32_t userId); @@ -101,6 +346,7 @@ private: ErrCode GetBundleProperty( const sptr &bundleOption, const BundleType &type, T &value) const; std::string GenerateBundleKey(const sptr &bundleOption) const; + bool CheckApiCompatibility(const sptr &bundleOption) const; private: NotificationPreferencesInfo preferencesInfo_ {}; diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 5382772b0e7170052df6a54b345f30d4b99f45c4..b570b6ddcd21e0befe66ee834af8f3e922716a01 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -28,30 +28,157 @@ class NotificationPreferencesDatabase final { public: NotificationPreferencesDatabase(); ~NotificationPreferencesDatabase(); + + /** + * @brief Put notification slots into disturbe DB. + * + * @param bundleName Indicates bunlde name. + * @param bundleUid Indicates bunlde uid. + * @param slots Indicates notification slots. + * @return Return true on success, false on failure. + */ bool PutSlotsToDisturbeDB( - const std::string &bundleName, const int &bundleUid, const std::vector> &slots); - bool PutGroupsToDisturbeDB( - const std::string &bundleName, const int &bundleUid, const std::vector> &groups); + const std::string &bundleName, const int32_t &bundleUid, const std::vector> &slots); + + /** + * @brief Put notification slot groups into disturbe DB. + * + * @param bundleName Indicates bunlde name. + * @param bundleUid Indicates bunlde uid. + * @param groups Indicates notification groups. + * @return Return true on success, false on failure. + */ + bool PutGroupsToDisturbeDB(const std::string &bundleName, const int32_t &bundleUid, + const std::vector> &groups); + + /** + * @brief Put notification bundle into disturbe DB. + * + * @param bundleInfo Indicates bunlde info. + * @return Return true on success, false on failure. + */ bool PutBundlePropertyToDisturbeDB(const NotificationPreferencesInfo::BundleInfo &bundleInfo); + /** + * @brief Put show badge in the of bundle into disturbe DB. + * + * @param bundleInfo Indicates bunlde info. + * @param enable Indicates to whether show badge. + * @return Return true on success, false on failure. + */ bool PutShowBadge(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enable); - bool PutImportance(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int &importance); - bool PutTotalBadgeNums(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int &totalBadgeNum); + + /** + * @brief Put importance in the of bundle into disturbe DB. + * + * @param bundleInfo Indicates bunlde info. + * @param importance Indicates to importance level which can be LEVEL_NONE, + LEVEL_MIN, LEVEL_LOW, LEVEL_DEFAULT, LEVEL_HIGH, or LEVEL_UNDEFINED. + * @return Return true on success, false on failure. + */ + bool PutImportance(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int32_t &importance); + + /** + * @brief Put badge total nums in the of bundle into disturbe DB. + * + * @param bundleInfo Indicates bunlde info. + * @param totalBadgeNum Indicates to total badge num. + * @return Return true on success, false on failure. + */ + bool PutTotalBadgeNums(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int32_t &totalBadgeNum); + + /** + * @brief Put private notification allowed in the of bundle into disturbe DB. + * + * @param bundleInfo Indicates bunlde info. + * @param allow Indicates to whether to allow + * @return Return true on success, false on failure. + */ bool PutPrivateNotificationsAllowed(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &allow); + + /** + * @brief Put enable notification in the of bundle into disturbe DB. + * + * @param bundleInfo Indicates bunlde info. + * @param enabled Indicates to whether to enabled + * @return Return true on success, false on failure. + */ bool PutNotificationsEnabledForBundle( const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enabled); + + /** + * @brief Put enable notification into disturbe DB. + * + * @param userId Indicates user. + * @param enabled Indicates to whether to enabled + * @return Return true on success, false on failure. + */ bool PutNotificationsEnabled(const int32_t &userId, const bool &enabled); bool PutHasPoppedDialog(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &hasPopped); + + /** + * @brief Put do not disturbe date into disturbe DB. + * + * @param userId Indicates user. + * @param date Indicates to do not disturbe date. + * @return Return true on success, false on failure. + */ bool PutDoNotDisturbDate(const int32_t &userId, const sptr &date); + /** + * @brief Parse notification info from disturbe DB. + * + * @param info Indicates notification info. + * @return Return true on success, false on failure. + */ bool ParseFromDisturbeDB(NotificationPreferencesInfo &info); + /** + * @brief Delete all data from disturbe DB. + * + * @return Return true on success, false on failure. + */ bool RemoveAllDataFromDisturbeDB(); + + /** + * @brief Delete bundle data from disturbe DB. + * + * @param bundleKey Indicates the bundle key. + * @return Return true on success, false on failure. + */ bool RemoveBundleFromDisturbeDB(const std::string &bundleKey); + + /** + * @brief Delete slot from disturbe DB. + * + * @param bundleKey Indicates to which a bundle. + * @param type Indicates to slot type. + * @return Return true on success, false on failure. + */ bool RemoveSlotFromDisturbeDB(const std::string &bundleKey, const NotificationConstant::SlotType &type); + + /** + * @brief Delete all slots in the of bundle from disturbe DB. + * + * @param bundleKey Indicates to which a bundle. + * @return Return true on success, false on failure. + */ bool RemoveAllSlotsFromDisturbeDB(const std::string &bundleKey); + + /** + * @brief Delete some groups in the of bundle from disturbe DB. + * + * @param bundleKey Indicates to which a bundle. + * @param groupId Indicates to group id in the of bundle. + * @return Return true on success, false on failure. + */ bool RemoveGroupsFromDisturbeDB(const std::string &bundleKey, const std::vector &groupId); + /** + * @brief Deal death recipient. + * + * @return Return true on success, false on failure. + */ bool StoreDeathRecipient(); bool RemoveNotificationEnable(const int32_t userId); @@ -63,7 +190,7 @@ private: void CloseKvStore(); bool CheckKvStore(); - bool CheckBundle(const std::string &bundleName, const int &bundleUid); + bool CheckBundle(const std::string &bundleName, const int32_t &bundleUid); bool PutBundlePropertyValueToDisturbeDB(const NotificationPreferencesInfo::BundleInfo &bundleInfo); template DistributedKv::Status PutBundlePropertyToDisturbeDB( @@ -71,15 +198,15 @@ private: bool PutBundleToDisturbeDB( const std::string &bundleKey, const NotificationPreferencesInfo::BundleInfo &bundleInfo); - void GetValueFromDisturbeDB(const std::string &key, std::function funcion); + void GetValueFromDisturbeDB(const std::string &key, std::function function); void GetValueFromDisturbeDB(const std::string &key, - std::function funcion); + std::function function); bool GetRemoveGroupKeysFromDisturbeDB( const std::string &bundleKey, const std::string &groupId, std::vector &keys); - bool SlotToEntry(const std::string &bundleName, const int &bundleUid, const sptr &slot, + bool SlotToEntry(const std::string &bundleName, const int32_t &bundleUid, const sptr &slot, std::vector &entries); - bool GroupToEntry(const std::string &bundleName, const int &bundleUid, const sptr &group, + bool GroupToEntry(const std::string &bundleName, const int32_t &bundleUid, const sptr &group, std::vector &entries); void GenerateGroupEntry(const std::string &bundleKey, const sptr &group, std::vector &entries) const; @@ -92,7 +219,7 @@ private: std::string SubUniqueIdentifyFromString(const std::string &findString, const std::string &keyStr) const; std::string VectorToString(const std::vector &data) const; void StringToVector(const std::string &str, std::vector &data) const; - int StringToInt(const std::string &str) const; + int32_t StringToInt(const std::string &str) const; int64_t StringToInt64(const std::string &str) const; bool IsSlotKey(const std::string &bundleKey, const std::string &key) const; bool IsGroupKey(const std::string &bundleKey, const std::string &key) const; @@ -139,12 +266,13 @@ private: void ParseSlotSound(sptr &slot, const std::string &value) const; void ParseSlotVibrationSytle(sptr &slot, const std::string &value) const; void ParseSlotEnableBypassDnd(sptr &slot, const std::string &value) const; + void ParseSlotEnabled(sptr &slot, const std::string &value) const; std::string GenerateBundleLablel(const NotificationPreferencesInfo::BundleInfo &bundleInfo) const; - void GetDoNotDisturbType(NotificationPreferencesInfo &info, int userId); - void GetDoNotDisturbBeginDate(NotificationPreferencesInfo &info, int userId); - void GetDoNotDisturbEndDate(NotificationPreferencesInfo &info, int userId); - void GetEnableAllNotification(NotificationPreferencesInfo &info, int userId); + void GetDoNotDisturbType(NotificationPreferencesInfo &info, int32_t userId); + void GetDoNotDisturbBeginDate(NotificationPreferencesInfo &info, int32_t userId); + void GetDoNotDisturbEndDate(NotificationPreferencesInfo &info, int32_t userId); + void GetEnableAllNotification(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 b7af5c22c73b26e01f445e15a39628095c3a95fb..530577a315b07bc6350c41ceecf9c18a5f681385 100644 --- a/services/ans/include/notification_preferences_info.h +++ b/services/ans/include/notification_preferences_info.h @@ -34,44 +34,222 @@ public: public: BundleInfo(); ~BundleInfo(); + /** + * @brief Set bundle name. + * + * @param name Indicates the bundle name. + */ void SetBundleName(const std::string &name); + + /** + * @brief Get bundle name. + * + * @return Return bundle name. + */ std::string GetBundleName() const; - void SetImportance(const int &level); - int GetImportance() const; + + /** + * @brief Set bundle importance. + * + * @param name Indicates the bundle importance. + */ + void SetImportance(const int32_t &level); + + /** + * @brief Get bundle importance. + * + * @return Return importance. + */ + int32_t GetImportance() const; + + /** + * @brief Set bundle Whether to show badge. + * + * @param name Indicates the set bundle Whether to show badge. + */ void SetIsShowBadge(const bool &isShowBadge); + + /** + * @brief Get bundle Whether to show badge. + * + * @return Return true on success, false on failure. + */ bool GetIsShowBadge() const; - void SetBadgeTotalNum(const int &num); - int GetBadgeTotalNum() const; + + /** + * @brief Set bundle total badge num. + * + * @param name Indicates the set bundle total badge num. + */ + void SetBadgeTotalNum(const int32_t &num); + + /** + * @brief Get bundle total badge num. + * + * @return Return badge total num. + */ + int32_t GetBadgeTotalNum() const; + + /** + * @brief Set bundle Whether to private allowed. + * + * @param name Indicates the set Whether to private allowed. + */ void SetIsPrivateAllowed(const bool &isPrivateAllowed); + + /** + * @brief Get bundle Whether to private allowed. + * + * @return Return true on success, false on failure. + */ bool GetIsPrivateAllowed() const; + + /** + * @brief Set bundle enable notification. + * + * @param enable Indicates the set enable notification. + */ void SetEnableNotification(const bool &enable); + + /** + * @brief Set bundle enable notification. + * + * @return Return true on success, false on failure. + */ bool GetEnableNotification() const; + void SetHasPoppedDialog(const bool &hasPopped); bool GetHasPoppedDialog() const; + + /** + * @brief Set bundle slot. + * + * @param slot Indicates the set slot. + */ void SetSlot(const sptr &slot); + + /** + * @brief Get bundle slot by type. + * + * @param type Indicates the slot type. + * @param slot Indicates the slot object. + * @return Return true on success, false on failure. + */ bool GetSlot(const NotificationConstant::SlotType &type, sptr &slot) const; + + /** + * @brief Get slots from bundle. + * + * @param slots Indicates the get slots. + * @return Return true on success, false on failure. + */ bool GetAllSlots(std::vector> &slots); + + /** + * @brief Get slot num from bundle. + * + * @return Return true on success, false on failure. + */ uint32_t GetAllSlotsSize(); + + /** + * @brief Get all slot from group in bundle. + * + * @param groupId Indicates a groupId from bundle. + * @param slots Indicates get slots from group. + * @return Return true on success, false on failure. + */ bool GetAllSlotsInGroup(const std::string &groupId, std::vector> &slots); + + /** + * @brief Get all slot from group in bundle. + * + * @param groupId Indicates a groupId from bundle. + * @param slots Indicates get slots from group. + * @return Return true on success, false on failure. + */ bool GetAllSlotsInGroup(const std::string &groupId, std::vector &slots); + + /** + * @brief Set bundle group. + * + * @param group Indicates the set group. + */ void SetGroup(const sptr &group); + + /** + * @brief Get group from bundle. + * + * @param groupId Indicates the get group id in the of bundle. + * @param group Indicates the get group. + * @return Return true on success, false on failure. + */ bool GetGroup(const std::string &groupId, sptr &group); + + /** + * @brief Get all group from bundle. + * + * @param group Indicates the get groups. + * @return Return true on success, false on failure. + */ bool GetAllGroups(std::vector> &group); - uint32_t GetGroupSize() const; + + /** + * @brief Get slot group num from bundle. + * + * @return Return num is group size. + */ + size_t GetGroupSize() const; + + /** + * @brief Check whether to exsist slot in the of bundle. + * + * @param type Indicates the slot type. + * @return Return true on success, false on failure. + */ bool IsExsitSlot(const NotificationConstant::SlotType &type) const; + + /** + * @brief Check whether to exsist slot group in the of bundle. + * + * @param groupId Indicates the slot group id. + * @return Return true on success, false on failure. + */ bool IsExsitSlotGroup(const std::string &groupId) const; + + /** + * @brief Rremove a slot from bundle. + * + * @param type Indicates the slot type. + * @return Return true on success, false on failure. + */ bool RemoveSlot(const NotificationConstant::SlotType &type); + + /** + * @brief Remove all slots from bundle. + * + * @return Return true on success, false on failure. + */ void RemoveAllSlots(); + + /** + * @brief remove slot group from bundle. + * + * @param groupId Indicates the slot group id. + * @return Return true on success, false on failure. + */ bool RemoveSlotGroup(const std::string &groupId); - void SetBundleUid(const int &uid); - int GetBundleUid() const; + void SetBundleUid(const int32_t &uid); + int32_t GetBundleUid() const; + void SetSlotEnabled(NotificationConstant::SlotType slotType, bool enabled); + bool GetSlotEnabled(NotificationConstant::SlotType slotType, bool &enabled) const; private: std::string bundleName_; - int uid_ = 0; - int importance_ = BUNDLE_IMPORTANCE; + int32_t uid_ = 0; + int32_t importance_ = BUNDLE_IMPORTANCE; bool isShowBadge_ = BUNDLE_SHOW_BADGE; - int badgeTotalNum_ = BUNDLE_BADGE_TOTAL_NUM; + int32_t badgeTotalNum_ = BUNDLE_BADGE_TOTAL_NUM; bool isPrivateAllowed_ = BUNDLE_PRIVATE_ALLOWED; bool isEnabledNotification_ = BUNDLE_ENABLE_NOTIFICATION; bool hasPoppedDialog_ = BUNDLE_POPPED_DIALOG; @@ -79,20 +257,81 @@ public: std::map> groups_; }; + /* + * @brief Constructor used to create an NotificationPreferencesInfo object. + */ NotificationPreferencesInfo() {} + /** + * @brief Default destructor. + */ ~NotificationPreferencesInfo() {} + + /** + * set bundle info into preferences info. + * @param info Indicates the bundle. + */ void SetBundleInfo(const BundleInfo &info); + + /** + * get bundle info from preferences info. + * @param bundleOption Indicates the bundle info label. + * @param info Indicates the bundle info. + * @return Whether to get bundle info success. + */ bool GetBundleInfo(const sptr &bundleOption, BundleInfo &info) const; + + /** + * remove bundle info from preferences info. + * @param bundleOption Indicates the bundle info label. + * @return Whether to remove bundle info success. + */ bool RemoveBundleInfo(const sptr &bundleOption); + + /** + * whether to exsist bundle info in the of preferences info. + * @param bundleOption Indicates the bundle info label. + * @return Whether to exsist bundle info. + */ bool IsExsitBundleInfo(const sptr &bundleOption) const; + + /** + * clear bundle info in the of preferences info. + */ void ClearBundleInfo(); + + /** + * set do not disturb date into preferences info. + * @param userId Indicates userId. + * @param doNotDisturbDate Indicates do not disturb date. + * @return Whether to set do not disturb success. + */ void SetDoNotDisturbDate(const int32_t &userId, const sptr &doNotDisturbDate); + + /** + * get do not disturb date from preferences info. + * @param userId Indicates userId. + * @param doNotDisturbDate Indicates do not disturb date. + * @return Whether to get do not disturb success. + */ bool GetDoNotDisturbDate(const int32_t &userId, sptr &doNotDisturbDate) const; + + /** + * set enable all notification into preferences info. + * @param userId Indicates userId. + * @param enable Indicates whether to enable all notification. + */ void SetEnabledAllNotification(const int32_t &userId, const bool &enable); + + /** + * get enable all notification from preferences info. + * @param userId Indicates userId. + * @param enable Indicates whether to enable all notification. + * @return Whether to enable all notification success. + */ bool GetEnabledAllNotification(const int32_t &userId, bool &enable) const; void RemoveNotificationEnable(const int32_t userId); void RemoveDoNotDisturbDate(const int32_t userId); diff --git a/services/ans/include/notification_slot_filter.h b/services/ans/include/notification_slot_filter.h index 3b8978c2c581b2bf23b61f427beab1087c4aebd9..3fa6d544d6e737edd50478583d0279c1ad156d33 100644 --- a/services/ans/include/notification_slot_filter.h +++ b/services/ans/include/notification_slot_filter.h @@ -25,9 +25,22 @@ public: NotificationSlotFilter() {}; ~NotificationSlotFilter() {}; + /** + * @brief Start the filter. Inherited from INotificationFilter. + */ void OnStart() override; + + /** + * @brief Stop the filter. Inherited from INotificationFilter. + */ void OnStop() override; + /** + * @brief Filters the publish operation. Inherited from INotificationFilter. + * + * @param record Indicates the NotificationRecord. + * @return Returns the filter result. + */ ErrCode OnPublish(const std::shared_ptr &record) override; }; } // namespace Notification diff --git a/services/ans/include/notification_subscriber_manager.h b/services/ans/include/notification_subscriber_manager.h index 2bf73706e65db4d6ca52d2241abefd91c5f82379..004f5268e8293ff3a43e77682b2b9fd19de9f9ec 100644 --- a/services/ans/include/notification_subscriber_manager.h +++ b/services/ans/include/notification_subscriber_manager.h @@ -38,16 +38,64 @@ namespace OHOS { namespace Notification { class NotificationSubscriberManager : public DelayedSingleton { public: + /** + * @brief Add a subscriber. + * + * @param subscriber Indicates the IAnsSubscriber object. + * @param subscribeInfo Indicates the NotificationSubscribeInfo object. + * @return Indicates the result code. + */ ErrCode AddSubscriber(const sptr &subscriber, const sptr &subscribeInfo); + + /** + * @brief Remove a subscriber. + * + * @param subscriber Indicates the IAnsSubscriber object. + * @param subscribeInfo Indicates the NotificationSubscribeInfo object. + * @return Indicates the result code. + */ ErrCode RemoveSubscriber( const sptr &subscriber, const sptr &subscribeInfo); + /** + * @brief Notify all subscribers on counsumed. + * + * @param notification Indicates the Notification object. + * @param notificationMap Indicates the NotificationSortingMap object. + */ void NotifyConsumed(const sptr ¬ification, const sptr ¬ificationMap); - void NotifyCanceled( - const sptr ¬ification, const sptr ¬ificationMap, int deleteReason); + + /** + * @brief Notify all subscribers on canceled. + * + * @param notification Indicates the Notification object. + * @param notificationMap Indicates the NotificationSortingMap object. + * @param deleteReason Indicates the delete reason. + */ + void NotifyCanceled(const sptr ¬ification, + const sptr ¬ificationMap, int32_t deleteReason); + + /** + * @brief Notify all subscribers on updated. + * + * @param notificationMap Indicates the NotificationSortingMap object. + */ void NotifyUpdated(const sptr ¬ificationMap); + + /** + * @brief Notify all subscribers on dnd date changed. + * + * @param date Indicates the NotificationDoNotDisturbDate object. + */ void NotifyDoNotDisturbDateChanged(const sptr &date); + void NotifyEnabledNotificationChanged(const sptr &callbackData); + + /** + * @brief Obtains the death event. + * + * @param object Indicates the death object. + */ void OnRemoteDied(const wptr &object); private: @@ -67,8 +115,8 @@ private: void NotifyConsumedInner( const sptr ¬ification, const sptr ¬ificationMap); - void NotifyCanceledInner( - const sptr ¬ification, const sptr ¬ificationMap, int deleteReason); + void NotifyCanceledInner(const sptr ¬ification, + const sptr ¬ificationMap, int32_t deleteReason); void NotifyUpdatedInner(const sptr ¬ificationMap); void NotifyDoNotDisturbDateChangedInner(const sptr &date); void NotifyEnabledNotificationChangedInner(const sptr &callbackData); diff --git a/services/ans/include/permission_filter.h b/services/ans/include/permission_filter.h index f0610279d9ec938eeea5cd8f70484eb3b922af14..b14536da889fc09a36895e1dcd326c4ea666983b 100644 --- a/services/ans/include/permission_filter.h +++ b/services/ans/include/permission_filter.h @@ -25,9 +25,22 @@ public: PermissionFilter() {}; ~PermissionFilter() {}; + /** + * @brief Start the filter. Inherited from INotificationFilter. + */ void OnStart() override; + + /** + * @brief Stop the filter. Inherited from INotificationFilter. + */ void OnStop() override; + /** + * @brief Filters the publish operation. Inherited from INotificationFilter. + * + * @param record Indicates the NotificationRecord. + * @return Returns the filter result. + */ ErrCode OnPublish(const std::shared_ptr &record) override; }; } // namespace Notification diff --git a/services/ans/include/preferences_constant.h b/services/ans/include/preferences_constant.h index e2538daf3b3411e05a278276f3f177933c530bf1..f8546b2a802d591ed1dd1d5bd15617481f37b225 100644 --- a/services/ans/include/preferences_constant.h +++ b/services/ans/include/preferences_constant.h @@ -18,56 +18,225 @@ namespace OHOS { namespace Notification { +/** + * Indicates that disturbe key which do not disturbe type. + */ const static std::string KEY_DO_NOT_DISTURB_TYPE = "ans_doNotDisturbType"; + +/** + * Indicates that disturbe key which do not disturbe begin date. + */ const static std::string KEY_DO_NOT_DISTURB_BEGIN_DATE = "ans_doNotDisturbBeginDate"; + +/** + * Indicates that disturbe key which do not disturbe end date. + */ const static std::string KEY_DO_NOT_DISTURB_END_DATE = "ans_doNotDisturbEndDate"; + +/** + * Indicates that disturbe key which enable all notification. + */ const static std::string KEY_ENABLE_ALL_NOTIFICATION = "ans_notificationAll"; + +/** + * Indicates that disturbe key which bundle label. + */ const static std::string KEY_BUNDLE_LABEL = "label_ans_bundle_"; + +/** + * Indicates that disturbe key which under line. + */ const static std::string KEY_UNDER_LINE = "_"; + +/** + * Indicates that disturbe key which bundle begin key. + */ const static std::string KEY_ANS_BUNDLE = "ans_bundle"; +/** + * Indicates that disturbe key which bundle name. + */ const static std::string KEY_BUNDLE_NAME = "name"; + +/** + * Indicates that disturbe key which bundle imortance. + */ const static std::string KEY_BUNDLE_IMPORTANCE = "importance"; + +/** + * Indicates that disturbe key which bundle show badge. + */ const static std::string KEY_BUNDLE_SHOW_BADGE = "showBadge"; + +/** + * Indicates that disturbe key which bundle total badge num. + */ const static std::string KEY_BUNDLE_BADGE_TOTAL_NUM = "badgeTotalNum"; + +/** + * Indicates that disturbe key which bundle private allowed. + */ const static std::string KEY_BUNDLE_PRIVATE_ALLOWED = "privateAllowed"; + +/** + * Indicates that disturbe key which bundle enable notification. + */ const static std::string KEY_BUNDLE_ENABLE_NOTIFICATION = "enabledNotification"; + +/** + * Indicates that disturbe key which bundle popped dialog. + */ const static std::string KEY_BUNDLE_POPPED_DIALOG = "poppedDialog"; + +/** + * Indicates that disturbe key which bundle uid. + */ const static std::string KEY_BUNDLE_UID = "uid"; +/** + * Indicates that disturbe key which group. + */ const static std::string KEY_GROUP = "group"; + +/** + * Indicates that disturbe key which group id. + */ const static std::string KEY_GROUP_ID = "id"; + +/** + * Indicates that disturbe key which group name. + */ const static std::string KEY_GROUP_NAME = "name"; + +/** + * Indicates that disturbe key which group description. + */ const static std::string KEY_GROUP_DESCRIPTION = "groupDescription"; + +/** + * Indicates that disturbe key which group is disable. + */ const static std::string KEY_GROUP_DISABLE = "isDisable"; +/** + * Indicates that disturbe key which slot. + */ const static std::string KEY_SLOT = "slot"; + +/** + * Indicates that disturbe key which slot type. + */ const static std::string KEY_SLOT_TYPE = "type"; + +/** + * Indicates that disturbe key which slot id. + */ const static std::string KEY_SLOT_ID = "id"; + +/** + * Indicates that disturbe key which slot group id. + */ const static std::string KEY_SLOT_GROUPID = "groupId"; + +/** + * Indicates that disturbe key which slot group name. + */ const static std::string KEY_SLOT_NAME = "name"; + +/** + * Indicates that disturbe key which slot description. + */ const static std::string KEY_SLOT_DESCRIPTION = "description"; + +/** + * Indicates that disturbe key which slot level. + */ const static std::string KEY_SLOT_LEVEL = "level"; + +/** + * Indicates that disturbe key which slot show badge. + */ const static std::string KEY_SLOT_SHOW_BADGE = "showBadge"; + +/** + * Indicates that disturbe key which slot enable light. + */ const static std::string KEY_SLOT_ENABLE_LIGHT = "enableLight"; + +/** + * Indicates that disturbe key which slot enable vibration. + */ const static std::string KEY_SLOT_ENABLE_VRBRATION = "enableVibration"; + +/** + * Indicates that disturbe key which slot led light color. + */ const static std::string KEY_SLOT_LED_LIGHT_COLOR = "ledLightColor"; + +/** + * Indicates that disturbe key which slot lockscreen visibleness. + */ const static std::string KEY_SLOT_LOCKSCREEN_VISIBLENESS = "lockscreenVisibleness"; + +/** + * Indicates that disturbe key which slot sound. + */ const static std::string KEY_SLOT_SOUND = "sound"; + +/** + * Indicates that disturbe key which slot vibration style. + */ const static std::string KEY_SLOT_VIBRATION_STYLE = "vibrationSytle"; + +/** + * Indicates that disturbe key which slot enable bypass end. + */ const static std::string KEY_SLOT_ENABLE_BYPASS_DND = "enableBypassDnd"; -// distributed database +/** + * Indicates whether the type of slot is enabled. + */ +const static std::string KEY_SLOT_ENABLED = "enabled"; + +/** + * Indicates distributed database app id. + */ const std::string APP_ID = "advanced_notification_service"; + +/** + * Indicates distributed database store id. + */ const std::string STORE_ID = "local_db"; +/** + * Default params that bundle importance is LEVEL_DEFAULT. + */ const static int BUNDLE_IMPORTANCE = 3; + +/** + * Default params that bundle badge total num is zero. + */ const static int BUNDLE_BADGE_TOTAL_NUM = 0; + +/** + * Default params that bundle private allowed is false. + */ const static int BUNDLE_PRIVATE_ALLOWED = false; + +/** + * Default params that bundle enable notification is true. + */ const static int BUNDLE_ENABLE_NOTIFICATION = true; const static int BUNDLE_POPPED_DIALOG = false; + +/** + * Default params that bundle show badge is false. + */ const static bool BUNDLE_SHOW_BADGE = false; +/** + * Indicates bundle type which used to DB store. + */ enum class BundleType { BUNDLE_NAME_TYPE = 1, BUNDLE_IMPORTANCE_TYPE, diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index b1d22285a35a000f2fea65ea06991d547efeb1d0..e9a727ecde015174b685668f20eebb782b313885 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -22,13 +22,17 @@ #include "advanced_notification_service.h" #include "player.h" #include "reminder_request.h" +#include "reminder_store.h" #include "reminder_timer_info.h" namespace OHOS { namespace Notification { class ReminderDataManager final { public: - ReminderDataManager() {}; + ReminderDataManager() + { + Init(false); + }; ~ReminderDataManager() {}; ReminderDataManager(ReminderDataManager &other) = delete; @@ -37,10 +41,10 @@ public: /** * @brief Cancels all the reminders relative to the bundle option. * - * @param bundleOption Indicates the bundle option. + * @param packageName Indicates the package name. * @param userId Indicates the user id which the bundle belong to. */ - void CancelAllReminders(const sptr &bundleOption, int userId); + void CancelAllReminders(const std::string &packageName, const int32_t &userId); /** * @brief Cancels the target reminder relative to the reminder id and bundle option. @@ -72,6 +76,8 @@ public: * @return Single instance of ReminderDataManager. */ static std::shared_ptr GetInstance(); + static std::shared_ptr InitInstance( + const sptr &advancedNotificationService); /** * Obtains all the valid reminders (which are not expired) relative to the bundle option. @@ -80,14 +86,29 @@ public: * @param[out] reminders return the valid reminders. */ void GetValidReminders( - const sptr bundleOption, std::vector> &reminders); + const sptr &bundleOption, std::vector> &reminders); + + /** + * @brief Inits and recovery data from database. + * + * @param isFromBootComplete Indicates the init is called when boot completed. + */ + void Init(bool isFromBootComplete); + + void InitUserId(); + + void OnUserRemove(const int32_t& userId); + + void OnServiceStart(); + + void OnUserSwitch(const int32_t& userId); /** * @brief Triggered when third party application died. * * @param bundleOption Indicates the bundleOption of third party application. */ - void OnProcessDiedLocked(const sptr bundleOption); + void OnProcessDiedLocked(const sptr &bundleOption); /** * Publishs a scheduled reminder. @@ -95,7 +116,7 @@ public: * @param reminder Indicates the reminder. * @param bundleOption Indicates bundle option the reminder belongs to. */ - void PublishReminder(sptr &reminder, sptr &bundleOption); + void PublishReminder(const sptr &reminder, const sptr &bundleOption); /** * @brief Refresh all reminders when date/time or timeZone of device changed by user. @@ -111,12 +132,15 @@ public: */ void SetService(AdvancedNotificationService *advancedNotificationService); + bool ShouldAlert(const sptr &reminder) const; + /** * @brief Show the reminder. * * @param isSysTimeChanged Indicates it is triggered as dateTime changed by user or not. + * @param want Which contains the given reminder. */ - void ShowActiveReminder(); + void ShowActiveReminder(const EventFwk::Want &want); /** * @brief Snooze the reminder by manual. @@ -129,6 +153,11 @@ public: */ void SnoozeReminder(const OHOS::EventFwk::Want &want); + /** + * Starts the recent reminder timing. + */ + void StartRecentReminder(); + /** * @brief Terminate the alerting reminder. * @@ -164,6 +193,16 @@ private: */ void AddToShowedReminders(const sptr &reminder); + void CancelAllReminders(const int32_t &userId); + + /** + * @brief Cancels all the reminders of the target bundle or user. + * + * @param packageName Indicates the packageName need to cancel. + * @param userId Indicates the userId to cancel. + */ + void CancelRemindersImplLocked(const std::string &packageName, const int32_t &userId); + /** * Cancels the notification relative to the reminder. * @@ -177,7 +216,7 @@ private: * @param bundleName Indicates the target bundle. * @return true if number limit is exceeded. */ - bool CheckReminderLimitExceededLocked(const std::string &bundleName) const; + bool CheckReminderLimitExceededLocked(const sptr &bundleOption) const; void CloseReminder(const sptr &reminder, bool cancelNotification); /** @@ -188,6 +227,8 @@ private: */ std::shared_ptr CreateTimerInfo(TimerType type) const; + void GetImmediatelyShowRemindersLocked(std::vector> &reminders) const; + std::string GetSoundUri(const sptr &reminder); /** @@ -225,14 +266,6 @@ private: */ sptr GetRecentReminderLocked(); - /** - * Obtains all the reminders of the target bundle name. - * - * @param bundleName Indicates the bundle name. - * @return all the reminders of the target bundle name. - */ - std::vector> GetSameBundleRemindersLocked(std::string &bundleName); - void HandleImmediatelyShow(std::vector> &showImmediately, bool isSysTimeChanged); /** @@ -242,7 +275,7 @@ private: * @param reminder Indicates the target reminder. * @return sptr Returns the target reminder if it is need to show immediately, otherwise nullptr. */ - sptr HandleRefreshReminder(uint8_t &type, sptr &reminder); + sptr HandleRefreshReminder(const uint8_t &type, sptr &reminder); /** * @brief Handles all the reminders that have the same notification id and belong to same application @@ -255,15 +288,30 @@ private: bool HandleSysTimeChange(const sptr reminder) const; /** - * Judge the two reminders is belong to the same application or not. + * @brief Judge the two reminders is belong to the same application or not. * - * @param reminder Indicates the first reminder. - * @param otherPkgName Indicates the package name of second reminder. - * @param otherUserId Indicates the user id of second reminder. + * @param bundleOption Indicates the bundleOption of first reminder. + * @param other Indicates the bundleOption of second reminder. * @return true if the two reminders belong to the same application. */ - bool IsBelongToSameApp( - const sptr reminder, const std::string otherPkgName, const int otherUserId); + bool IsBelongToSameApp(const sptr &bundleOption, + const sptr &other) const; + + /** + * @brief Judges whether the reminder is matched with the bundleOption or userId. + * + * @param reminder Indicates the target reminder. + * @param packageName Indicates the package name. + * @param userId Indicates the user id. + * @return true If the reminder is matched with the bundleOption or userId. + */ + bool IsMatched(const sptr &reminder, const std::string &packageName, const int32_t &userId) const; + + bool IsAllowedNotify(const sptr &reminder) const; + + bool IsReminderAgentReady() const; + + void LoadReminderFromDb(); void PlaySoundAndVibrationLocked(const sptr &reminder); void PlaySoundAndVibration(const sptr &reminder); @@ -321,11 +369,6 @@ private: void SnoozeReminderImpl(sptr &reminder); - /** - * Starts the recent reminder timing. - */ - void StartRecentReminder(); - /** * Starts timing actually. * @@ -386,7 +429,7 @@ private: static std::shared_ptr REMINDER_DATA_MANAGER; /** - * Used for multi-thread syncronise. + * Used for multi-thread synchronise. */ static std::mutex MUTEX; static std::mutex SHOW_MUTEX; @@ -403,6 +446,8 @@ private: */ static const int16_t MAX_NUM_REMINDER_LIMIT_APP; + bool isReminderAgentReady_ = false; + /** * Vector used to record all the reminders in system. */ @@ -446,7 +491,9 @@ private: * Indicates the total count of reminders in system. */ int16_t totalCount_ {0}; - AdvancedNotificationService *advancedNotificationService_; + int currentUserId_ {0}; + sptr advancedNotificationService_ = nullptr; + std::shared_ptr store_ = nullptr; }; } // namespace OHOS } // namespace Nofitifcation diff --git a/services/ans/include/reminder_event_manager.h b/services/ans/include/reminder_event_manager.h index 35f46ba0ec2d26137aba6d19eed2ae3078bdbd8e..09c731643bb18daba6a555759302e84d448bdae6 100644 --- a/services/ans/include/reminder_event_manager.h +++ b/services/ans/include/reminder_event_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -18,6 +18,7 @@ #include "common_event_subscriber.h" #include "reminder_data_manager.h" +#include "system_ability_status_change_stub.h" #include @@ -25,7 +26,7 @@ namespace OHOS { namespace Notification { class ReminderEventManager { public: - ReminderEventManager(std::shared_ptr &reminderDataManager); + explicit ReminderEventManager(std::shared_ptr &reminderDataManager); virtual ~ReminderEventManager() {}; ReminderEventManager(ReminderEventManager &other) = delete; ReminderEventManager& operator = (const ReminderEventManager &other) = delete; @@ -41,8 +42,18 @@ public: private: sptr GetBundleOption(const OHOS::EventFwk::Want &want) const; - void HandlePackageRemove(OHOS::EventFwk::Want &want) const; - void HandleProcessDied(OHOS::EventFwk::Want &want) const; + void HandlePackageRemove(const EventFwk::Want &want) const; + void HandleProcessDied(const EventFwk::Want &want) const; + std::shared_ptr reminderDataManager_ = nullptr; +}; + +class SystemAbilityStatusChangeListener : public OHOS::SystemAbilityStatusChangeStub { +public: + explicit SystemAbilityStatusChangeListener(std::shared_ptr &reminderDataManager); + ~SystemAbilityStatusChangeListener() {}; + virtual void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + virtual void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; +private: std::shared_ptr reminderDataManager_ = nullptr; }; }; diff --git a/services/ans/include/reminder_timer_info.h b/services/ans/include/reminder_timer_info.h index b3e66b42d7087a5a2de9f6f4795030750cf5b57b..ca8f575730651a04d01e73b6768ca0d3e66edde5 100644 --- a/services/ans/include/reminder_timer_info.h +++ b/services/ans/include/reminder_timer_info.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -44,7 +44,7 @@ public: /** * Indicates the timing type. */ - void SetType(const int &type) override; + void SetType(const int32_t &type) override; /** * Indicates the repeat policy. diff --git a/services/ans/include/remote_death_recipient.h b/services/ans/include/remote_death_recipient.h index ea52d41e60ef0fbeaf0378b823a560d83e72d654..6c876bc6cc1c95b458a43f3ea495b8b4a60b1856 100644 --- a/services/ans/include/remote_death_recipient.h +++ b/services/ans/include/remote_death_recipient.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -24,16 +24,27 @@ namespace OHOS { namespace Notification { class RemoteDeathRecipient : public IRemoteObject::DeathRecipient { public: - RemoteDeathRecipient(std::function &)> callback) + /** + * The constructor. + * @param callback Indicates the callback. + */ + explicit RemoteDeathRecipient(std::function &)> callback) { callback_ = callback; } + + /** + * The deconstructor. + */ ~RemoteDeathRecipient() { callback_ = nullptr; } - // IRemoteObject::DeathRecipient + /** + * Obtains the death event. Inherited from IRemoteObject::DeathRecipient. + * @param object Indicates the death object. + */ void OnRemoteDied(const wptr &object) { if (callback_ != nullptr) { diff --git a/services/ans/include/system_event_observer.h b/services/ans/include/system_event_observer.h index 382959c4f802efe02da74dfd433497a4131c8777..85629c59ce4ffb6f06ac0db8bdeaebd2506b9d3b 100644 --- a/services/ans/include/system_event_observer.h +++ b/services/ans/include/system_event_observer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -28,11 +28,21 @@ namespace OHOS { namespace Notification { class SystemEventObserver { public: - SystemEventObserver(const ISystemEvent &callbacks); + /** + * @brief The constructor. + * + * @param callbacks Indicates the ISystemEvent object. + */ + explicit SystemEventObserver(const ISystemEvent &callbacks); + + /** + * @brief The deconstructor. + */ ~SystemEventObserver(); private: void OnReceiveEvent(const EventFwk::CommonEventData &data); + sptr GetBundleOption(AAFwk::Want want); private: std::shared_ptr subscriber_ = nullptr; diff --git a/services/ans/include/system_event_subscriber.h b/services/ans/include/system_event_subscriber.h index 593f92b8bb6c7386a0f06251a78ee3627f4778f9..a1adbeb31c9906fb61813670b3eb5dcedcef31b5 100644 --- a/services/ans/include/system_event_subscriber.h +++ b/services/ans/include/system_event_subscriber.h @@ -24,14 +24,28 @@ namespace OHOS { namespace Notification { class SystemEventSubscriber : public EventFwk::CommonEventSubscriber { public: + /** + * @brief The constructor. + * + * @param subscribeInfo Indicates the EventFwk::CommonEventSubscribeInfo object. + * @param callback Indicates the callback. + */ SystemEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, const std::function &callback) : EventFwk::CommonEventSubscriber(subscribeInfo), callback_(callback) {} + /** + * @brief The deconstructor. + */ ~SystemEventSubscriber() {} + /** + * @brief Obtains the death event. Inherited from EventFwk::CommonEventSubscriber. + * + * @param data Indicates the EventFwk::CommonEventData object. + */ void OnReceiveEvent(const EventFwk::CommonEventData &data) override { if (callback_ != nullptr) { diff --git a/services/ans/resource/downloadTemplate.abc b/services/ans/resource/downloadTemplate.abc new file mode 100644 index 0000000000000000000000000000000000000000..4bee22f50ceb0cca9eb1b6c188d438bd5680640b Binary files /dev/null and b/services/ans/resource/downloadTemplate.abc differ diff --git a/services/ans/resource/downloadTemplate.js b/services/ans/resource/downloadTemplate.js new file mode 100644 index 0000000000000000000000000000000000000000..fe795e0e6f9cd0e15377c71f240f7cfe232c5e07 --- /dev/null +++ b/services/ans/resource/downloadTemplate.js @@ -0,0 +1,2 @@ +(()=>{"use strict";var e={};(()=>{var t=e;Object.defineProperty(t,"__esModule",{value:!0});const o="Template-DownloadTemplate";class i extends View{constructor(e,t,o){super(e,t),this.icon=null,this.__title=new ObservedPropertySimple("",this,"title"),this.__detailedInfo=new ObservedPropertySimple("",this,"detailedInfo"),this.__passTime=new ObservedPropertySimple(0,this,"passTime"),this.__fileName=new ObservedPropertySimple("",this,"fileName"),this.__progressValue=new ObservedPropertySimple(40,this,"progressValue"),this.__isShowDetailedInfo=new ObservedPropertySimple(!1,this,"isShowDetailedInfo"),this.updateWithValueParams(o)}updateWithValueParams(e){void 0!==e.icon&&(this.icon=e.icon),void 0!==e.title&&(this.title=e.title),void 0!==e.detailedInfo&&(this.detailedInfo=e.detailedInfo),void 0!==e.passTime&&(this.passTime=e.passTime),void 0!==e.fileName&&(this.fileName=e.fileName),void 0!==e.progressValue&&(this.progressValue=e.progressValue),void 0!==e.isShowDetailedInfo&&(this.isShowDetailedInfo=e.isShowDetailedInfo)}aboutToBeDeleted(){this.__title.aboutToBeDeleted(),this.__detailedInfo.aboutToBeDeleted(),this.__passTime.aboutToBeDeleted(),this.__fileName.aboutToBeDeleted(),this.__progressValue.aboutToBeDeleted(),this.__isShowDetailedInfo.aboutToBeDeleted(),SubscriberManager.Get().delete(this.id())}get title(){return this.__title.get()}set title(e){this.__title.set(e)}get detailedInfo(){return this.__detailedInfo.get()}set detailedInfo(e){this.__detailedInfo.set(e)}get passTime(){return this.__passTime.get()}set passTime(e){this.__passTime.set(e)}get fileName(){return this.__fileName.get()}set fileName(e){this.__fileName.set(e)}get progressValue(){return this.__progressValue.get()}set progressValue(e){this.__progressValue.set(e)}get isShowDetailedInfo(){return this.__isShowDetailedInfo.get()}set isShowDetailedInfo(e){this.__isShowDetailedInfo.set(e)}aboutToAppear(){console.log(`${o} ------\x3e aboutToAppear, icon: ${JSON.stringify(this.icon)}`),console.log(`${o} ------\x3e aboutToAppear, title: ${this.title}`),console.log(`${o} ------\x3e aboutToAppear, detailedInfo: ${this.detailedInfo}`),console.log(`${o} ------\x3e aboutToAppear, passTime: ${this.passTime}`),console.log(`${o} ------\x3e aboutToAppear, fileName: ${this.fileName}`),console.log(`${o} ------\x3e aboutToAppear, progressValue: ${this.progressValue}`)}render(){Flex.create({direction:FlexDirection.Column,alignItems:ItemAlign.Center,justifyContent:FlexAlign.Start}),Flex.width("100%"),Flex.margin({top:12,bottom:12}),Flex.border({width:1,color:Color.White,radius:30}),Flex.backgroundColor(Color.White),Column.create({space:10}),Column.alignItems(HorizontalAlign.Center),Column.width("100%"),Row.create({space:10}),Row.alignItems(VerticalAlign.Center),Row.align(Alignment.Start),Row.margin({bottom:12}),Row.width("100%"),If.create(),this.icon&&(If.branchId(0),Image.create(this.icon),Image.objectFit(ImageFit.Contain),Image.width(16),Image.height(16)),If.pop(),Text.create(this.title),Text.fontColor("#182431"),Text.fontSize("12"),Text.fontWeight(FontWeight.Regular),Text.align(Alignment.Start),Text.pop(),Text.create("已完成:"),Text.fontColor("#182431"),Text.fontSize("12"),Text.fontWeight(FontWeight.Regular),Text.pop(),Text.create(`${this.progressValue}%`),Text.fontColor("#182431"),Text.fontSize("12"),Text.fontWeight(FontWeight.Regular),Text.pop(),Text.create(`${this.passTime}分钟前`),Text.fontColor("#182431"),Text.fontSize("12"),Text.fontWeight(FontWeight.Regular),Text.pop(),Row.pop(),Flex.create({justifyContent:FlexAlign.SpaceBetween}),Flex.width("100%"),Row.create({space:5}),Row.flexShrink(0),Row.alignItems(VerticalAlign.Center),Row.align(Alignment.Start),Text.create("标题:正在接收"),Text.fontColor("#182431"),Text.fontSize("14"),Text.pop(),Text.create(this.fileName),Text.fontColor("#182431"),Text.fontSize("14"),Text.pop(),Row.pop(),Row.create(),Row.alignItems(VerticalAlign.Center),Row.align(Alignment.End),Row.onClick((()=>this.isShowDetailedInfo=!this.isShowDetailedInfo)),Text.create("文件详情"),Text.fontColor("#182431"),Text.fontSize("14"),Text.fontWeight(FontWeight.Regular),Text.pop(),Row.pop(),Flex.pop(),If.create(),this.isShowDetailedInfo&&(If.branchId(0),Row.create(),Row.alignItems(VerticalAlign.Center),Row.align(Alignment.Start),Row.width("100%"),Text.create(this.detailedInfo),Text.maxLines(3),Text.textOverflow({overflow:TextOverflow.Ellipsis}),Text.fontColor("#182431"),Text.fontSize("14"),Text.pop(),Row.pop()),If.pop(),Column.create(),Column.alignItems(HorizontalAlign.Start),Column.width("100%"),Progress.create({value:this.progressValue,total:100,style:ProgressStyle.Linear}),Progress.color(Color.Blue),Progress.value(this.progressValue),Progress.width("100%"),Column.pop(),Column.pop(),Flex.pop()}}t.default=i,loadDocument(new i("1",void 0,{}))})()})(); +//# sourceMappingURL=../_releaseMap/pages/downloadTemplate.js.map \ No newline at end of file diff --git a/services/ans/resource/external.json b/services/ans/resource/external.json new file mode 100755 index 0000000000000000000000000000000000000000..7eb2533f4e88864def8271afa25c0e5c69f45c0f --- /dev/null +++ b/services/ans/resource/external.json @@ -0,0 +1,3 @@ +{ + "downloadTemplate": "/system/etc/notification_template/assets/js/downloadTemplate.js" +} \ No newline at end of file diff --git a/services/ans/src/access_token_helper.cpp b/services/ans/src/access_token_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b49617be6ad571b0c72cdd76099d51e8121767e2 --- /dev/null +++ b/services/ans/src/access_token_helper.cpp @@ -0,0 +1,34 @@ +/* + * 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. + */ + +#include "access_token_helper.h" + +namespace OHOS { +namespace Notification { +bool AccessTokenHelper::VerifyCallerPermission( + const Security::AccessToken::AccessTokenID &tokenCaller, const std::string &permission) +{ + int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission); + return (result == Security::AccessToken::PERMISSION_GRANTED); +} + +bool AccessTokenHelper::VerifyNativeToken(const Security::AccessToken::AccessTokenID &callerToken) +{ + Security::AccessToken::ATokenTypeEnum tokenType = + Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken); + return tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE; +} +} // 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 c9c4b4853c22732bba50970124d134b17c66b2eb..8fe812c6900a34f579f9091e8e9110e7a313fe05 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -21,11 +21,17 @@ #include "ability_context.h" #include "ability_info.h" +#include "access_token_helper.h" #include "accesstoken_kit.h" #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "ans_watchdog.h" +#include "ans_permission_def.h" #include "bundle_manager_helper.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "display_manager.h" #include "ipc_skeleton.h" #include "notification_constant.h" #include "notification_filter.h" @@ -63,17 +69,18 @@ constexpr int32_t NOTIFICATION_MAX_COUNT = 1024; constexpr int32_t DEFAULT_RECENT_COUNT = 16; -constexpr int HOURS_IN_ONE_DAY = 24; +constexpr int32_t HOURS_IN_ONE_DAY = 24; -constexpr int DIALOG_POSTION_X = 150; -constexpr int DIALOG_POSTION_Y = 300; -constexpr int DIALOG_WIDTH = 450; -constexpr int DIALOG_HEIGHT = 300; +constexpr int32_t DIALOG_DEFAULT_WIDTH = 400; +constexpr int32_t DIALOG_DEFAULT_HEIGHT = 240; +constexpr int32_t WINDOW_DEFAULT_WIDTH = 720; +constexpr int32_t WINDOW_DEFAULT_HEIGHT = 1280; +constexpr int32_t UI_HALF = 2; struct RecentNotification { sptr notification = nullptr; bool isActive = false; - int deleteReason = 0; + int32_t deleteReason = 0; int64_t deleteTime = 0; }; } // namespace @@ -95,7 +102,7 @@ inline std::string GetClientBundleName() { std::string bundle; - int callingUid = IPCSkeleton::GetCallingUid(); + int32_t callingUid = IPCSkeleton::GetCallingUid(); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { @@ -109,7 +116,7 @@ inline bool IsSystemApp() { bool isSystemApp = false; - int callingUid = IPCSkeleton::GetCallingUid(); + int32_t callingUid = IPCSkeleton::GetCallingUid(); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { @@ -137,12 +144,9 @@ inline int64_t GetCurrentTime() inline tm GetLocalTime(time_t time) { - tm result = {0}; - tm *lt = localtime(&time); - if (lt != nullptr) { - result = *lt; - } - return result; + struct tm ret = {0}; + localtime_r(&time, &ret); + return ret; } inline ErrCode AssignValidNotificationSlot(const std::shared_ptr &record) @@ -158,7 +162,12 @@ inline ErrCode AssignValidNotificationSlot(const std::shared_ptrbundleOption, slots); } if (result == ERR_OK) { - record->slot = slot; + if (slot != nullptr && slot->GetEnable()) { + record->slot = slot; + } else { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED; + ANS_LOGE("Type[%{public}d] slot enable closed", slotType); + } } return result; } @@ -173,41 +182,64 @@ inline ErrCode CheckPictureSize(const sptr &request) std::static_pointer_cast(content->GetNotificationContent()); if (pictureContent != nullptr) { auto picture = pictureContent->GetBigPicture(); - if (picture != nullptr && (uint32_t)picture->GetByteCount() > MAX_PICTURE_SIZE) { + if (picture != nullptr && static_cast(picture->GetByteCount()) > MAX_PICTURE_SIZE) { result = ERR_ANS_PICTURE_OVER_SIZE; } } } auto littleIcon = request->GetLittleIcon(); - if (littleIcon != nullptr && (uint32_t)littleIcon->GetByteCount() > MAX_ICON_SIZE) { + if (littleIcon != nullptr && static_cast(littleIcon->GetByteCount()) > MAX_ICON_SIZE) { result = ERR_ANS_ICON_OVER_SIZE; } auto bigIcon = request->GetBigIcon(); - if (bigIcon != nullptr && (uint32_t)bigIcon->GetByteCount() > MAX_ICON_SIZE) { + if (bigIcon != nullptr && static_cast(bigIcon->GetByteCount()) > MAX_ICON_SIZE) { result = ERR_ANS_ICON_OVER_SIZE; } return result; } -ErrCode PrepereNotificationRequest(const sptr &request) +ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptr &request) { + ANS_LOGD("%{public}s", __FUNCTION__); + std::string bundle = GetClientBundleName(); if (bundle.empty()) { return ERR_ANS_INVALID_BUNDLE; } - request->SetOwnerBundleName(bundle); + if (request->IsAgentNotification()) { + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) || + !CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) { + return ERR_ANS_PERMISSION_DENIED; + } + + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + int32_t uid = -1; + if (bundleManager != nullptr) { + uid = bundleManager->GetDefaultUidByBundleName(request->GetOwnerBundleName(), request->GetOwnerUserId()); + } + if (uid < 0) { + return ERR_ANS_INVALID_UID; + } + request->SetOwnerUid(uid); + } else { + request->SetOwnerBundleName(bundle); + } request->SetCreatorBundleName(bundle); - int uid = IPCSkeleton::GetCallingUid(); - int pid = IPCSkeleton::GetCallingPid(); + int32_t uid = IPCSkeleton::GetCallingUid(); + int32_t pid = IPCSkeleton::GetCallingPid(); request->SetCreatorUid(uid); request->SetCreatorPid(pid); - int userId = SUBSCRIBE_USER_INIT; + int32_t userId = SUBSCRIBE_USER_INIT; OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); request->SetCreatorUserId(userId); ErrCode result = CheckPictureSize(request); @@ -233,6 +265,7 @@ AdvancedNotificationService::AdvancedNotificationService() { runner_ = OHOS::AppExecFwk::EventRunner::Create(); handler_ = std::make_shared(runner_); + AnsWatchdog::AddHandlerThread(handler_, runner_); recentInfo_ = std::make_shared(); distributedKvStoreDeathRecipient_ = std::make_shared( std::bind(&AdvancedNotificationService::OnDistributedKvStoreDeathRecipient, this)); @@ -246,6 +279,7 @@ AdvancedNotificationService::AdvancedNotificationService() std::bind(&AdvancedNotificationService::OnScreenOff, this), #endif std::bind(&AdvancedNotificationService::OnResourceRemove, this, std::placeholders::_1), + std::bind(&AdvancedNotificationService::OnBundleDataCleared, this, std::placeholders::_1), }; systemEventObserver_ = std::make_shared(iSystemEvent); @@ -291,7 +325,7 @@ sptr AdvancedNotificationService::GenerateBundleOption if (bundle.empty()) { return nullptr; } - int uid = IPCSkeleton::GetCallingUid(); + int32_t uid = IPCSkeleton::GetCallingUid(); bundleOption = new NotificationBundleOption(bundle, uid); return bundleOption; } @@ -303,12 +337,12 @@ sptr AdvancedNotificationService::GenerateValidBundleO if (bundleOption->GetUid() <= 0) { std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { - int activeUserId = -1; + int32_t activeUserId = -1; if (!GetActiveUserId(activeUserId)) { ANS_LOGE("Failed to get active user id!"); return validBundleOption; } - int uid = bundleManager->GetDefaultUidByBundleName(bundleOption->GetBundleName(), activeUserId); + int32_t uid = bundleManager->GetDefaultUidByBundleName(bundleOption->GetBundleName(), activeUserId); if (uid > 0) { validBundleOption = new NotificationBundleOption(bundleOption->GetBundleName(), uid); } @@ -328,7 +362,7 @@ ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ if (record->request->IsAlertOneTime()) { record->notification->SetEnableLight(false); record->notification->SetEnableSound(false); - record->notification->SetEnableViration(false); + record->notification->SetEnableVibration(false); } UpdateInNotificationList(record); } @@ -336,7 +370,7 @@ ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ } ErrCode AdvancedNotificationService::CancelPreparedNotification( - int notificationId, const std::string &label, const sptr &bundleOption) + int32_t notificationId, const std::string &label, const sptr &bundleOption) { if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -350,7 +384,7 @@ ErrCode AdvancedNotificationService::CancelPreparedNotification( } if (notification != nullptr) { - int reason = NotificationConstant::APP_CANCEL_REASON_DELETE; + int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); @@ -368,11 +402,18 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( if ((request->GetSlotType() == NotificationConstant::SlotType::CUSTOM) && !IsSystemApp()) { return ERR_ANS_NON_SYSTEM_APP; } - ErrCode result = PrepereNotificationRequest(request); + ErrCode result = PrepareNotificationRequest(request); if (result != ERR_OK) { return result; } - bundleOption = GenerateBundleOption(); + + if (request->IsAgentNotification()) { + bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(), + request->GetOwnerUid()); + } else { + bundleOption = GenerateBundleOption(); + } + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } @@ -504,7 +545,7 @@ sptr AdvancedNotificationService::GenerateSortingMap() std::vector sortingList; for (auto record : notificationList_) { NotificationSorting sorting; - sorting.SetRanking((int32_t)sortingList.size()); + sorting.SetRanking(static_cast(sortingList.size())); sorting.SetKey(record->notification->GetKey()); sorting.SetSlot(record->slot); sortingList.push_back(sorting); @@ -529,9 +570,10 @@ void AdvancedNotificationService::StopFilters() } } -ErrCode AdvancedNotificationService::Cancel(int notificationId, const std::string &label) +ErrCode AdvancedNotificationService::Cancel(int32_t notificationId, const std::string &label) { ANS_LOGD("%{public}s", __FUNCTION__); + sptr bundleOption = GenerateBundleOption(); return CancelPreparedNotification(notificationId, label, bundleOption); } @@ -561,7 +603,7 @@ ErrCode AdvancedNotificationService::CancelAll() } if (notification != nullptr) { - int reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE; + int32_t reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); @@ -576,6 +618,33 @@ ErrCode AdvancedNotificationService::CancelAll() return result; } +ErrCode AdvancedNotificationService::CancelAsBundle( + int32_t notificationId, const std::string &representativeBundle, int32_t userId) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) || + !CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) { + return ERR_ANS_PERMISSION_DENIED; + } + + int32_t uid = -1; + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager != nullptr) { + uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(representativeBundle, userId); + } + if (uid < 0) { + return ERR_ANS_INVALID_UID; + } + sptr bundleOption = new (std::nothrow) NotificationBundleOption( + representativeBundle, uid); + return CancelPreparedNotification(notificationId, "", bundleOption); +} + ErrCode AdvancedNotificationService::AddSlots(const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -584,7 +653,7 @@ ErrCode AdvancedNotificationService::AddSlots(const std::vectorPostSyncTask(std::bind([&]() { - int count = 0; + size_t count = 0; for (auto record : notificationList_) { if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && (record->bundleOption->GetUid() == bundleOption->GetUid())) { count += 1; } } - num = count; + num = static_cast(count); })); return result; } @@ -760,21 +829,24 @@ ErrCode AdvancedNotificationService::SetNotificationAgent(const std::string &age { return ERR_INVALID_OPERATION; } + ErrCode AdvancedNotificationService::GetNotificationAgent(std::string &agent) { return ERR_INVALID_OPERATION; } + ErrCode AdvancedNotificationService::CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) { return ERR_INVALID_OPERATION; } + ErrCode AdvancedNotificationService::PublishAsBundle( const sptr notification, const std::string &representativeBundle) { return ERR_INVALID_OPERATION; } -ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int num) +ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int32_t num) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -789,7 +861,7 @@ ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int num) return result; } -ErrCode AdvancedNotificationService::GetBundleImportance(int &importance) +ErrCode AdvancedNotificationService::GetBundleImportance(int32_t &importance) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -853,7 +925,7 @@ ErrCode AdvancedNotificationService::Delete(const std::string &key) return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -870,7 +942,7 @@ ErrCode AdvancedNotificationService::Delete(const std::string &key) } if (notification != nullptr) { - int reason = NotificationConstant::CANCEL_REASON_DELETE; + int32_t reason = NotificationConstant::CANCEL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); @@ -891,7 +963,7 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); @@ -939,13 +1011,13 @@ ErrCode AdvancedNotificationService::DeleteAll() return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { - int activeUserId = SUBSCRIBE_USER_INIT; + int32_t activeUserId = SUBSCRIBE_USER_INIT; (void)GetActiveUserId(activeUserId); std::vector keys = GetNotificationKeys(nullptr); for (auto key : keys) { @@ -955,12 +1027,12 @@ ErrCode AdvancedNotificationService::DeleteAll() sptr notification = nullptr; result = RemoveFromNotificationListForDeleteAll(key, activeUserId, notification); - if (result != ERR_OK || notification == nullptr) { + if ((result != ERR_OK) || (notification == nullptr)) { continue; } if (notification->GetUserId() == activeUserId) { - int reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; + int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); @@ -1001,7 +1073,7 @@ ErrCode AdvancedNotificationService::GetSlotsByBundle( return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1030,7 +1102,7 @@ ErrCode AdvancedNotificationService::UpdateSlots( return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1058,7 +1130,7 @@ ErrCode AdvancedNotificationService::UpdateSlotGroups( return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1086,7 +1158,7 @@ ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1110,7 +1182,7 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle( return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1151,7 +1223,7 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled) } ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptr &bundleOption, - const std::string &label, int notificationId, sptr ¬ification, bool isCancel) + const std::string &label, int32_t notificationId, sptr ¬ification, bool isCancel) { for (auto record : notificationList_) { if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && @@ -1200,7 +1272,7 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( } ErrCode AdvancedNotificationService::RemoveFromNotificationListForDeleteAll( - const std::string &key, const int &userId, sptr ¬ification) + const std::string &key, const int32_t &userId, sptr ¬ification) { for (auto record : notificationList_) { if ((record->notification->GetKey() == key) && (record->notification->GetUserId() == userId)) { @@ -1224,12 +1296,13 @@ ErrCode AdvancedNotificationService::Subscribe( { ANS_LOGD("%{public}s", __FUNCTION__); - if (!IsSystemApp()) { - ANS_LOGE("Client is not a system app"); + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); + if (!IsSystemApp() && !isSubsystem) { + ANS_LOGE("Client is not a system app or subsystem"); return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1245,12 +1318,13 @@ ErrCode AdvancedNotificationService::Unsubscribe( { ANS_LOGD("%{public}s", __FUNCTION__); - if (!IsSystemApp()) { - ANS_LOGE("Client is not a system app"); + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); + if (!IsSystemApp() && !isSubsystem) { + ANS_LOGE("Client is not a system app or subsystem"); return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1304,11 +1378,12 @@ ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vectorGetUid()) + std::string("\"}"); Ace::UIServiceMgrClient::GetInstance()->ShowDialog( "notification_dialog", params, - OHOS::Rosen::WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW, - DIALOG_POSTION_X, - DIALOG_POSTION_Y, - DIALOG_WIDTH, - DIALOG_HEIGHT, + Rosen::WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW, + positionX, + positionY, + width, + height, [this](int32_t id, const std::string& event, const std::string& params) { ANS_LOGD("Dialog callback: %{public}s, %{public}s", event.c_str(), params.c_str()); int32_t uid = std::stoi(params, nullptr); @@ -1434,11 +1516,11 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } - int userId = SUBSCRIBE_USER_INIT; + int32_t userId = SUBSCRIBE_USER_INIT; if (!GetActiveUserId(userId)) { return ERR_ANS_GET_ACTIVE_USER_FAILED; } @@ -1464,7 +1546,7 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1502,11 +1584,11 @@ ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed) return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } - int userId = SUBSCRIBE_USER_INIT; + int32_t userId = SUBSCRIBE_USER_INIT; if (!GetActiveUserId(userId)) { return ERR_ANS_GET_ACTIVE_USER_FAILED; } @@ -1523,35 +1605,49 @@ ErrCode AdvancedNotificationService::IsAllowedNotifySelf(bool &allowed) { ANS_LOGD("%{public}s", __FUNCTION__); - ErrCode result = ERR_OK; sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + return IsAllowedNotifySelf(bundleOption, allowed); +} + +ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptr &bundleOption, + bool &allowed) +{ + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + int32_t userId = SUBSCRIBE_USER_INIT; + if (!GetActiveUserId(userId)) { + return ERR_ANS_GET_ACTIVE_USER_FAILED; + } + + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { - result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleOption, allowed); - if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { - result = ERR_OK; - allowed = CheckApiCompatibility(bundleOption); - SetNotificationsEnabledForSpecialBundle("", bundleOption, allowed); + allowed = false; + result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed); + if (result == ERR_OK && allowed) { + result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleOption, allowed); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + allowed = CheckApiCompatibility(bundleOption); + SetNotificationsEnabledForSpecialBundle("", bundleOption, allowed); + } } })); - return result; } -ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( - const sptr &bundleOption, bool &allowed) +ErrCode AdvancedNotificationService::GetAppTargetBundle(const sptr &bundleOption, + sptr &targetBundle) { - ANS_LOGD("%{public}s", __FUNCTION__); - sptr clientBundle = GenerateBundleOption(); if (clientBundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; } - sptr targetBundle = nullptr; if (bundleOption == nullptr) { targetBundle = clientBundle; } else { @@ -1562,18 +1658,39 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( if (!IsSystemApp()) { return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { - return ERR_ANS_PERMISSION_DENIED; - } targetBundle = GenerateValidBundleOption(bundleOption); } } + return ERR_OK; +} + +ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( + const sptr &bundleOption, bool &allowed) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + return ERR_ANS_PERMISSION_DENIED; + } + + sptr targetBundle = nullptr; + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); + if (isSubsystem) { + if (bundleOption != nullptr) { + targetBundle = GenerateValidBundleOption(bundleOption); + } + } else { + ErrCode result = GetAppTargetBundle(bundleOption, targetBundle); + if (result != ERR_OK) { + return result; + } + } if (targetBundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; } - int userId = SUBSCRIBE_USER_INIT; + int32_t userId = SUBSCRIBE_USER_INIT; if (!GetActiveUserId(userId)) { return ERR_ANS_GET_ACTIVE_USER_FAILED; } @@ -1587,6 +1704,7 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { result = ERR_OK; allowed = CheckApiCompatibility(targetBundle); + SetNotificationsEnabledForSpecialBundle("", bundleOption, allowed); } } })); @@ -1621,11 +1739,17 @@ ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const spt { ANS_LOGD("%{public}s", __FUNCTION__); - int uid = IPCSkeleton::GetCallingUid(); - if (uid != SYSTEM_SERVICE_UID) { + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); + if (!isSubsystem) { return ERR_ANS_NOT_SYSTEM_SERVICE; } + int32_t uid = IPCSkeleton::GetCallingUid(); + int32_t userId = SUBSCRIBE_USER_INIT; + OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); + request->SetCreatorUserId(userId); + ANS_LOGD("%{public}s, uid=%{public}d userId=%{public}d", __FUNCTION__, uid, userId); + if (request->GetCreatorBundleName().empty()) { request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME); } @@ -1640,7 +1764,7 @@ ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const spt return ERR_ANS_INVALID_BUNDLE; } - ErrCode result = PrepereContinuousTaskNotificationRequest(request, uid); + ErrCode result = PrepareContinuousTaskNotificationRequest(request, uid); if (result != ERR_OK) { return result; } @@ -1660,7 +1784,7 @@ ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const spt if (record->request->IsAlertOneTime()) { record->notification->SetEnableLight(false); record->notification->SetEnableSound(false); - record->notification->SetEnableViration(false); + record->notification->SetEnableVibration(false); } UpdateInNotificationList(record); } @@ -1676,11 +1800,13 @@ ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const spt ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) { ANS_LOGD("%{public}s", __FUNCTION__); - int uid = IPCSkeleton::GetCallingUid(); - if (uid != SYSTEM_SERVICE_UID) { + + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); + if (!isSubsystem) { return ERR_ANS_NOT_SYSTEM_SERVICE; } + int32_t uid = IPCSkeleton::GetCallingUid(); ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { sptr notification = nullptr; @@ -1694,7 +1820,7 @@ ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std: } } if (notification != nullptr) { - int reason = NotificationConstant::APP_CANCEL_REASON_DELETE; + int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); @@ -1714,7 +1840,6 @@ ErrCode AdvancedNotificationService::PublishReminder(sptr &remi return result; } - ReminderDataManager::GetInstance()->SetService(this); sptr notificationRequest = reminder->GetNotificationRequest(); sptr bundleOption = nullptr; result = PrepareNotificationInfo(notificationRequest, bundleOption); @@ -1722,46 +1847,59 @@ ErrCode AdvancedNotificationService::PublishReminder(sptr &remi ANSR_LOGW("PrepareNotificationInfo fail"); return result; } - ReminderDataManager::GetInstance()->PublishReminder(reminder, bundleOption); + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + return ERR_NO_INIT; + } + rdm->PublishReminder(reminder, bundleOption); return ERR_OK; } ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId) { ANSR_LOGI("Cancel Reminder"); - ReminderDataManager::GetInstance()->SetService(this); sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } - ReminderDataManager::GetInstance()->CancelReminder(reminderId, bundleOption); + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + return ERR_NO_INIT; + } + rdm->CancelReminder(reminderId, bundleOption); return ERR_OK; } ErrCode AdvancedNotificationService::CancelAllReminders() { ANSR_LOGI("Cancel all reminders"); - ReminderDataManager::GetInstance()->SetService(this); sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } - int userId = -1; + int32_t userId = -1; AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); - ReminderDataManager::GetInstance()->CancelAllReminders(bundleOption, userId); + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + return ERR_NO_INIT; + } + rdm->CancelAllReminders(bundleOption->GetBundleName(), userId); return ERR_OK; } ErrCode AdvancedNotificationService::GetValidReminders(std::vector> &reminders) { ANSR_LOGI("GetValidReminders"); - ReminderDataManager::GetInstance()->SetService(this); reminders.clear(); sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } - ReminderDataManager::GetInstance()->GetValidReminders(bundleOption, reminders); + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + return ERR_NO_INIT; + } + rdm->GetValidReminders(bundleOption, reminders); ANSR_LOGD("Valid reminders size=%{public}zu", reminders.size()); return ERR_OK; } @@ -1851,9 +1989,9 @@ ErrCode AdvancedNotificationService::DistributedNotificationDump(std::vector NOTIFICATION_MAX_COUNT) { + if ((count < NOTIFICATION_MIN_COUNT) || (count > NOTIFICATION_MAX_COUNT)) { return ERR_ANS_INVALID_PARAM; } @@ -1870,7 +2008,9 @@ std::string AdvancedNotificationService::TimeToString(int64_t time) auto timeT = std::chrono::system_clock::to_time_t(timePoint); std::stringstream stream; - stream << std::put_time(std::localtime(&timeT), "%F, %T"); + struct tm ret = {0}; + localtime_r(&timeT, &ret); + stream << std::put_time(&ret, "%F, %T"); return stream.str(); } @@ -1883,7 +2023,8 @@ int64_t AdvancedNotificationService::GetNowSysTime() return duration; } -void AdvancedNotificationService::UpdateRecentNotification(sptr ¬ification, bool isDelete, int reason) +void AdvancedNotificationService::UpdateRecentNotification(sptr ¬ification, + bool isDelete, int32_t reason) { for (auto recentNotification : recentInfo_->list) { if (recentNotification->notification->GetKey() == notification->GetKey()) { @@ -1930,9 +2071,8 @@ static bool SortNotificationsByLevelAndTime( { if (first->slot->GetLevel() != second->slot->GetLevel()) { return (first->slot->GetLevel() < second->slot->GetLevel()); - } else { - return (first->request->GetCreateTime() < second->request->GetCreateTime()); } + return (first->request->GetCreateTime() < second->request->GetCreateTime()); } ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr &record) @@ -1940,7 +2080,7 @@ ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr= MAX_ACTIVE_NUM_PERSECOND) { - return ERR_ANS_OVER_MAX_ACITVE_PERSECOND; + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; } flowControlTimestampList_.push_back(now); @@ -1996,7 +2136,7 @@ void AdvancedNotificationService::OnBundleRemoved(const sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); @@ -2080,7 +2220,7 @@ ErrCode AdvancedNotificationService::AddSlotByType(NotificationConstant::SlotTyp } ErrCode AdvancedNotificationService::RemoveNotification( - const sptr &bundleOption, int notificationId, const std::string &label) + const sptr &bundleOption, int32_t notificationId, const std::string &label) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -2088,7 +2228,7 @@ ErrCode AdvancedNotificationService::RemoveNotification( return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -2129,7 +2269,7 @@ ErrCode AdvancedNotificationService::RemoveNotification( } if (notification != nullptr) { - int reason = NotificationConstant::CANCEL_REASON_DELETE; + int32_t reason = NotificationConstant::CANCEL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); @@ -2152,7 +2292,7 @@ ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptrnotification != nullptr) { - int reason = NotificationConstant::CANCEL_REASON_DELETE; + int32_t reason = NotificationConstant::CANCEL_REASON_DELETE; UpdateRecentNotification(record->notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason); @@ -2197,7 +2337,8 @@ ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptr &bundleOption, int &num) +ErrCode AdvancedNotificationService::GetSlotNumAsBundle( + const sptr &bundleOption, uint64_t &num) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -2205,7 +2346,7 @@ ErrCode AdvancedNotificationService::GetSlotNumAsBundle(const sptrnotification != nullptr) { - int reason = NotificationConstant::APP_CANCEL_REASON_DELETE; + int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE; UpdateRecentNotification(record->notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason); @@ -2280,7 +2421,7 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -2313,7 +2454,7 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( notificationList_.remove(record); if (record->notification != nullptr) { - int reason = NotificationConstant::CANCEL_REASON_DELETE; + int32_t reason = NotificationConstant::CANCEL_REASON_DELETE; UpdateRecentNotification(record->notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason); @@ -2388,15 +2529,18 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptr &request) +bool AdvancedNotificationService::CheckDistributedNotificationType(const sptr &request) { + auto deviceTypeList = request->GetNotificationDistributedOptions().GetDevicesSupportDisplay(); + if (deviceTypeList.empty()) { + return true; + } + DistributedDatabase::DeviceInfo localDeviceInfo; DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo); - auto deviceTypeList = request->GetNotificationDistributedOptions().GetDevicesSupportDisplay(); for (auto device : deviceTypeList) { if (device == localDeviceInfo.deviceType) { return true; @@ -2755,7 +2906,7 @@ void AdvancedNotificationService::OnDistributedPublish( const std::string &deviceId, const std::string &bundleName, sptr &request) { ANS_LOGD("%{public}s", __FUNCTION__); - int activeUserId = -1; + int32_t activeUserId = -1; if (!GetActiveUserId(activeUserId)) { ANS_LOGE("Failed to get active user id!"); return; @@ -2810,7 +2961,7 @@ void AdvancedNotificationService::OnDistributedUpdate( const std::string &deviceId, const std::string &bundleName, sptr &request) { ANS_LOGD("%{public}s", __FUNCTION__); - int activeUserId = -1; + int32_t activeUserId = -1; if (!GetActiveUserId(activeUserId)) { ANS_LOGE("Failed to get active user id!"); return; @@ -2853,7 +3004,7 @@ void AdvancedNotificationService::OnDistributedUpdate( if (record->request->IsAlertOneTime()) { record->notification->SetEnableLight(false); record->notification->SetEnableSound(false); - record->notification->SetEnableViration(false); + record->notification->SetEnableVibration(false); } UpdateInNotificationList(record); } @@ -2897,7 +3048,7 @@ void AdvancedNotificationService::OnDistributedDelete( } if (notification != nullptr) { - int reason = NotificationConstant::APP_CANCEL_REASON_OTHER; + int32_t reason = NotificationConstant::APP_CANCEL_REASON_OTHER; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); @@ -2908,7 +3059,7 @@ void AdvancedNotificationService::OnDistributedDelete( ErrCode AdvancedNotificationService::GetDistributedEnableInApplicationInfo( const sptr bundleOption, bool &enable) { - int userId = SUBSCRIBE_USER_INIT; + int32_t userId = SUBSCRIBE_USER_INIT; OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); if (userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && userId <= SUBSCRIBE_USER_SYSTEM_END) { @@ -2922,10 +3073,10 @@ ErrCode AdvancedNotificationService::GetDistributedEnableInApplicationInfo( } #endif -ErrCode AdvancedNotificationService::PrepereContinuousTaskNotificationRequest( - const sptr &request, const int &uid) +ErrCode AdvancedNotificationService::PrepareContinuousTaskNotificationRequest( + const sptr &request, const int32_t &uid) { - int pid = IPCSkeleton::GetCallingPid(); + int32_t pid = IPCSkeleton::GetCallingPid(); request->SetCreatorUid(uid); request->SetCreatorPid(pid); @@ -2960,7 +3111,7 @@ void AdvancedNotificationService::TriggerRemoveWantAgent(const sptrGetRemovalWantAgent() == nullptr) { + if ((request == nullptr) || (request->GetRemovalWantAgent() == nullptr)) { return; } OHOS::AbilityRuntime::WantAgent::TriggerInfo triggerInfo; @@ -2976,7 +3127,7 @@ ErrCode AdvancedNotificationService::IsSpecialUserAllowedNotify(const int32_t &u return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -2996,7 +3147,7 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledByUser(const int32_t return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -3030,12 +3181,12 @@ ErrCode AdvancedNotificationService::DeleteAllByUser(const int32_t &userId) sptr notification = nullptr; result = RemoveFromNotificationListForDeleteAll(key, userId, notification); - if (result != ERR_OK || notification == nullptr) { + if ((result != ERR_OK) || (notification == nullptr)) { continue; } if (notification->GetUserId() == userId) { - int reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; + int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); @@ -3065,7 +3216,7 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const int32_t &userId, return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -3086,7 +3237,7 @@ ErrCode AdvancedNotificationService::GetDoNotDisturbDate(const int32_t &userId, return ERR_ANS_NON_SYSTEM_APP; } - if (!CheckPermission(GetClientBundleName())) { + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -3096,7 +3247,9 @@ ErrCode AdvancedNotificationService::GetDoNotDisturbDate(const int32_t &userId, ErrCode AdvancedNotificationService::SetDoNotDisturbDateByUser(const int32_t &userId, const sptr &date) { + ANS_LOGD("%{public}s enter, userId = %{public}d", __FUNCTION__, userId); if (date == nullptr) { + ANS_LOGE("Invalid date param"); return ERR_ANS_INVALID_PARAM; } @@ -3104,7 +3257,6 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDateByUser(const int32_t &us int64_t beginDate = ResetSeconds(date->GetBeginDate()); int64_t endDate = ResetSeconds(date->GetEndDate()); - switch (date->GetDoNotDisturbType()) { case NotificationConstant::DoNotDisturbType::NONE: beginDate = 0; @@ -3121,7 +3273,8 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDateByUser(const int32_t &us default: break; } - + ANS_LOGD("Before set SetDoNotDisturbDate beginDate = %{public}" PRId64 ", endDate = %{public}" PRId64, + beginDate, endDate); const sptr newConfig = new NotificationDoNotDisturbDate( date->GetDoNotDisturbType(), beginDate, @@ -3130,6 +3283,7 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDateByUser(const int32_t &us sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { + ANS_LOGE("Generate invalid bundle option!"); return ERR_ANS_INVALID_BUNDLE; } @@ -3197,24 +3351,12 @@ ErrCode AdvancedNotificationService::GetHasPoppedDialog( bool AdvancedNotificationService::CheckApiCompatibility(const sptr &bundleOption) { - AppExecFwk::BundleInfo bundleInfo; + ANS_LOGD("%{public}s", __FUNCTION__); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); - int32_t callingUserId; - AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), callingUserId); - if (bundleManager != nullptr) { - if (!bundleManager->GetBundleInfoByBundleName(bundleOption->GetBundleName(), callingUserId, bundleInfo)) { - ANS_LOGW("Failed to GetBundleInfoByBundleName, bundlename = %{public}s", - bundleOption->GetBundleName().c_str()); - return false; - } - } - - for (auto abilityInfo : bundleInfo.abilityInfos) { - if (abilityInfo.isStageBasedModel) { - return false; - } + if (bundleManager == nullptr) { + return false; } - return true; + return bundleManager->CheckApiCompatibility(bundleOption); } void AdvancedNotificationService::OnResourceRemove(int32_t userId) @@ -3225,5 +3367,183 @@ void AdvancedNotificationService::OnResourceRemove(int32_t userId) NotificationPreferences::GetInstance().RemoveSettings(userId); })); } + +void AdvancedNotificationService::OnBundleDataCleared(const sptr &bundleOption) +{ + handler_->PostSyncTask(std::bind([&]() { + std::vector keys = GetNotificationKeys(bundleOption); + for (auto key : keys) { +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::string deviceId = GetNotificationDeviceId(key); +#endif + sptr notification = nullptr; + + ErrCode result = RemoveFromNotificationList(key, notification); + if (result != ERR_OK) { + continue; + } + + if (notification != nullptr) { + int32_t reason = NotificationConstant::CANCEL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, notification); +#endif + } + } + })); +} + +void AdvancedNotificationService::GetDisplayPosition( + int& offsetX, int& offsetY, int& width, int& height, bool& wideScreen) +{ + wideScreen = false; + auto display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay(); + if (display == nullptr) { + ANS_LOGD("dialog GetDefaultDisplay fail, try again."); + display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay(); + } + + if (display != nullptr) { + ANS_LOGD("display size: %{public}d x %{public}d", + display->GetWidth(), display->GetHeight()); + if (display->GetWidth() < display->GetHeight()) { + float widthRatio = 0.75f; + int32_t heightRatio = 5; + width = static_cast(display->GetWidth() * widthRatio); + height = display->GetHeight() / heightRatio; + } else { + int32_t widthRatio = 3; + int32_t heightRatio = 4; + wideScreen = true; + width = display->GetWidth() / widthRatio; + height = display->GetHeight() / heightRatio; + } + offsetX = (display->GetWidth() - width) / UI_HALF; + offsetY = (display->GetHeight() - height) / UI_HALF; + } else { + ANS_LOGD("dialog get display fail, use default wide."); + width = DIALOG_DEFAULT_WIDTH; + height = DIALOG_DEFAULT_HEIGHT; + offsetX = (WINDOW_DEFAULT_WIDTH - width) / UI_HALF; + offsetY = (WINDOW_DEFAULT_HEIGHT - height) / UI_HALF; + } + ANS_LOGD("GetDisplayPosition: %{public}d, %{public}d (%{public}d x %{public}d)", + offsetX, offsetY, width, height); +} + +ErrCode AdvancedNotificationService::SetEnabledForBundleSlot( + const sptr &bundleOption, const NotificationConstant::SlotType &slotType, bool enabled) +{ + ANS_LOGD("slotType: %{public}d, enabled: %{public}d", slotType, enabled); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + return ERR_ANS_PERMISSION_DENIED; + } + + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + sptr slot; + result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST || + result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + slot = new (std::nothrow) NotificationSlot(slotType); + if (slot == nullptr) { + ANS_LOGE("Failed to create NotificationSlot ptr."); + result = ERR_ANS_NO_MEMORY; + return; + } + } else if ((result == ERR_OK) && (slot != nullptr)) { + if (slot->GetEnable() == enabled) { + return; + } + NotificationPreferences::GetInstance().RemoveNotificationSlot(bundle, slotType); + } else { + ANS_LOGE("Set enable slot: GetNotificationSlot failed"); + return; + } + + slot->SetEnable(enabled); + std::vector> slots; + slots.push_back(slot); + result = NotificationPreferences::GetInstance().AddNotificationSlots(bundle, slots); + if (result != ERR_OK) { + ANS_LOGE("Set enable slot: AddNotificationSlot failed"); + return; + } + + PublishSlotChangeCommonEvent(bundle, slotType); + })); + return result; +} + +ErrCode AdvancedNotificationService::GetEnabledForBundleSlot( + const sptr &bundleOption, const NotificationConstant::SlotType &slotType, bool &enabled) +{ + ANS_LOGD("slotType: %{public}d", slotType); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + return ERR_ANS_PERMISSION_DENIED; + } + + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + sptr slot; + result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot); + if (result != ERR_OK) { + ANS_LOGE("Get enable slot: GetNotificationSlot failed"); + return; + } + if (slot == nullptr) { + ANS_LOGE("Get enable slot: object is null"); + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; + return; + } + enabled = slot->GetEnable(); + })); + + return result; +} + +bool AdvancedNotificationService::PublishSlotChangeCommonEvent( + const sptr &bundleOption, const NotificationConstant::SlotType &slotType) +{ + ANS_LOGD("slotType: %{public}d", slotType); + + EventFwk::Want want; + AppExecFwk::ElementName element; + element.SetBundleName(bundleOption->GetBundleName()); + want.SetElement(element); + want.SetParam(AppExecFwk::Constants::UID, bundleOption->GetUid()); + want.SetParam("SlotType", slotType); + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SLOT_CHANGE); + EventFwk::CommonEventData commonData {want}; + if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) { + ANS_LOGE("PublishCommonEvent failed"); + return false; + } + + return true; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index 56f052fb8b4cf0c10e32d58b47c6ebed42223f8d..2fb8f0911ce41d49d207755921e1b4cf80866255 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -38,11 +38,13 @@ void AdvancedNotificationServiceAbility::OnStart() if (!Publish(service_)) { return; } + reminderAgent_ = ReminderDataManager::InitInstance(service_); } void AdvancedNotificationServiceAbility::OnStop() { service_ = nullptr; + reminderAgent_ = nullptr; } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/bundle_manager_helper.cpp b/services/ans/src/bundle_manager_helper.cpp index 9e965edcb73798f9fe07f06e0f98ee0b2983315e..f5083925fc5da0442a30ca28003be98b30fc5a8d 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -17,6 +17,7 @@ #include "if_system_ability_manager.h" #include "iservice_registry.h" +#include "os_account_manager.h" #include "system_ability_definition.h" #include "ans_const_define.h" @@ -42,7 +43,7 @@ void BundleManagerHelper::OnRemoteDied(const wptr &object) Disconnect(); } -std::string BundleManagerHelper::GetBundleNameByUid(int uid) +std::string BundleManagerHelper::GetBundleNameByUid(int32_t uid) { std::string bundle; @@ -56,7 +57,7 @@ std::string BundleManagerHelper::GetBundleNameByUid(int uid) return bundle; } -bool BundleManagerHelper::IsSystemApp(int uid) +bool BundleManagerHelper::IsSystemApp(int32_t uid) { bool isSystemApp = false; @@ -71,6 +72,25 @@ bool BundleManagerHelper::IsSystemApp(int uid) return isSystemApp; } +bool BundleManagerHelper::CheckApiCompatibility(const sptr &bundleOption) +{ + AppExecFwk::BundleInfo bundleInfo; + int32_t callingUserId; + AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), callingUserId); + if (!GetBundleInfoByBundleName(bundleOption->GetBundleName(), callingUserId, bundleInfo)) { + ANS_LOGW("Failed to GetBundleInfoByBundleName, bundlename = %{public}s", + bundleOption->GetBundleName().c_str()); + return false; + } + + for (auto abilityInfo : bundleInfo.abilityInfos) { + if (abilityInfo.isStageBasedModel) { + return false; + } + } + return true; +} + bool BundleManagerHelper::GetBundleInfoByBundleName( const std::string bundle, const int32_t userId, AppExecFwk::BundleInfo &bundleInfo) { @@ -111,18 +131,18 @@ void BundleManagerHelper::Disconnect() } } -int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId) +int32_t BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId) { - int uid = -1; + int32_t uid = -1; std::lock_guard lock(connectionMutex_); Connect(); if (bundleMgr_ != nullptr) { - AppExecFwk::BundleInfo bundleInfo; - if (bundleMgr_->GetBundleInfo(bundle, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId)) { - uid = bundleInfo.uid; + uid = bundleMgr_->GetUidByBundleName(bundle, userId); + if (uid < 0) { + ANS_LOGW("get invalid uid of bundle %{public}s in userId %{public}d", bundle.c_str(), userId); } } @@ -130,7 +150,7 @@ int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, co } #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED -bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &bundleName, const int userId) +bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &bundleName, const int32_t userId) { std::lock_guard lock(connectionMutex_); diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index f29609b269038206ee223a5ab09382a1f573ab4e..981ba23b85e06d9de723d338922e79611e26ccc3 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -20,6 +20,7 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "bundle_manager_helper.h" #include "nlohmann/json.hpp" #include "os_account_manager.h" @@ -83,7 +84,7 @@ ErrCode NotificationPreferences::AddNotificationSlotGroups( } } - if (result == ERR_OK && + if ((result == ERR_OK) && (!preferncesDB_->PutGroupsToDisturbeDB(bundleOption->GetBundleName(), bundleOption->GetUid(), groups))) { return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -173,7 +174,7 @@ ErrCode NotificationPreferences::RemoveNotificationSlotGroups( return result; } } - if (result == ERR_OK && (!preferncesDB_->RemoveGroupsFromDisturbeDB(GenerateBundleKey(bundleOption), groupIds))) { + if ((result == ERR_OK) && (!preferncesDB_->RemoveGroupsFromDisturbeDB(GenerateBundleKey(bundleOption), groupIds))) { return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -226,7 +227,7 @@ ErrCode NotificationPreferences::UpdateNotificationSlots( } } - if (result == ERR_OK && + if ((result == ERR_OK) && (!preferncesDB_->PutSlotsToDisturbeDB(bundleOption->GetBundleName(), bundleOption->GetUid(), slots))) { return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -255,7 +256,7 @@ ErrCode NotificationPreferences::UpdateNotificationSlotGroups( } } - if (result == ERR_OK && + if ((result == ERR_OK) && (!preferncesDB_->PutGroupsToDisturbeDB(bundleOption->GetBundleName(), bundleOption->GetUid(), groups))) { return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -307,7 +308,7 @@ ErrCode NotificationPreferences::GetNotificationAllSlots( } ErrCode NotificationPreferences::GetNotificationSlotsNumForBundle( - const sptr &bundleOption, int &num) + const sptr &bundleOption, uint64_t &num) { if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; @@ -316,7 +317,7 @@ ErrCode NotificationPreferences::GetNotificationSlotsNumForBundle( ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { - num = bundleInfo.GetAllSlotsSize(); + num = static_cast(bundleInfo.GetAllSlotsSize()); } else { result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } @@ -401,7 +402,7 @@ ErrCode NotificationPreferences::SetShowBadge(const sptr &bundleOption, int &importance) +ErrCode NotificationPreferences::GetImportance(const sptr &bundleOption, int32_t &importance) { if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; @@ -411,7 +412,7 @@ ErrCode NotificationPreferences::GetImportance(const sptr &bundleOption, const int &importance) + const sptr &bundleOption, const int32_t &importance) { if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; @@ -425,7 +426,7 @@ ErrCode NotificationPreferences::SetImportance( } ErrCode NotificationPreferences::GetTotalBadgeNums( - const sptr &bundleOption, int &totalBadgeNum) + const sptr &bundleOption, int32_t &totalBadgeNum) { if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; @@ -433,7 +434,8 @@ ErrCode NotificationPreferences::GetTotalBadgeNums( return GetBundleProperty(bundleOption, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, totalBadgeNum); } -ErrCode NotificationPreferences::SetTotalBadgeNums(const sptr &bundleOption, const int num) +ErrCode NotificationPreferences::SetTotalBadgeNums( + const sptr &bundleOption, const int32_t num) { if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; @@ -567,6 +569,7 @@ ErrCode NotificationPreferences::GetDoNotDisturbDate(const int32_t &userId, ErrCode NotificationPreferences::SetDoNotDisturbDate(const int32_t &userId, const sptr date) { + ANS_LOGE("enter."); if (userId <= SUBSCRIBE_USER_INIT) { return ERR_ANS_INVALID_PARAM; } @@ -610,6 +613,7 @@ ErrCode NotificationPreferences::CheckSlotForCreateSlot(const sptrGetBundleName()); bundleInfo.SetBundleUid(bundleOption->GetUid()); + bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption)); } bundleInfo.SetSlot(slot); preferencesInfo.SetBundleInfo(bundleInfo); @@ -634,6 +638,7 @@ ErrCode NotificationPreferences::CheckGroupForCreateSlotGroup(const sptrGetBundleName()); bundleInfo.SetBundleUid(bundleOption->GetUid()); + bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption)); } else { if (bundleInfo.GetGroupSize() >= MAX_SLOT_GROUP_NUM) { return ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM; @@ -744,6 +749,7 @@ ErrCode NotificationPreferences::SetBundleProperty(NotificationPreferencesInfo & if (!preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { bundleInfo.SetBundleName(bundleOption->GetBundleName()); bundleInfo.SetBundleUid(bundleOption->GetUid()); + bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption)); } result = SaveBundleProperty(bundleInfo, bundleOption, type, value); @@ -889,5 +895,15 @@ void NotificationPreferences::RemoveSettings(int32_t userId) preferncesDB_->RemoveDoNotDisturbDate(userId); } } + +bool NotificationPreferences::CheckApiCompatibility(const sptr &bundleOption) const +{ + ANS_LOGD("%{public}s", __FUNCTION__); + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager == nullptr) { + return false; + } + return bundleManager->CheckApiCompatibility(bundleOption); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 85c9643aae91da15919ec540fa5e7d9aa03714cd..a0e6e93a40b1e21ee433f0c7d50035eb727bc8ea 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "notification_preferences_database.h" #include "ans_const_define.h" @@ -79,6 +80,11 @@ const std::map> &slots) + const std::string &bundleName, const int32_t &bundleUid, const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty()) { @@ -208,7 +214,7 @@ bool NotificationPreferencesDatabase::PutSlotsToDisturbeDB( } bool NotificationPreferencesDatabase::PutGroupsToDisturbeDB( - const std::string &bundleName, const int &bundleUid, const std::vector> &groups) + const std::string &bundleName, const int32_t &bundleUid, const std::vector> &groups) { if (bundleName.empty()) { ANS_LOGE("Bundle name is null."); @@ -225,6 +231,7 @@ bool NotificationPreferencesDatabase::PutGroupsToDisturbeDB( for (auto iter : groups) { result = GroupToEntry(bundleName, bundleUid, iter, entries); if (!result) { + ANS_LOGE("Group to entry is null."); return result; } } @@ -288,7 +295,7 @@ bool NotificationPreferencesDatabase::PutShowBadge( } bool NotificationPreferencesDatabase::PutImportance( - const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int &importance) + const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int32_t &importance) { if (bundleInfo.GetBundleName().empty()) { ANS_LOGE("Bundle name is null."); @@ -306,7 +313,7 @@ bool NotificationPreferencesDatabase::PutImportance( } bool NotificationPreferencesDatabase::PutTotalBadgeNums( - const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int &totalBadgeNum) + const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int32_t &totalBadgeNum) { if (bundleInfo.GetBundleName().empty()) { ANS_LOGE("Bundle name is null."); @@ -442,7 +449,7 @@ bool NotificationPreferencesDatabase::PutDoNotDisturbDate( } void NotificationPreferencesDatabase::GetValueFromDisturbeDB( - const std::string &key, std::function funcion) + const std::string &key, std::function callback) { if (!CheckKvStore()) { ANS_LOGE("KvStore is nullptr."); @@ -454,19 +461,19 @@ void NotificationPreferencesDatabase::GetValueFromDisturbeDB( DistributedKv::Key getKey(key); status = kvStorePtr_->Get(getKey, value); if (status != DistributedKv::Status::SUCCESS) { - ANS_LOGE("Get value failed, use defalut value. error code is %{public}d", status); + ANS_LOGE("Get value failed, use default value. error code is %{public}d", status); return; } if (value.Empty()) { - ANS_LOGE("Get value is empty, use defalut value. error code is %{public}d", value.Empty()); + ANS_LOGE("Get value is empty, use default value. error code is %{public}d", value.Empty()); return; } - funcion(value); + callback(value); } void NotificationPreferencesDatabase::GetValueFromDisturbeDB( - const std::string &key, std::function funcion) + const std::string &key, std::function callback) { if (!CheckKvStore()) { ANS_LOGE("KvStore is nullptr."); @@ -477,10 +484,10 @@ void NotificationPreferencesDatabase::GetValueFromDisturbeDB( DistributedKv::Value value; DistributedKv::Key getKey(key); status = kvStorePtr_->Get(getKey, value); - funcion(status, value); + callback(status, value); } -bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleName, const int &bundleUid) +bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleName, const int32_t &bundleUid) { std::string bundleKeyStr = KEY_BUNDLE_LABEL + bundleName + std::to_string(bundleUid); ANS_LOGD("CheckBundle bundleKeyStr %{public}s", bundleKeyStr.c_str()); @@ -808,7 +815,7 @@ void NotificationPreferencesDatabase::GenerateEntry( entries.push_back(entry); } -bool NotificationPreferencesDatabase::SlotToEntry(const std::string &bundleName, const int &bundleUid, +bool NotificationPreferencesDatabase::SlotToEntry(const std::string &bundleName, const int32_t &bundleUid, const sptr &slot, std::vector &entries) { if (slot == nullptr) { @@ -854,9 +861,10 @@ void NotificationPreferencesDatabase::GenerateSlotEntry(const std::string &bundl GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_VIBRATION_STYLE), VectorToString(slot->GetVibrationStyle()), entries); + GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_ENABLED), std::to_string(slot->GetEnable()), entries); } -bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleName, const int &bundleUid, +bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleName, const int32_t &bundleUid, const sptr &group, std::vector &entries) { @@ -900,9 +908,9 @@ void NotificationPreferencesDatabase::ParseBundleFromDistureDB( ANS_LOGD("Bundle key is %{public}s.", GenerateBundleKey(bundleKey).c_str()); NotificationPreferencesInfo::BundleInfo bunldeInfo; for (auto bundleEntry : bundleEntries) { - if (IsSlotKey(bundleKey, bundleEntry.key.ToString())) { + if (IsSlotKey(GenerateBundleKey(bundleKey), bundleEntry.key.ToString())) { ParseSlotFromDisturbeDB(bunldeInfo, bundleKey, bundleEntry); - } else if (IsGroupKey(bundleKey, bundleEntry.key.ToString())) { + } else if (IsGroupKey(GenerateBundleKey(bundleKey), bundleEntry.key.ToString())) { ParseGroupFromDisturbeDB(bunldeInfo, bundleKey, bundleEntry); } else { ParseBundlePropertyFromDisturbeDB(bunldeInfo, bundleKey, bundleEntry); @@ -1023,9 +1031,9 @@ void NotificationPreferencesDatabase::StringToVector(const std::string &str, std } } -int NotificationPreferencesDatabase::StringToInt(const std::string &str) const +int32_t NotificationPreferencesDatabase::StringToInt(const std::string &str) const { - int value = 0; + int32_t value = 0; if (!str.empty()) { value = stoi(str, nullptr); } @@ -1034,7 +1042,7 @@ int NotificationPreferencesDatabase::StringToInt(const std::string &str) const int64_t NotificationPreferencesDatabase::StringToInt64(const std::string &str) const { - int value = 0; + int64_t value = 0; if (!str.empty()) { value = stoll(str, nullptr); } @@ -1241,7 +1249,7 @@ void NotificationPreferencesDatabase::ParseBundlePoppedDialog( NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const { ANS_LOGD("SetBundlePoppedDialog bundle has popped dialog is %{public}s.", value.c_str()); - bundleInfo.SetEnableNotification(static_cast(StringToInt(value))); + bundleInfo.SetHasPoppedDialog(static_cast(StringToInt(value))); } void NotificationPreferencesDatabase::ParseBundleUid( @@ -1337,13 +1345,21 @@ void NotificationPreferencesDatabase::ParseSlotEnableBypassDnd( slot->EnableBypassDnd(enable); } +void NotificationPreferencesDatabase::ParseSlotEnabled( + sptr &slot, const std::string &value) const +{ + ANS_LOGD("ParseSlotEnabled slot enabled is %{public}s.", value.c_str()); + bool enabled = static_cast(StringToInt(value)); + slot->SetEnable(enabled); +} + std::string NotificationPreferencesDatabase::GenerateBundleLablel( const NotificationPreferencesInfo::BundleInfo &bundleInfo) const { return bundleInfo.GetBundleName().append(std::to_string(bundleInfo.GetBundleUid())); } -void NotificationPreferencesDatabase::GetDoNotDisturbType(NotificationPreferencesInfo &info, int userId) +void NotificationPreferencesDatabase::GetDoNotDisturbType(NotificationPreferencesInfo &info, int32_t userId) { std::string key = std::string().append(KEY_DO_NOT_DISTURB_TYPE).append(KEY_UNDER_LINE).append(std::to_string(userId)); @@ -1362,13 +1378,13 @@ void NotificationPreferencesDatabase::GetDoNotDisturbType(NotificationPreference } } } else { - ANS_LOGW("Parse disturbe mode failed, use defalut value."); + ANS_LOGW("Parse disturbe mode failed, use default value."); } info.SetDoNotDisturbDate(userId, disturbDate); }); } -void NotificationPreferencesDatabase::GetDoNotDisturbBeginDate(NotificationPreferencesInfo &info, int userId) +void NotificationPreferencesDatabase::GetDoNotDisturbBeginDate(NotificationPreferencesInfo &info, int32_t userId) { std::string key = std::string().append(KEY_DO_NOT_DISTURB_BEGIN_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId)); @@ -1386,13 +1402,13 @@ void NotificationPreferencesDatabase::GetDoNotDisturbBeginDate(NotificationPrefe } } } else { - ANS_LOGW("Parse disturbe start time failed, use defalut value."); + ANS_LOGW("Parse disturbe start time failed, use default value."); } info.SetDoNotDisturbDate(userId, disturbDate); }); } -void NotificationPreferencesDatabase::GetDoNotDisturbEndDate(NotificationPreferencesInfo &info, int userId) +void NotificationPreferencesDatabase::GetDoNotDisturbEndDate(NotificationPreferencesInfo &info, int32_t userId) { std::string key = std::string().append(KEY_DO_NOT_DISTURB_END_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId)); @@ -1410,13 +1426,13 @@ void NotificationPreferencesDatabase::GetDoNotDisturbEndDate(NotificationPrefere } } } else { - ANS_LOGW("Parse disturbe end time failed, use defalut value."); + ANS_LOGW("Parse disturbe end time failed, use default value."); } info.SetDoNotDisturbDate(userId, disturbDate); }); } -void NotificationPreferencesDatabase::GetEnableAllNotification(NotificationPreferencesInfo &info, int userId) +void NotificationPreferencesDatabase::GetEnableAllNotification(NotificationPreferencesInfo &info, int32_t userId) { std::string key = std::string().append(KEY_ENABLE_ALL_NOTIFICATION).append(KEY_UNDER_LINE).append(std::to_string(userId)); @@ -1434,7 +1450,7 @@ void NotificationPreferencesDatabase::GetEnableAllNotification(NotificationPrefe info.SetEnabledAllNotification(userId, static_cast(StringToInt(value.ToString()))); } } else { - ANS_LOGW("Parse enable all notification failed, use defalut value."); + ANS_LOGW("Parse enable all notification failed, use default value."); } }); } diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index 1afe46b42ffd44781c82a602940a94cc3bf6d02e..bd2788d8401e859a3dd934c4a235428018d7ef43 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -31,12 +31,12 @@ std::string NotificationPreferencesInfo::BundleInfo::GetBundleName() const return bundleName_; } -void NotificationPreferencesInfo::BundleInfo::SetImportance(const int &level) +void NotificationPreferencesInfo::BundleInfo::SetImportance(const int32_t &level) { importance_ = level; } -int NotificationPreferencesInfo::BundleInfo::GetImportance() const +int32_t NotificationPreferencesInfo::BundleInfo::GetImportance() const { return importance_; } @@ -51,12 +51,12 @@ bool NotificationPreferencesInfo::BundleInfo::GetIsShowBadge() const return isShowBadge_; } -void NotificationPreferencesInfo::BundleInfo::SetBadgeTotalNum(const int &num) +void NotificationPreferencesInfo::BundleInfo::SetBadgeTotalNum(const int32_t &num) { badgeTotalNum_ = num; } -int NotificationPreferencesInfo::BundleInfo::GetBadgeTotalNum() const +int32_t NotificationPreferencesInfo::BundleInfo::GetBadgeTotalNum() const { return badgeTotalNum_; } @@ -152,7 +152,9 @@ bool NotificationPreferencesInfo::BundleInfo::GetAllSlotsInGroup( void NotificationPreferencesInfo::BundleInfo::SetGroup(const sptr &group) { - groups_.insert_or_assign(group->GetId(), group); + if (group) { + groups_.insert_or_assign(group->GetId(), group); + } } bool NotificationPreferencesInfo::BundleInfo::GetGroup(const std::string &groupId, sptr &group) @@ -180,7 +182,7 @@ bool NotificationPreferencesInfo::BundleInfo::GetAllGroups(std::vectorslot->CanVibrate()) { - record->notification->SetEnableViration(true); + record->notification->SetEnableVibration(true); record->notification->SetVibrationStyle(record->slot->GetVibrationStyle()); } else { - record->notification->SetEnableViration(false); + record->notification->SetEnableVibration(false); } auto sound = record->slot->GetSound(); diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index cdd4abfcf1bcb76c006d38ae47aa950d38fa6c75..96d85e0a92aabb4ba754332e5e15d42bedc358b4 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -22,6 +22,7 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "ans_watchdog.h" #include "ipc_skeleton.h" #include "os_account_manager.h" #include "remote_death_recipient.h" @@ -39,6 +40,7 @@ NotificationSubscriberManager::NotificationSubscriberManager() { runner_ = OHOS::AppExecFwk::EventRunner::Create(); handler_ = std::make_shared(runner_); + AnsWatchdog::AddHandlerThread(handler_, runner_); recipient_ = new RemoteDeathRecipient(std::bind(&NotificationSubscriberManager::OnRemoteDied, this, std::placeholders::_1)); } @@ -66,15 +68,15 @@ ErrCode NotificationSubscriberManager::AddSubscriber( } if (subInfo->GetAppUserId() == SUBSCRIBE_USER_INIT) { - int userId = SUBSCRIBE_USER_INIT; - int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = SUBSCRIBE_USER_INIT; + int32_t callingUid = IPCSkeleton::GetCallingUid(); ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret != ERR_OK) { ANS_LOGD("Get userId failed, callingUid = <%{public}d>", callingUid); return ERR_ANS_INVALID_PARAM; } - ANS_LOGD("Get userId successed, callingUid = <%{public}d> userId = <%{public}d>", callingUid, userId); + ANS_LOGD("Get userId succeeded, callingUid = <%{public}d> userId = <%{public}d>", callingUid, userId); subInfo->AddAppUserId(userId); } @@ -116,7 +118,7 @@ void NotificationSubscriberManager::NotifyConsumed( } void NotificationSubscriberManager::NotifyCanceled( - const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) + const sptr ¬ification, const sptr ¬ificationMap, int32_t deleteReason) { if (handler_ == nullptr) { ANS_LOGE("handler is nullptr"); @@ -287,7 +289,7 @@ ErrCode NotificationSubscriberManager::RemoveSubscriberInner( RemoveRecordInfo(record, subscribeInfo); - if (record->subscribedAll == false && record->bundleList_.empty()) { + if (!record->subscribedAll && record->bundleList_.empty()) { record->subscriber->AsObject()->RemoveDeathRecipient(recipient_); subscriberRecordList_.remove(record); @@ -306,13 +308,14 @@ void NotificationSubscriberManager::NotifyConsumedInner( int32_t recvUserId = notification->GetNotificationRequest().GetReceiverUserId(); int32_t sendUserId = notification->GetUserId(); for (auto record : subscriberRecordList_) { - ANS_LOGD("%{public}s record->userId = <%{public}d>", __FUNCTION__, record->userId); auto BundleNames = notification->GetBundleName(); + ANS_LOGD("%{public}s record->userId = <%{public}d> BundleName = <%{public}s", + __FUNCTION__, record->userId, BundleNames.c_str()); auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); if (!record->subscribedAll == (iter != record->bundleList_.end()) && - (record->userId == sendUserId || - record->userId == SUBSCRIBE_USER_ALL || - record->userId == recvUserId || + ((record->userId == sendUserId) || + (record->userId == SUBSCRIBE_USER_ALL) || + (record->userId == recvUserId) || IsSystemUser(record->userId) || // Delete this, When the systemui subscribe carry the user ID. IsSystemUser(sendUserId))) { record->subscriber->OnConsumed(notification, notificationMap); @@ -322,7 +325,7 @@ void NotificationSubscriberManager::NotifyConsumedInner( } void NotificationSubscriberManager::NotifyCanceledInner( - const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) + const sptr ¬ification, const sptr ¬ificationMap, int32_t deleteReason) { ANS_LOGD("%{public}s notification->GetUserId <%{public}d>", __FUNCTION__, notification->GetUserId()); int32_t recvUserId = notification->GetNotificationRequest().GetReceiverUserId(); @@ -332,9 +335,9 @@ void NotificationSubscriberManager::NotifyCanceledInner( auto BundleNames = notification->GetBundleName(); auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); if (!record->subscribedAll == (iter != record->bundleList_.end()) && - (record->userId == sendUserId || - record->userId == SUBSCRIBE_USER_ALL || - record->userId == recvUserId || + ((record->userId == sendUserId) || + (record->userId == SUBSCRIBE_USER_ALL) || + (record->userId == recvUserId) || IsSystemUser(record->userId) || // Delete this, When the systemui subscribe carry the user ID. IsSystemUser(sendUserId))) { record->subscriber->OnCanceled(notification, notificationMap, deleteReason); @@ -359,11 +362,7 @@ void NotificationSubscriberManager::NotifyDoNotDisturbDateChangedInner(const spt bool NotificationSubscriberManager::IsSystemUser(int32_t userId) { - if (userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && userId <= SUBSCRIBE_USER_SYSTEM_END) { - return true; - } - - return false; + return ((userId >= SUBSCRIBE_USER_SYSTEM_BEGIN) && (userId <= SUBSCRIBE_USER_SYSTEM_END)); } void NotificationSubscriberManager::NotifyEnabledNotificationChangedInner( diff --git a/services/ans/src/permission_filter.cpp b/services/ans/src/permission_filter.cpp index 9c4a86870cd4a44666ca1c5e5c6b6239bd639618..41d6e4575d6120585523b1262a6e0f6cab2405fa 100644 --- a/services/ans/src/permission_filter.cpp +++ b/services/ans/src/permission_filter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -17,6 +17,7 @@ #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "bundle_manager_helper.h" #include "notification_preferences.h" namespace OHOS { @@ -34,7 +35,10 @@ ErrCode PermissionFilter::OnPublish(const std::shared_ptr &r NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(record->bundleOption, enable); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { result = ERR_OK; - enable = true; + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager != nullptr) { + enable = bundleManager->CheckApiCompatibility(record->bundleOption); + } } if (result == ERR_OK) { if (!enable) { diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 52adfccde3323e4a36e343f52e2db06b76e26392..a74441c54bf12da8bac47f77d1c05884caec6dc5 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -13,18 +13,25 @@ * limitations under the License. */ +#include "reminder_data_manager.h" + #include "ans_log_wrapper.h" #include "ans_const_define.h" #include "common_event_support.h" +#include "ipc_skeleton.h" #include "notification_slot.h" +#include "os_account_manager.h" #include "reminder_event_manager.h" #include "time_service_client.h" #include "singleton.h" -#include "reminder_data_manager.h" - namespace OHOS { namespace Notification { +namespace { +const std::string ALL_PACKAGES = "allPackages"; +const int32_t MAIN_USER_ID = 100; +} + const int16_t ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM = 2000; const int16_t ReminderDataManager::MAX_NUM_REMINDER_LIMIT_APP = 30; const uint8_t ReminderDataManager::TIME_ZONE_CHANGE = 0; @@ -35,10 +42,10 @@ std::mutex ReminderDataManager::SHOW_MUTEX; std::mutex ReminderDataManager::ALERT_MUTEX; std::mutex ReminderDataManager::TIMER_MUTEX; -void ReminderDataManager::PublishReminder(sptr &reminder, - sptr &bundleOption) +void ReminderDataManager::PublishReminder(const sptr &reminder, + const sptr &bundleOption) { - if (CheckReminderLimitExceededLocked(bundleOption->GetBundleName())) { + if (CheckReminderLimitExceededLocked(bundleOption)) { return; } UpdateAndSaveReminderLocked(reminder, bundleOption); @@ -68,67 +75,46 @@ void ReminderDataManager::CancelReminder( StartRecentReminder(); } -void ReminderDataManager::CancelNotification(const sptr &reminder) const +void ReminderDataManager::CancelAllReminders(const std::string &packageName, const int32_t &userId) { - if (!(reminder->IsShowing())) { - ANSR_LOGD("No need to cancel notification"); - return; - } - sptr notification = reminder->GetNotificationRequest(); - if (notification == nullptr) { - ANSR_LOGW("Cancel notification fail"); - return; - } - ANSR_LOGD("Cancel notification"); - if (advancedNotificationService_ == nullptr) { - ANSR_LOGE("Cancel notification fail"); - return; - } - sptr bundleOption = FindNotificationBundleOption(reminder->GetReminderId()); - advancedNotificationService_->CancelPreparedNotification( - notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL, bundleOption); + ANSR_LOGD("CancelAllReminders, userId=%{public}d, pkgName=%{public}s", + userId, packageName.c_str()); + CancelRemindersImplLocked(packageName, userId); } -bool ReminderDataManager::CheckReminderLimitExceededLocked(const std::string &bundleName) const +void ReminderDataManager::GetValidReminders( + const sptr &bundleOption, std::vector> &reminders) { std::lock_guard lock(ReminderDataManager::MUTEX); - if (totalCount_ >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM) { - ANSR_LOGW("The number of validate reminders exceeds the system upper limit:%{public}d, \ - and new reminder can not be published", MAX_NUM_REMINDER_LIMIT_SYSTEM); - return true; - } - int8_t count = 0; for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { if ((*it)->IsExpired()) { continue; } - auto mit = notificationBundleOptionMap_.find((*it)->GetReminderId()); + int32_t reminderId = (*it)->GetReminderId(); + auto mit = notificationBundleOptionMap_.find(reminderId); if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", (*it)->GetReminderId()); + ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); } else { - if (mit->second->GetBundleName() == bundleName) { - count++; + if (IsBelongToSameApp(mit->second, bundleOption)) { + reminders.push_back(*it); } } } - if (count >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_APP) { - ANSR_LOGW("The number of validate reminders exceeds the application upper limit:%{public}d, and new \ - reminder can not be published", MAX_NUM_REMINDER_LIMIT_APP); - return true; - } - return false; } -void ReminderDataManager::CancelAllReminders(const sptr &bundleOption, int userId) +void ReminderDataManager::CancelAllReminders(const int32_t &userId) +{ + ANSR_LOGD("CancelAllReminders, userId=%{public}d", userId); + CancelRemindersImplLocked(ALL_PACKAGES, userId); +} + +void ReminderDataManager::CancelRemindersImplLocked(const std::string &packageName, const int32_t &userId) { MUTEX.lock(); - auto it = notificationBundleOptionMap_.find(activeReminderId_); - if (it != notificationBundleOptionMap_.end()) { - if (it->second->GetBundleName() == bundleOption->GetBundleName()) { - activeReminder_->OnStop(); - StopTimer(TimerType::TRIGGER_TIMER); - ANSR_LOGD("Stop active reminder, reminderId=%{public}d", activeReminderId_); - } + if (activeReminderId_ != -1 && IsMatched(activeReminder_, packageName, userId)) { + activeReminder_->OnStop(); + StopTimer(TimerType::TRIGGER_TIMER); + ANSR_LOGD("Stop active reminder, reminderId=%{public}d", activeReminderId_); } for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) { int32_t reminderId = (*vit)->GetReminderId(); @@ -138,8 +124,7 @@ void ReminderDataManager::CancelAllReminders(const sptrsecond->GetBundleName() == bundleOption->GetBundleName()) { - ANSR_LOGD("currently, userId is not supported. userId=%{public}d", userId); + if (IsMatched(*vit, packageName, userId)) { if ((*vit)->IsAlerting()) { StopAlertingReminder(*vit); } @@ -153,28 +138,84 @@ void ReminderDataManager::CancelAllReminders(const sptrDeleteUser(userId); + } else { + store_->Delete(packageName, userId); + } MUTEX.unlock(); StartRecentReminder(); } -void ReminderDataManager::GetValidReminders( - const sptr bundleOption, std::vector> &reminders) +bool ReminderDataManager::IsMatched(const sptr &reminder, + const std::string &packageName, const int32_t &userId) const +{ + auto mit = notificationBundleOptionMap_.find(reminder->GetReminderId()); + if (mit == notificationBundleOptionMap_.end()) { + ANS_LOGE("Failed to get bundle information. reminderId=%{public}d", reminder->GetReminderId()); + return true; + } + if (ReminderRequest::GetUserId(mit->second->GetUid()) != userId) { + return false; + } + if (packageName == ALL_PACKAGES) { + return true; + } + if (mit->second->GetBundleName() == packageName) { + return true; + } + return false; +} + +void ReminderDataManager::CancelNotification(const sptr &reminder) const +{ + if (!(reminder->IsShowing())) { + ANSR_LOGD("No need to cancel notification"); + return; + } + sptr notification = reminder->GetNotificationRequest(); + if (notification == nullptr) { + ANSR_LOGW("Cancel notification fail"); + return; + } + ANSR_LOGD("Cancel notification"); + if (advancedNotificationService_ == nullptr) { + ANSR_LOGE("Cancel notification fail"); + return; + } + sptr bundleOption = FindNotificationBundleOption(reminder->GetReminderId()); + advancedNotificationService_->CancelPreparedNotification( + notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL, bundleOption); +} + +bool ReminderDataManager::CheckReminderLimitExceededLocked(const sptr &bundleOption) const { std::lock_guard lock(ReminderDataManager::MUTEX); + if (totalCount_ >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM) { + ANSR_LOGW("The number of validate reminders exceeds the system upper limit:%{public}d, \ + and new reminder can not be published", MAX_NUM_REMINDER_LIMIT_SYSTEM); + return true; + } + int8_t count = 0; for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { if ((*it)->IsExpired()) { continue; } - int32_t reminderId = (*it)->GetReminderId(); - auto mit = notificationBundleOptionMap_.find(reminderId); + auto mit = notificationBundleOptionMap_.find((*it)->GetReminderId()); if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); + ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", (*it)->GetReminderId()); } else { - if (mit->second->GetBundleName() == bundleOption->GetBundleName()) { - reminders.push_back(*it); + if (IsBelongToSameApp(mit->second, bundleOption)) { + count++; } } } + if (count >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_APP) { + ANSR_LOGW("The number of validate reminders exceeds the application upper limit:%{public}d, and new \ + reminder can not be published", MAX_NUM_REMINDER_LIMIT_APP); + return true; + } + return false; } void ReminderDataManager::AddToShowedReminders(const sptr &reminder) @@ -190,7 +231,36 @@ void ReminderDataManager::AddToShowedReminders(const sptr &remi showedReminderVector_.push_back(reminder); } -void ReminderDataManager::OnProcessDiedLocked(const sptr bundleOption) +void ReminderDataManager::OnUserRemove(const int32_t& userId) +{ + ANSR_LOGD("Remove user id: %{public}d", userId); + if (!IsReminderAgentReady()) { + ANSR_LOGW("Give up to remove user id: %{public}d for reminderAgent is not ready", userId); + return; + } + CancelAllReminders(userId); +} + +void ReminderDataManager::OnServiceStart() +{ + std::vector> immediatelyShowReminders; + GetImmediatelyShowRemindersLocked(immediatelyShowReminders); + ANSR_LOGD("immediatelyShowReminders size=%{public}zu", immediatelyShowReminders.size()); + HandleImmediatelyShow(immediatelyShowReminders, false); + StartRecentReminder(); +} + +void ReminderDataManager::OnUserSwitch(const int32_t& userId) +{ + ANSR_LOGD("Switch user id from %{public}d to %{public}d", currentUserId_, userId); + currentUserId_ = userId; + std::lock_guard lock(ReminderDataManager::MUTEX); + if ((alertingReminderId_ != -1) && IsReminderAgentReady()) { + TerminateAlerting(alertingReminder_, "OnUserSwitch"); + } +} + +void ReminderDataManager::OnProcessDiedLocked(const sptr &bundleOption) { std::string bundleName = bundleOption->GetBundleName(); int32_t uid = bundleOption->GetUid(); @@ -219,24 +289,33 @@ void ReminderDataManager::OnProcessDiedLocked(const sptrUpdateOrInsert((*it), bundleOption); } } std::shared_ptr ReminderDataManager::CreateTimerInfo(TimerType type) const { auto sharedTimerInfo = std::make_shared(); - sharedTimerInfo->SetType(sharedTimerInfo->TIMER_TYPE_WAKEUP|sharedTimerInfo->TIMER_TYPE_EXACT); + if ((sharedTimerInfo->TIMER_TYPE_WAKEUP > UINT8_MAX) || (sharedTimerInfo->TIMER_TYPE_EXACT > UINT8_MAX)) { + ANSR_LOGE("Failed to set timer type."); + return nullptr; + } + uint8_t timerTypeWakeup = static_cast(sharedTimerInfo->TIMER_TYPE_WAKEUP); + uint8_t timerTypeExact = static_cast(sharedTimerInfo->TIMER_TYPE_EXACT); + int32_t timerType = static_cast(timerTypeWakeup | timerTypeExact); + sharedTimerInfo->SetType(timerType); sharedTimerInfo->SetRepeat(false); sharedTimerInfo->SetInterval(0); - int requestCode = 10; + int32_t requestCode = 10; std::vector flags; flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); - auto want = std::make_shared(); + auto want = std::make_shared(); switch (type) { case (TimerType::TRIGGER_TIMER): { want->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); + want->SetParam(ReminderRequest::PARAM_REMINDER_ID, activeReminderId_); break; } case (TimerType::ALERTING_TIMER): { @@ -261,8 +340,12 @@ std::shared_ptr ReminderDataManager::CreateTimerInfo(TimerTyp wants, nullptr ); + + std::string identity = IPCSkeleton::ResetCallingIdentity(); std::shared_ptr wantAgent = AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, 0); + IPCSkeleton::SetCallingIdentity(identity); + sharedTimerInfo->SetWantAgent(wantAgent); return sharedTimerInfo; } @@ -303,6 +386,7 @@ sptr ReminderDataManager::FindNotificationBundleOption { auto it = notificationBundleOptionMap_.find(reminderId); if (it == notificationBundleOptionMap_.end()) { + ANSR_LOGW("Failed to get bundle option."); return nullptr; } else { return it->second; @@ -319,7 +403,7 @@ void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool c int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); sptr reminder = FindReminderRequestLocked(reminderId); if (reminder == nullptr) { - ANSR_LOGW("Invilate reminder id: %{public}d", reminderId); + ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); return; } CloseReminder(reminder, cancelNotification); @@ -340,15 +424,23 @@ void ReminderDataManager::CloseReminder(const sptr &reminder, b } reminder->OnClose(true); RemoveFromShowedReminders(reminder); + store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); if (cancelNotification) { CancelNotification(reminder); } } std::shared_ptr ReminderDataManager::GetInstance() +{ + return REMINDER_DATA_MANAGER; +} + +std::shared_ptr ReminderDataManager::InitInstance( + const sptr &advancedNotificationService) { if (REMINDER_DATA_MANAGER == nullptr) { REMINDER_DATA_MANAGER = std::make_shared(); + REMINDER_DATA_MANAGER->advancedNotificationService_ = advancedNotificationService; ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER); } return REMINDER_DATA_MANAGER; @@ -376,7 +468,7 @@ void ReminderDataManager::TerminateAlerting(const OHOS::EventFwk::Want &want) int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); sptr reminder = FindReminderRequestLocked(reminderId); if (reminder == nullptr) { - ANSR_LOGE("Invilate reminder id: %{public}d", reminderId); + ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); return; } TerminateAlerting(reminder, "timeOut"); @@ -390,14 +482,14 @@ void ReminderDataManager::TerminateAlerting(const uint16_t waitInSecond, const s void ReminderDataManager::TerminateAlerting(const sptr &reminder, const std::string &reason) { - ANSR_LOGI("Terminate the alerting reminder, %{public}s, called by %{public}s", - reminder->Dump().c_str(), reason.c_str()); - StopAlertingReminder(reminder); - if (reminder == nullptr) { ANSR_LOGE("TerminateAlerting illegal."); return; } + ANSR_LOGI("Terminate the alerting reminder, %{public}s, called by %{public}s", + reminder->Dump().c_str(), reason.c_str()); + StopAlertingReminder(reminder); + if (!reminder->OnTerminate()) { return; } @@ -410,7 +502,12 @@ void ReminderDataManager::TerminateAlerting(const sptr &reminde } ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); UpdateNotification(reminder); + if (advancedNotificationService_ == nullptr) { + ANSR_LOGE("Ans instance is null."); + return; + } advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); } void ReminderDataManager::UpdateAndSaveReminderLocked( @@ -419,6 +516,7 @@ void ReminderDataManager::UpdateAndSaveReminderLocked( std::lock_guard lock(ReminderDataManager::MUTEX); reminder->InitReminderId(); reminder->InitUserId(ReminderRequest::GetUserId(bundleOption->GetUid())); + reminder->InitUid(bundleOption->GetUid()); int32_t reminderId = reminder->GetReminderId(); ANSR_LOGD("Containers(map) add. reminderId=%{public}d", reminderId); auto ret = notificationBundleOptionMap_.insert( @@ -430,6 +528,7 @@ void ReminderDataManager::UpdateAndSaveReminderLocked( ANSR_LOGD("Containers(vector) add. reminderId=%{public}d", reminderId); reminderVector_.push_back(reminder); totalCount_++; + store_->UpdateOrInsert(reminder, bundleOption); } void ReminderDataManager::SetService(AdvancedNotificationService *advancedNotificationService) @@ -437,19 +536,68 @@ void ReminderDataManager::SetService(AdvancedNotificationService *advancedNotifi advancedNotificationService_ = advancedNotificationService; } -void ReminderDataManager::ShowActiveReminder() +bool ReminderDataManager::ShouldAlert(const sptr &reminder) const { - ANSR_LOGI("Begin to show reminder."); - if (activeReminderId_ == -1) { - ANSR_LOGE("Active reminder not exist"); - return; + if (reminder == nullptr) { + return false; + } + int32_t reminderId = reminder->GetReminderId(); + sptr bundleOption = FindNotificationBundleOption(reminderId); + if (bundleOption == nullptr) { + ANSR_LOGD("The reminder (reminderId=%{public}d) is silent", reminderId); + return false; + } + int32_t userId = ReminderRequest::GetUserId(bundleOption->GetUid()); + if (currentUserId_ != userId) { + ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for not in active user, " \ + "current user id: %{public}d, reminder user id: %{public}d", reminderId, currentUserId_, userId); + return false; } - if (HandleSysTimeChange(activeReminder_)) { + + sptr date; + ErrCode errCode = advancedNotificationService_->GetDoNotDisturbDate(date); + if (errCode != ERR_OK) { + ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get disturbDate error", reminderId); + return false; + } + if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { + return true; + } + std::vector> slots; + errCode = advancedNotificationService_->GetSlotsByBundle(bundleOption, slots); + if (errCode != ERR_OK) { + ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get slots error", reminderId); + return false; + } + for (auto slot : slots) { + if (slot->GetType() != reminder->GetSlotType()) { + continue; + } + if (slot->IsEnableBypassDnd()) { + ANSR_LOGD("Not silent for enable by pass Dnd, reminderId=%{public}d", reminderId); + return true; + } + } + ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for Dnd", reminderId); + return false; +} + +void ReminderDataManager::ShowActiveReminder(const EventFwk::Want &want) +{ + int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); + ANSR_LOGI("Begin to show reminder(reminderId=%{public}d)", reminderId); + if (reminderId == activeReminderId_) { ResetStates(TimerType::TRIGGER_TIMER); + } + sptr reminder = FindReminderRequestLocked(reminderId); + if (reminder == nullptr) { + ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); + return; + } + if (HandleSysTimeChange(reminder)) { return; } - ShowActiveReminderExtendLocked(activeReminder_); - ResetStates(TimerType::TRIGGER_TIMER); + ShowActiveReminderExtendLocked(reminder); StartRecentReminder(); } @@ -529,19 +677,17 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co if (advancedNotificationService_ == nullptr) { ANSR_LOGE("ShowReminder fail"); reminder->OnShow(false, isSysTimeChanged, false); + store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); return; } - if (isNeedToPlaySound) { // todo if shouldAlert - PlaySoundAndVibration(reminder); // play sound and vibration - reminder->OnShow(true, isSysTimeChanged, true); - if (needScheduleTimeout) { - StartTimer(reminder, TimerType::ALERTING_TIMER); - } else { - TerminateAlerting(1, reminder); - } - } else { - reminder->OnShow(false, isSysTimeChanged, true); + if (!IsAllowedNotify(reminder)) { + ANSR_LOGD("Not allow to notify."); + reminder->OnShow(false, isSysTimeChanged, false); + store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + return; } + bool toPlaySound = isNeedToPlaySound && ShouldAlert(reminder) ? true : false; + reminder->OnShow(toPlaySound, isSysTimeChanged, true); AddToShowedReminders(reminder); UpdateNotification(reminder); // this should be called after OnShow ANSR_LOGD("publish notification.(reminderId=%{public}d)", reminder->GetReminderId()); @@ -550,8 +696,18 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co reminder->OnShowFail(); RemoveFromShowedReminders(reminder); } else { + if (toPlaySound) { + PlaySoundAndVibration(reminder); // play sound and vibration + if (needScheduleTimeout) { + StartTimer(reminder, TimerType::ALERTING_TIMER); + } else { + TerminateAlerting(1, reminder); + } + } HandleSameNotificationIdShowing(reminder); } + store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + if (isNeedToStartNext) { StartRecentReminder(); } @@ -563,6 +719,7 @@ void ReminderDataManager::UpdateNotification(const sptr &remind reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::WANT_AGENT, ""); reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::MAX_SCREEN_WANT_AGENT, ""); + reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::BUNDLE_INFO, ""); } void ReminderDataManager::SnoozeReminder(const OHOS::EventFwk::Want &want) @@ -570,7 +727,7 @@ void ReminderDataManager::SnoozeReminder(const OHOS::EventFwk::Want &want) int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); sptr reminder = FindReminderRequestLocked(reminderId); if (reminder == nullptr) { - ANSR_LOGW("Invilate reminder id: %{public}d", reminderId); + ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); return; } SnoozeReminderImpl(reminder); @@ -592,6 +749,7 @@ void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) StopTimerLocked(TimerType::ALERTING_TIMER); } reminder->OnSnooze(); + store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); // 2) Show the notification dialog in the systemUI sptr bundleOption = FindNotificationBundleOption(reminderId); @@ -602,12 +760,14 @@ void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) } ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); UpdateNotification(reminder); + if (advancedNotificationService_ == nullptr) { + ANSR_LOGE("Ans instance is null"); + return; + } advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); StartRecentReminder(); } -// snoozeReminder(bool snoozeAll) - void ReminderDataManager::StartRecentReminder() { sptr reminder = GetRecentReminderLocked(); @@ -622,12 +782,13 @@ void ReminderDataManager::StartRecentReminder() } if (activeReminderId_ != -1) { activeReminder_->OnStop(); + store_->UpdateOrInsert(activeReminder_, FindNotificationBundleOption(activeReminderId_)); StopTimerLocked(TimerType::TRIGGER_TIMER); } ANSR_LOGI("Start recent reminder"); StartTimerLocked(reminder, TimerType::TRIGGER_TIMER); reminder->OnStart(); - SetActiveReminder(reminder); + store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); } void ReminderDataManager::StopAlertingReminder(const sptr &reminder) @@ -636,7 +797,7 @@ void ReminderDataManager::StopAlertingReminder(const sptr &remi ANSR_LOGE("StopAlertingReminder illegal."); return; } - if (alertingReminderId_ == -1 || reminder->GetReminderId() != alertingReminderId_) { + if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) { ANSR_LOGE("StopAlertingReminder is illegal."); return; } @@ -727,28 +888,11 @@ sptr ReminderDataManager::GetRecentReminderLocked() } it = reminderVector_.erase(it); totalCount_--; + store_->Delete(reminderId); } return nullptr; } -std::vector> ReminderDataManager::GetSameBundleRemindersLocked(std::string &bundleName) -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - std::vector> reminders; - for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - sptr bundleOption = FindNotificationBundleOption((*it)->GetReminderId()); - if (bundleOption == nullptr) { - ANSR_LOGW("GetSameBundleRemindersLocked get notificationBundleOption(reminderId=%{public}d) fail", - (*it)->GetReminderId()); - continue; - } - if (bundleName == bundleOption->GetBundleName()) { - reminders.push_back((*it)); - } - } - return reminders; -} - void ReminderDataManager::HandleImmediatelyShow( std::vector> &showImmediately, bool isSysTimeChanged) { @@ -763,7 +907,7 @@ void ReminderDataManager::HandleImmediatelyShow( } } -sptr ReminderDataManager::HandleRefreshReminder(uint8_t &type, sptr &reminder) +sptr ReminderDataManager::HandleRefreshReminder(const uint8_t &type, sptr &reminder) { reminder->SetReminderTimeInMilli(ReminderRequest::INVALID_LONG_LONG_VALUE); uint64_t triggerTimeBefore = reminder->GetTriggerTimeInMilli(); @@ -779,8 +923,10 @@ sptr ReminderDataManager::HandleRefreshReminder(uint8_t &type, if (triggerTimeBefore != triggerTimeAfter || reminder->GetReminderId() == alertingReminderId_) { CloseReminder(reminder, true); } + store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); return nullptr; } + store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); return reminder; } @@ -790,6 +936,12 @@ void ReminderDataManager::HandleSameNotificationIdShowing(const sptrGetNotificationId(); ANSR_LOGD("HandleSameNotificationIdShowing notificationId=%{public}d", notificationId); int32_t curReminderId = reminder->GetReminderId(); + auto mit = notificationBundleOptionMap_.find(curReminderId); + if (mit == notificationBundleOptionMap_.end()) { + ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", curReminderId); + return; + } + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { int32_t tmpId = (*it)->GetReminderId(); if (tmpId == curReminderId) { @@ -803,36 +955,127 @@ void ReminderDataManager::HandleSameNotificationIdShowing(const sptrGetNotificationId() && - IsBelongToSameApp(reminder, bundleOption->GetBundleName(), 0)) { + if (notificationId == (*it)->GetNotificationId() && IsBelongToSameApp(bundleOption, mit->second)) { if ((*it)->IsAlerting()) { StopAlertingReminder(*it); } (*it)->OnSameNotificationIdCovered(); RemoveFromShowedReminders(*it); + store_->UpdateOrInsert((*it), FindNotificationBundleOption((*it)->GetReminderId())); } } } -bool ReminderDataManager::IsBelongToSameApp( - const sptr reminder, const std::string otherPkgName, const int otherUserId) +void ReminderDataManager::Init(bool isFromBootComplete) { - ANSR_LOGD("otherUserId=%{public}d, (currently, userId not support)", otherUserId); + ANSR_LOGD("ReminderDataManager Init, isFromBootComplete:%{public}d", isFromBootComplete); + if (IsReminderAgentReady()) { + return; + } + if (store_ == nullptr) { + store_ = std::make_shared(); + } + if (store_->Init() != ReminderStore::STATE_OK) { + ANSR_LOGW("Db init fail."); + return; + } + LoadReminderFromDb(); + InitUserId(); + isReminderAgentReady_ = true; + ANSR_LOGD("ReminderAgent is ready."); +} + +void ReminderDataManager::InitUserId() +{ + std::vector activeUserId; + AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); + if (activeUserId.size() > 0) { + currentUserId_ = activeUserId[0]; + ANSR_LOGD("Init user id=%{public}d", currentUserId_); + } else { + currentUserId_ = MAIN_USER_ID; + ANSR_LOGE("Failed to get active user id."); + } +} + +void ReminderDataManager::GetImmediatelyShowRemindersLocked(std::vector> &reminders) const +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + for (auto reminderSptr : reminderVector_) { + if (!(reminderSptr->ShouldShowImmediately())) { + break; + } + if (reminderSptr->GetReminderType() != ReminderRequest::ReminderType::TIMER) { + reminderSptr->SetSnoozeTimesDynamic(0); + } + reminders.push_back(reminderSptr); + } +} + +bool ReminderDataManager::IsAllowedNotify(const sptr &reminder) const +{ + if (reminder == nullptr) { + return false; + } int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = FindNotificationBundleOption(reminderId); - if (bundleOption == nullptr) { - ANSR_LOGW("IsBelongToSameApp get notificationBundleOption(reminderId=%{public}d) fail", reminderId); + auto mit = notificationBundleOptionMap_.find(reminderId); + if (mit == notificationBundleOptionMap_.end()) { + ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); return false; } - if (bundleOption->GetBundleName() == otherPkgName) { - return true; + bool isAllowed = false; + ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(mit->second, isAllowed); + if (errCode != ERR_OK) { + ANSR_LOGE("Failed to call IsSpecialBundleAllowedNotify, errCode=%{public}d", errCode); + return false; } - return false; + return isAllowed; +} + +bool ReminderDataManager::IsReminderAgentReady() const +{ + return isReminderAgentReady_; +} + +bool ReminderDataManager::IsBelongToSameApp(const sptr &bundleOption, + const sptr &other) const +{ + int32_t userIdSrc = ReminderRequest::GetUserId(bundleOption->GetUid()); + int32_t userIdTar = ReminderRequest::GetUserId(other->GetUid()); + return ((bundleOption->GetBundleName() == other->GetBundleName()) && (userIdSrc == userIdTar)) ? true : false; +} + +void ReminderDataManager::LoadReminderFromDb() +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + std::vector> existReminders = store_->GetAllValidReminders(); + reminderVector_ = existReminders; + ANSR_LOGD("LoadReminderFromDb, reminder size=%{public}zu", reminderVector_.size()); + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + sptr bundleOption = new (std::nothrow) NotificationBundleOption(); + if (bundleOption == nullptr) { + ANS_LOGE("Failed to create bundle option due to low memory."); + return; + } + int32_t reminderId = (*it)->GetReminderId(); + if (!(store_->GetBundleOption(reminderId, bundleOption))) { + ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); + continue; + } + auto ret = notificationBundleOptionMap_.insert( + std::pair>(reminderId, bundleOption)); + if (!ret.second) { + ANSR_LOGE("Containers add to map error"); + continue; + } + } + totalCount_ = static_cast(reminderVector_.size()); + ReminderRequest::GLOBAL_ID = store_->GetMaxId() + 1; } void ReminderDataManager::PlaySoundAndVibrationLocked(const sptr &reminder) { - std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); // todo check died lock + std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); PlaySoundAndVibration(reminder); } @@ -860,10 +1103,14 @@ void ReminderDataManager::PlaySoundAndVibration(const sptr &rem std::string ReminderDataManager::GetSoundUri(const sptr &reminder) { + Uri uri = DEFAULT_NOTIFICATION_SOUND; + if (advancedNotificationService_ == nullptr) { + ANSR_LOGE("Ans instance is null."); + return uri.GetSchemeSpecificPart(); + } sptr bundle = FindNotificationBundleOption(reminder->GetReminderId()); std::vector> slots; ErrCode errCode = advancedNotificationService_->GetSlotsByBundle(bundle, slots); - Uri uri = DEFAULT_NOTIFICATION_SOUND; if (errCode != ERR_OK) { ANSR_LOGW("Get sound uri fail, use default sound instead."); return uri.GetSchemeSpecificPart(); @@ -889,15 +1136,19 @@ void ReminderDataManager::StopSoundAndVibration(const sptr &rem ANSR_LOGE("Stop sound and vibration failed as reminder is null."); return; } - if (alertingReminderId_ == -1 || (reminder->GetReminderId() != alertingReminderId_)) { + if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) { ANSR_LOGE("Stop sound and vibration failed as alertingReminder is illegal, alertingReminderId_=" \ "%{public}d, tarReminderId=%{public}d", alertingReminderId_, reminder->GetReminderId()); return; } ANSR_LOGD("Stop sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); - soundPlayer_->Stop(); - soundPlayer_->Release(); - soundPlayer_ = nullptr; + if (soundPlayer_ == nullptr) { + ANSR_LOGW("Sound player is null"); + } else { + soundPlayer_->Stop(); + soundPlayer_->Release(); + soundPlayer_ = nullptr; + } sptr nullReminder = nullptr; SetAlertingReminder(nullReminder); } @@ -935,6 +1186,7 @@ void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId) ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); it = reminderVector_.erase(it); totalCount_--; + store_->Delete(reminderId); break; } else { ++it; @@ -958,6 +1210,10 @@ void ReminderDataManager::StartTimerLocked(const sptr &reminder void ReminderDataManager::StartTimer(const sptr &reminderRequest, TimerType type) { sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr) { + ANS_LOGE("Failed to start timer due to get TimeServiceClient is null."); + return; + } time_t now; (void)time(&now); // unit is seconds. if (now < 0) { @@ -971,11 +1227,11 @@ void ReminderDataManager::StartTimer(const sptr &reminderReques ANSR_LOGE("Trigger timer has already started."); break; } - triggerTime = reminderRequest->GetTriggerTimeInMilli(); + SetActiveReminder(reminderRequest); timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type)); + triggerTime = reminderRequest->GetTriggerTimeInMilli(); timer->StartTimer(timerId_, triggerTime); - SetActiveReminder(reminderRequest); - ANSR_LOGD("Start timing (next triggerTime), timerId=%{public}llu", (unsigned long long)timerId_); + ANSR_LOGD("Start timing (next triggerTime), timerId=%{public}" PRIu64 "", timerId_); break; } case TimerType::ALERTING_TIMER: { @@ -988,7 +1244,7 @@ void ReminderDataManager::StartTimer(const sptr &reminderReques timerIdAlerting_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type)); timer->StartTimer(timerIdAlerting_, triggerTime); ANSR_LOGD( - "Start timing (alerting time out), timerId=%{public}llu", (unsigned long long)timerIdAlerting_); + "Start timing (alerting time out), timerId=%{public}" PRIu64 "", timerIdAlerting_); break; } default: { @@ -999,9 +1255,8 @@ void ReminderDataManager::StartTimer(const sptr &reminderReques if (triggerTime == 0) { ANSR_LOGW("Start timer fail"); } else { - ANSR_LOGD("Timing info: now:(%{public}llu), tar:(%{public}llu)", - (unsigned long long)(ReminderRequest::GetDurationSinceEpochInMilli(now)), - (unsigned long long)(triggerTime)); + ANSR_LOGD("Timing info: now:(%{public}" PRIu64 "), tar:(%{public}" PRIu64 ")", + ReminderRequest::GetDurationSinceEpochInMilli(now), triggerTime); } } @@ -1014,6 +1269,10 @@ void ReminderDataManager::StopTimerLocked(TimerType type) void ReminderDataManager::StopTimer(TimerType type) { sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr) { + ANSR_LOGE("Failed to stop timer due to get TimeServiceClient is null."); + return; + } uint64_t timerId = 0; switch (type) { case TimerType::TRIGGER_TIMER: { @@ -1035,7 +1294,7 @@ void ReminderDataManager::StopTimer(TimerType type) ANSR_LOGD("Timer is not running"); return; } - ANSR_LOGD("Stop timer id=%{public}llu", (unsigned long long)timerId); + ANSR_LOGD("Stop timer id=%{public}" PRIu64 "", timerId); timer->StopTimer(timerId); ResetStates(type); } @@ -1044,13 +1303,13 @@ void ReminderDataManager::ResetStates(TimerType type) { switch (type) { case TimerType::TRIGGER_TIMER: { - ANSR_LOGD("ResetStates(activeReminder)"); + ANSR_LOGD("ResetStates(activeReminderId, timerId(next triggerTime))"); timerId_ = 0; activeReminderId_ = -1; break; } case TimerType::ALERTING_TIMER: { - ANSR_LOGD("ResetStates(alertingReminder)"); + ANSR_LOGD("ResetStates(alertingReminderId, timeId(alerting time out))"); timerIdAlerting_ = 0; alertingReminderId_ = -1; break; diff --git a/services/ans/src/reminder_event_manager.cpp b/services/ans/src/reminder_event_manager.cpp index 852d4367258df06f8dd7c30e1755739d574b08f2..ff0cdc5c49bbf9d16a4cff0f31e3fc329df9821c 100644 --- a/services/ans/src/reminder_event_manager.cpp +++ b/services/ans/src/reminder_event_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -13,15 +13,18 @@ * limitations under the License. */ +#include "reminder_event_manager.h" + #include "ans_log_wrapper.h" #include "appmgr/app_mgr_constants.h" #include "bundle_constants.h" #include "bundle_mgr_interface.h" #include "common_event_manager.h" #include "common_event_support.h" +#include "if_system_ability_manager.h" #include "ipc_skeleton.h" - -#include "reminder_event_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" using namespace OHOS::EventFwk; namespace OHOS { @@ -38,11 +41,14 @@ void ReminderEventManager::init(std::shared_ptr &reminderDa matchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); matchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CLOSE_ALERT); matchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_TIME_CHANGED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED); CommonEventSubscribeInfo subscriberInfo(matchingSkills); auto subscriber = std::make_shared(subscriberInfo, reminderDataManager); @@ -53,6 +59,22 @@ void ReminderEventManager::init(std::shared_ptr &reminderDa ANSR_LOGD("SubscribeCommonEvent fail"); } IPCSkeleton::SetCallingIdentity(identity); + + sptr statusChangeListener + = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); + if (statusChangeListener == nullptr) { + ANSR_LOGE("Failed to create statusChangeListener due to no memory."); + return; + } + sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + ANSR_LOGD("samgrProxy is null"); + return; + } + int32_t ret = samgrProxy->SubscribeSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, statusChangeListener); + if (ret != ERR_OK) { + ANSR_LOGE("subscribe system ability id: %{public}d failed", BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + } } ReminderEventManager::ReminderEventSubscriber::ReminderEventSubscriber( @@ -68,7 +90,7 @@ void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFw std::string action = want.GetAction(); ANSR_LOGI("Recieved common event:%{public}s", action.c_str()); if (action == ReminderRequest::REMINDER_EVENT_ALARM_ALERT) { - reminderDataManager_->ShowActiveReminder(); + reminderDataManager_->ShowActiveReminder(want); return; } if (action == ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT) { @@ -87,6 +109,10 @@ void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFw reminderDataManager_->CloseReminder(want, false); return; } + if (action == CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED) { + reminderDataManager_->Init(true); + return; + } if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { HandlePackageRemove(want); return; @@ -107,22 +133,25 @@ void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFw reminderDataManager_->RefreshRemindersDueToSysTimeChange(ReminderDataManager::DATE_TIME_CHANGE); return; } + if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + reminderDataManager_->OnUserSwitch(data.GetCode()); + return; + } + if (action == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { + reminderDataManager_->OnUserRemove(data.GetCode()); + return; + } } -void ReminderEventManager::ReminderEventSubscriber::HandlePackageRemove(OHOS::EventFwk::Want &want) const +void ReminderEventManager::ReminderEventSubscriber::HandlePackageRemove(const EventFwk::Want &want) const { OHOS::AppExecFwk::ElementName ele = want.GetElement(); std::string bundleName = ele.GetBundleName(); - int userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); - sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, -1); - if (bundleOption == nullptr) { - ANSR_LOGE("new NotificationBundleOption fail due to no memory."); - return; - } - reminderDataManager_->CancelAllReminders(bundleOption, userId); + int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); + reminderDataManager_->CancelAllReminders(bundleName, userId); } -void ReminderEventManager::ReminderEventSubscriber::HandleProcessDied(OHOS::EventFwk::Want &want) const +void ReminderEventManager::ReminderEventSubscriber::HandleProcessDied(const EventFwk::Want &want) const { sptr bundleOption = GetBundleOption(want); if (bundleOption == nullptr) { @@ -137,7 +166,7 @@ sptr ReminderEventManager::ReminderEventSubscriber::Ge { OHOS::AppExecFwk::ElementName ele = want.GetElement(); std::string bundleName = ele.GetBundleName(); - int userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); + int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); int32_t uid = ReminderRequest::GetUid(userId, bundleName); ANSR_LOGD("bundleName=%{public}s, userId=%{public}d, uid=%{public}d", bundleName.c_str(), userId, uid); sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); @@ -146,5 +175,24 @@ sptr ReminderEventManager::ReminderEventSubscriber::Ge } return bundleOption; } + +ReminderEventManager::SystemAbilityStatusChangeListener::SystemAbilityStatusChangeListener( + std::shared_ptr &reminderDataManager) +{ + reminderDataManager_ = reminderDataManager; +} + +void ReminderEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + ANSR_LOGD("OnAddSystemAbilityInner"); + reminderDataManager_->OnServiceStart(); +} + +void ReminderEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + ANSR_LOGD("OnRemoveSystemAbilityInner"); +} } // namespace OHOS } // namespace Notification diff --git a/services/ans/src/reminder_timer_info.cpp b/services/ans/src/reminder_timer_info.cpp index 939bb06856faef7782d3a5a09519be9d4510d8cc..fbfd1ab728810f03e7926456ad30124323c814f4 100644 --- a/services/ans/src/reminder_timer_info.cpp +++ b/services/ans/src/reminder_timer_info.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -13,12 +13,12 @@ * limitations under the License. */ +#include "reminder_timer_info.h" + #include "ans_log_wrapper.h" #include "common_event_manager.h" #include "reminder_request.h" -#include "reminder_timer_info.h" - using namespace OHOS::EventFwk; namespace OHOS { namespace Notification { diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index 3a1874b82063389e8afa6f732f75b08cc450cd06..8ada7d50d94c1be5fa024df53fadb8ad52c624e7 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -33,6 +33,7 @@ SystemEventObserver::SystemEventObserver(const ISystemEvent &callbacks) : callba #endif matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED); EventFwk::CommonEventSubscribeInfo commonEventSubscribeInfo(matchingSkills); subscriber_ = std::make_shared( @@ -46,6 +47,18 @@ SystemEventObserver::~SystemEventObserver() EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriber_); } +sptr SystemEventObserver::GetBundleOption(AAFwk::Want want) +{ + auto element = want.GetElement(); + std::string bundleName = element.GetBundleName(); + int32_t uid = want.GetIntParam(AppExecFwk::Constants::UID, -1); + sptr bundleOption = new NotificationBundleOption(bundleName, uid); + if (bundleOption == nullptr) { + ANS_LOGE("Failed to create bundleOption."); + } + return bundleOption; +} + void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) { auto want = data.GetWant(); @@ -53,11 +66,10 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) ANS_LOGD("OnReceiveEvent action is %{public}s.", action.c_str()); if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { if (callbacks_.onBundleRemoved != nullptr) { - auto element = want.GetElement(); - std::string bundleName = element.GetBundleName(); - int uid = want.GetIntParam(AppExecFwk::Constants::UID, -1); - sptr bundleOption = new NotificationBundleOption(bundleName, uid); - callbacks_.onBundleRemoved(bundleOption); + sptr bundleOption = GetBundleOption(want); + if (bundleOption != nullptr) { + callbacks_.onBundleRemoved(bundleOption); + } } #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON) { @@ -73,7 +85,16 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) NotificationPreferences::GetInstance().InitSettingFromDisturbDB(); } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { int32_t userId = data.GetCode(); - callbacks_.onResourceRemove(userId); + if (callbacks_.onResourceRemove != nullptr) { + callbacks_.onResourceRemove(userId); + } + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { + if (callbacks_.onBundleDataCleared != nullptr) { + sptr bundleOption = GetBundleOption(want); + if (bundleOption != nullptr) { + callbacks_.onBundleDataCleared(bundleOption); + } + } } } } // namespace Notification diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 86cb0965219fb28f58406b19aab0dd682b116af8..625aca8564f04ea4a90312a02b1327265b0bfc8b 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -47,6 +47,7 @@ ohos_unittest("ans_unit_test") { "advanced_notification_service_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", + "mock/mock_access_token_helper.cpp", "mock/mock_bundle_manager_helper.cpp", "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", @@ -63,7 +64,7 @@ ohos_unittest("ans_unit_test") { deps = [ "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", - "//foundation/ace/ace_engine/interfaces/innerkits/ui_service_manager:ui_service_mgr", + "//foundation/arkui/ace_engine/interfaces/inner_api/ui_service_manager:ui_service_mgr", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] @@ -76,22 +77,22 @@ ohos_unittest("ans_unit_test") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:abilitykit_native", "ability_runtime:app_manager", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "ces_standard:cesfwk_innerkits", + "common_event_service:cesfwk_innerkits", "distributeddatamgr:distributeddata_inner", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hitrace_native:libhitrace", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", "multimedia_media_standard:media_client", - "os_account_standard:os_account_innerkits", + "os_account:os_account_innerkits", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "time_native:time_service", diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index f58b8f4e70b1f95b79deeea6b187cff60866e81f..26342a3f1008a67dd7114b652bb1be293e6cadb5 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -96,7 +96,7 @@ public: void OnCanceled(const std::shared_ptr &request) override {} void OnCanceled(const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason) override + const std::shared_ptr &sortingMap, int32_t deleteReason) override {} void OnConsumed(const std::shared_ptr &request) override {} @@ -1602,6 +1602,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11000, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11100, Function | SmallTest | Level1) { + IPCSkeleton::SetCallingTokenID(NON_NATIVE_TOKEN); sptr req = new NotificationRequest(); EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::OTHER); @@ -1617,6 +1618,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11100, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11200, Function | SmallTest | Level1) { + IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); std::string label = "testLabel"; { @@ -1635,6 +1637,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11200, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11300, Function | SmallTest | Level1) { + IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); std::string label = "testLabel"; { @@ -1643,7 +1646,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11300, req->SetLabel(label); EXPECT_EQ(advancedNotificationService_->PublishContinuousTaskNotification(req), (int)ERR_OK); } - IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + IPCSkeleton::SetCallingTokenID(NON_NATIVE_TOKEN); EXPECT_EQ( advancedNotificationService_->CancelContinuousTaskNotification(label, 1), (int)ERR_ANS_NOT_SYSTEM_SERVICE); } diff --git a/services/ans/test/unittest/ans_ut_constant.h b/services/ans/test/unittest/ans_ut_constant.h index 886634b712c7763886178d30c05387d834abc23d..55f5f9d7c7e76cfc364fd07d617243d62a2c967e 100644 --- a/services/ans/test/unittest/ans_ut_constant.h +++ b/services/ans/test/unittest/ans_ut_constant.h @@ -20,9 +20,11 @@ namespace OHOS { namespace Notification { -constexpr int SYSTEM_APP_UID = 100; -constexpr int NON_SYSTEM_APP_UID = 1000; -constexpr int NON_BUNDLE_NAME_UID = 2000; +constexpr uint32_t NATIVE_TOKEN = 0; +constexpr uint32_t NON_NATIVE_TOKEN = 1; +constexpr int32_t SYSTEM_APP_UID = 100; +constexpr int32_t NON_SYSTEM_APP_UID = 1000; +constexpr int32_t NON_BUNDLE_NAME_UID = 2000; const std::string TEST_DEFUALT_BUNDLE = "bundleName"; } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h b/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h index aafcb863794e9ce7f188b80081f6ad94ff8626c3..56591d38ecd7f3cfda4ede0bea42982ca6a8027a 100644 --- a/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h +++ b/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h @@ -16,6 +16,7 @@ #ifndef OHOS_IPC_IPC_SKELETON_H #define OHOS_IPC_IPC_SKELETON_H +#include "accesstoken_kit.h" #include "iremote_object.h" namespace OHOS { @@ -24,38 +25,115 @@ public: IPCSkeleton() = default; ~IPCSkeleton() = default; - // default max is 4, only if you need a customize value + /** + * @brief Set the max number of work thread. + * Default max is 4, only if you need a customize value. + * + * @param maxThreadNum Indicates the max number of work thread + * @return Indicates the result. + */ static bool SetMaxWorkThreadNum(int maxThreadNum); - // join current thread into work loop. + /** + * @brief Join current thread into work loop. + */ static void JoinWorkThread(); - // remove current thread from work loop. + /** + * @brief Remove current thread from work loop. + */ static void StopWorkThread(); + /** + * @brief Get calling pid. + * + * @return Indicates the calling pid. + */ static pid_t GetCallingPid(); + /** + * @brief Get calling uid. + * + * @return Indicates the calling uid. + */ static pid_t GetCallingUid(); + /** + * @brief Get the ID of local device. + * + * @return Indicates the ID of local device. + */ static std::string GetLocalDeviceID(); + static Security::AccessToken::AccessTokenID GetCallingTokenID(); + + /** + * @brief Get the ID of calling device. + * + * @return Indicates the ID of calling device. + */ static std::string GetCallingDeviceID(); + /** + * @brief Whether it is locally calling. + * + * @return Return ture for calling from local, otherwise false. + */ static bool IsLocalCalling(); + /** + * @brief Get the instance. + * + * @return Indicates the instance. + */ static IPCSkeleton &GetInstance(); + /** + * @brief Get the object of context. + * + * @return Indicates the context cobject. + */ static sptr GetContextObject(); + /** + * @brief Set the object of context. + * + * @param object Indicates the context cobject. + * @return Indicates the result. + */ static bool SetContextObject(sptr &object); + /** + * @brief Flush the commands. + * + * @param object Indicates the object. + * @return Indicates the result. + */ static int FlushCommands(IRemoteObject *object); + /** + * @brief Reset calling identity. + * + * @return Indicates the result. + */ static std::string ResetCallingIdentity(); + /** + * @brief Set calling identity. + * + * @param identity Indicates the identity. + * @return Indicates the result. + */ static bool SetCallingIdentity(std::string &identity); + /** + * @brief Set calling uid. + * + * @param uid Indicates the uid. + */ static void SetCallingUid(pid_t uid); + + static void SetCallingTokenID(Security::AccessToken::AccessTokenID callerToken); }; -} // namespace OHOS -#endif // OHOS_IPC_IPC_SKELETON_H +} // namespace OHOS +#endif // OHOS_IPC_IPC_SKELETON_H diff --git a/services/ans/test/unittest/mock/include/mock_single_kv_store.h b/services/ans/test/unittest/mock/include/mock_single_kv_store.h index b682e43151bbd0c60c21ec51decf5460a8b8ee01..475228bbb3755a66d5b5178a6fd1fe0f55d83b74 100644 --- a/services/ans/test/unittest/mock/include/mock_single_kv_store.h +++ b/services/ans/test/unittest/mock/include/mock_single_kv_store.h @@ -33,81 +33,307 @@ namespace DistributedKv { // This class provides put, delete, search, sync and subscribe functions of a key-value store. class AnsTestSingleKvStore : public SingleKvStore { public: + /** + * @brief Get all entries in this store which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntries(const Key &prefixKey, std::vector &entries) const override; + /** + * @brief Get all entries in this store by query. + * + * @param query Indicates the query string. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntriesWithQuery(const std::string &query, std::vector &entries) const override; + /** + * @brief Get all entries in this store by query. + * + * @param query Indicates the query object. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntriesWithQuery(const DataQuery &query, std::vector &entries) const override; + /** + * @brief Get ResultSet in this store which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ virtual Status GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const override; + /** + * @brief Get ResultSet in this store by Query. + * + * @param query Indicates the query string. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ virtual Status GetResultSetWithQuery(const std::string &query, std::shared_ptr &resultSet) const override; + /** + * @brief Get ResultSet in this store by Query. + * + * @param query Indicates the query object. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ virtual Status GetResultSetWithQuery(const DataQuery &query, std::shared_ptr &resultSet) const override; + /** + * @brief Close the ResultSet returned by GetResultSet. + * + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status CloseResultSet(std::shared_ptr &resultSet) override; + /** + * @brief Get the number of result by query. + * + * @param query Indicates the query string. + * @param result Indicates the result. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status GetCountWithQuery(const std::string &query, int &result) const override; + /** + * @brief Get the number of result by query. + * + * @param query Indicates the query object. + * @param result Indicates the result will be returned in this parameter. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status GetCountWithQuery(const DataQuery &query, int &result) const override; + /** + * @brief Sync store with other devices. This is an asynchronous method, + * sync will fail if there is a syncing operation in progress. + * + * @param deviceIds Indicates the device list to sync. + * @param mode Indicates the sync mode, can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. + * PUSH_PULL will firstly push all not-local store to listed devices, then pull these stores back. + * @param allowedDelayMs Indicates the allowed delay milli-second to sync. default value is 0 for compatibility. + * @return Indicates the status of this Sync operation. + */ virtual Status Sync( const std::vector &deviceIds, SyncMode mode, uint32_t allowedDelayMs = 0) override; + /** + * @brief Remove the device data synced from remote. + * + * @param device Indicates the device id. + * @return Indicates the status of this remove operation. + */ virtual Status RemoveDeviceData(const std::string &device) override; + /** + * @brief Get id of this AppKvStore. + * + * @return Indicates the id of store. + */ virtual StoreId GetStoreId() const override; + /** + * @brief Delete an entry by its key. + * + * @param key Indicates the key of the entry to be deleted. + * @return Indicates the status of this delete operation. + */ virtual Status Delete(const Key &key) override; + /** + * @brief Write a pair of key and value to this store. + * + * @param key Indicates the key of this entry. Should be less than 256 bytes. key will be trimmed before store. + * @param value Indicates the value of this entry. Should be less than (1024 * 1024) bytes. + * @return Indicates the status of this put operation. + */ virtual Status Put(const Key &key, const Value &value) override; + /** + * @brief Get value from AppKvStore by its key. + * + * @param key Indicates the key of this entry. + * @param value Indicates the value will be returned in this parameter. + * @return Indicates the status of this get operation. + */ virtual Status Get(const Key &key, Value &value) override; + /** + * @brief Register change of this kvstore to a client-defined observer. + * observer->OnChange method will be called when store changes. + * One observer can subscribe more than one AppKvStore. + * + * @param subscribeType Indicates the subscribe type. + * OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, + * OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, + * OBSERVER_CHANGES_ALL means both native changes and synced data changes. + * @param observer Indicates the observer to subscribe changes. + * @return Indicates the status of this subscribe operation. + */ virtual Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + /** + * @brief Unregister a kvstore to an observer. + * + * @param subscribeType Indicates the subscribe type. + * Reserved parameter. Current is always SubscribeType::DEFAULT. + * @param observer Indicates the observer to unsubscribe this store. + * @return Indicates the status of this unsubscribe operation. + */ virtual Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + /** + * @brief Register message for sync operation. + * + * @param callback Indicates the callback to register. + * @return Indicates the status of this register operation. + */ virtual Status RegisterSyncCallback(std::shared_ptr callback) override; + /** + * @brief Unregister message for sync operation. + * + * @param callback Indicates the callback to register. + * @return Indicates the status of this register operation. + */ virtual Status UnRegisterSyncCallback() override; + /** + * @brief See Put, PutBatch put a list of entries to kvstore, + * all entries will be put in a transaction, + * if entries contains invalid entry, PutBatch will all fail. + * + * @param entries Indicates the entries. + * The entries's size should be less than 128 and memory size must be less than IPC transport limit. + * @return Indicates the status of this register operation. + */ virtual Status PutBatch(const std::vector &entries) override; + /** + * @brief Delete a list of entries in the kvstore, + * delete key not exist still return success, + * key length should not be greater than 256, and can not be empty. + * If keys contains invalid key, all delete will fail. + * + * @param keys Indicates the list of keys. + * The keys memory size should not be greater than IPC transport limit, and can not be empty. + * @return Indicates the status of this register operation. + */ virtual Status DeleteBatch(const std::vector &keys) override; + /** + * @brief Start transaction. + * All changes to this kvstore will be in a same transaction and will not change the store until Commit() or + * Rollback() is called. + * Before this transaction is committed or rollbacked, all attemption to close this store will fail. + * + * @return Indicates the status of this operation. + */ virtual Status StartTransaction() override; + /** + * @brief Commit current transaction. All changes to this store will be done after calling this method. + * Any calling of this method outside a transaction will fail. + * + * @return Indicates the status of this operation. + */ virtual Status Commit() override; + /** + * @brief Rollback current transaction. + * All changes to this store during this transaction will be rollback after calling this method. + * Any calling of this method outside a transaction will fail. + * + * @return Indicates the status of this operation. + */ virtual Status Rollback() override; + /** + * @brief Set synchronization parameters of this store. + * + * @param syncParam Indicates the sync policy parameter. + * @return Indicates the status of this operation. + */ virtual Status SetSyncParam(const KvSyncParam &syncParam) override; + /** + * @brief Get synchronization parameters of this store. + * + * @param syncParam Indicates the sync policy parameter. + * @return Indicates the status of this operation. + */ virtual Status GetSyncParam(KvSyncParam &syncParam) override; + /** + * @brief Set capability parameters of this store. + * + * @param enabled Indicates the capability Enabled status. + * @return Indicates the status of this operation. + */ virtual Status SetCapabilityEnabled(bool enabled) const override; + /** + * @brief Set capability parameters of this store. + * + * @param localLabels Indicates the labels of local. + * @param remoteSupportLabels Indicates the labels of remote support. + * @return Indicates the status of this operation. + */ virtual Status SetCapabilityRange(const std::vector &localLabels, const std::vector &remoteSupportLabels) const override; + /** + * @brief Get security level. + * + * @param securityLevel Indicates the security level. + * @return Indicates the status of this operation. + */ virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const override; + /** + * @brief Sync store with other devices only syncing the data which is satisfied with the condition. + * This is an asynchronous method, sync will fail if there is a syncing operation in progress. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * @param mode Indicates the sync mode, can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUSH_PULL. + * PUSH_PULL will firstly push all not-local store to listed devices, then pull these stores back. + * @return Indicates the status of this operation. + */ virtual Status SyncWithCondition(const std::vector &deviceIds, SyncMode mode, const DataQuery &query, std::shared_ptr syncCallback) override; + /** + * @brief Subscribe store with other devices consistently Synchronize the data which is satisfied + * with the condition. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * + * @return Indicates the status of this operation. + */ virtual Status SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; + /** + * @brief UnSubscribe store with other devices which is satisfied with the condition. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * @return Indicates the status of this UnSubscribe operation. + */ virtual Status UnsubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; - Status GetKvStoreSnapshot(std::shared_ptr observer, - std::shared_ptr &snapshot) const override; - - Status ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) override; - - Status Clear() override; protected: KVSTORE_API virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &output) override; }; diff --git a/services/ans/test/unittest/mock/mock_access_token_helper.cpp b/services/ans/test/unittest/mock/mock_access_token_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f3cba40f0988a31a08c6696fa5b944a7fb47d92 --- /dev/null +++ b/services/ans/test/unittest/mock/mock_access_token_helper.cpp @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#include "access_token_helper.h" +#include "ans_ut_constant.h" + +namespace OHOS { +namespace Notification { +bool AccessTokenHelper::VerifyCallerPermission( + const Security::AccessToken::AccessTokenID &tokenCaller, const std::string &permission) +{ + return true; +} + +bool AccessTokenHelper::VerifyNativeToken(const Security::AccessToken::AccessTokenID &callerToken) +{ + return callerToken == NATIVE_TOKEN; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp index 6eba48ba6f8b9a28b9b77136e946362d3b88ca52..fa0d3eb61358b4024540942ee05530f1f1b724ac 100644 --- a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -46,6 +46,11 @@ bool BundleManagerHelper::IsSystemApp(int uid) return (uid == SYSTEM_APP_UID); } +bool BundleManagerHelper::CheckApiCompatibility(const sptr &bundleOption) +{ + return true; +} + bool BundleManagerHelper::GetBundleInfoByBundleName( const std::string bundle, const int32_t userId, AppExecFwk::BundleInfo &bundleInfo) { diff --git a/services/ans/test/unittest/mock/mock_ipc.cpp b/services/ans/test/unittest/mock/mock_ipc.cpp index 6f08e07f8198df60e90bc15c8f55f0d7abab22bf..dc9c4065d7b82c824e9d8d2cf28417ac9dccb8f1 100644 --- a/services/ans/test/unittest/mock/mock_ipc.cpp +++ b/services/ans/test/unittest/mock/mock_ipc.cpp @@ -21,6 +21,7 @@ using namespace IPC_SINGLE; #endif pid_t uid_ = 1; +Security::AccessToken::AccessTokenID callerToken_ = 0; pid_t IPCSkeleton::GetCallingUid() { @@ -32,8 +33,18 @@ pid_t IPCSkeleton::GetCallingPid() return 1; } +Security::AccessToken::AccessTokenID IPCSkeleton::GetCallingTokenID() +{ + return callerToken_; +} + void IPCSkeleton::SetCallingUid(pid_t uid) { uid_ = uid; } + +void IPCSkeleton::SetCallingTokenID(Security::AccessToken::AccessTokenID callerToken) +{ + callerToken_ = callerToken; +} } // namespace OHOS diff --git a/services/ans/test/unittest/mock/mock_single_kv_store.cpp b/services/ans/test/unittest/mock/mock_single_kv_store.cpp index d58c045a4c8c4d34bac3005dda4478377572f284..68edb372e0020fad87b048626fc3b5f682f1e458 100644 --- a/services/ans/test/unittest/mock/mock_single_kv_store.cpp +++ b/services/ans/test/unittest/mock/mock_single_kv_store.cpp @@ -189,21 +189,5 @@ Status AnsTestSingleKvStore::UnsubscribeWithQuery(const std::vector { return Status::SUCCESS; } - -Status AnsTestSingleKvStore::GetKvStoreSnapshot(std::shared_ptr observer, - std::shared_ptr &snapshot) const -{ - return Status::NOT_SUPPORT; -} - -Status AnsTestSingleKvStore::ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) -{ - return Status::NOT_SUPPORT; -} - -Status AnsTestSingleKvStore::Clear() -{ - return Status::NOT_SUPPORT; -} } // namespace DistributedKv } // namespace OHOS diff --git a/services/distributed/BUILD.gn b/services/distributed/BUILD.gn index 337764a8b9a503fbd1e3e9c34bf50fb8205154ae..86107793a9d0c585b639d1c39d16b8b510cd24b9 100644 --- a/services/distributed/BUILD.gn +++ b/services/distributed/BUILD.gn @@ -46,8 +46,8 @@ ohos_shared_library("libans_distributed") { external_deps = [ "ability_base:want", + "ability_base:zuri", "distributeddatamgr:distributeddata_inner", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/distributed/include/distributed_database.h b/services/distributed/include/distributed_database.h index 6286769a00ce929d2d378975bb0a5148bc771d2d..3508780f513574941455c6d2dadeed06dd201dab 100644 --- a/services/distributed/include/distributed_database.h +++ b/services/distributed/include/distributed_database.h @@ -34,18 +34,93 @@ class DistributedDatabase : private DistributedFlowControl { public: using Entry = DistributedKv::Entry; using DeviceInfo = DistributedKv::DeviceInfo; + + /** + * @brief The constructor. + * + * @param databaseCb Distributed notification info changed callback object. + * @param deviceCb Device connection info changed callback object. + */ DistributedDatabase( std::shared_ptr databaseCb, std::shared_ptr deviceCb); + + /** + * @brief The deconstructor. + */ ~DistributedDatabase(); + /** + * @brief Put a key-value to database. + * + * @param key Indicates the key. + * @param value Indicates the value. + * @return Whether to put key-value success. + */ bool PutToDistributedDB(const std::string &key, const std::string &value); + + /** + * @brief Get the value of its key from database. + * + * @param key Indicates the key. + * @param value Indicates the value. + * @return Whether to get key-value success. + */ bool GetFromDistributedDB(const std::string &key, std::string &value); + + /** + * @brief Get all entries which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param entries Indicates the entries will be returned in this parameter. + * @return Whether to get entries success. + */ bool GetEntriesFromDistributedDB(const std::string &prefixKey, std::vector &entries); + + /** + * @brief Delete a key-value of its key from database. + * + * @param key Indicates the key. + * @return Whether to delete key-value success. + */ bool DeleteToDistributedDB(const std::string &key); + + /** + * @brief Clear all entries which put by specified device. + * + * @param deviceId Indicates the id of specified device. + * @return Whether to clear device entries success. + */ bool ClearDataByDevice(const std::string &deviceId); + + /** + * @brief Get local device id. + * + * @param deviceId Indicates the id of local device. + * @return Whether to get device id success. + */ bool GetLocalDeviceId(std::string &deviceId); + + /** + * @brief Get local device info. + * + * @param localInfo Indicates the infomation of local device. + * @return Whether to get device infomation success. + */ bool GetLocalDeviceInfo(DeviceInfo &localInfo); + + /** + * @brief Get all devices info on the network. + * + * @param deviceList Indicates the infomation list of devices. + * @return Whether to get devices infomation success. + */ bool GetDeviceInfoList(std::vector &deviceList); + + /** + * @brief Recreate the database of distributed notification + * + * @return Whether to recreate the database success. + */ bool RecreateDistributedDB(); private: diff --git a/services/distributed/include/distributed_database_callback.h b/services/distributed/include/distributed_database_callback.h index 672b55617faa0e51359b599f86ec7175aaaff824..2b4764a58ec60e4de75f8619d39d0c0bce794a46 100644 --- a/services/distributed/include/distributed_database_callback.h +++ b/services/distributed/include/distributed_database_callback.h @@ -24,16 +24,28 @@ namespace OHOS { namespace Notification { class DistributedDatabaseCallback : public DistributedKv::KvStoreObserver { public: + /** + * @brief Distributed notification Key-Value changed callback function structure. + */ struct IDatabaseChange { std::function OnInsert; std::function OnUpdate; std::function OnDelete; }; + + /** + * @brief The constructor. + * + * @param callback Key-Value changed callback. + */ explicit DistributedDatabaseCallback(const IDatabaseChange &callback); + + /** + * @brief The deconstructor. + */ ~DistributedDatabaseCallback(); + private: - void OnChange(const DistributedKv::ChangeNotification &changeNotification, - std::shared_ptr snapshot) override; void OnChange(const DistributedKv::ChangeNotification &changeNotification) override; private: diff --git a/services/distributed/include/distributed_device_callback.h b/services/distributed/include/distributed_device_callback.h index 33000b45604becf489bb938bade6d95f8339346f..86ac2c600f0b72f802b0615660e1d8d829aea2c2 100644 --- a/services/distributed/include/distributed_device_callback.h +++ b/services/distributed/include/distributed_device_callback.h @@ -24,11 +24,24 @@ namespace OHOS { namespace Notification { class DistributedDeviceCallback : public DistributedKv::DeviceStatusChangeListener { public: + /** + * @brief Device connection status changed callback function structure. + */ struct IDeviceChange { std::function OnConnected; std::function OnDisconnected; }; + + /** + * @brief The constructor. + * + * @param callback Device connection status changed callback. + */ explicit DistributedDeviceCallback(const IDeviceChange &callback); + + /** + * @brief The deconstructor. + */ ~DistributedDeviceCallback(); private: diff --git a/services/distributed/include/distributed_flow_control.h b/services/distributed/include/distributed_flow_control.h index 435381491d58798e95af0b2718034071acecc74e..90accf6c170cae79f31fa13eca41eb72319b684e 100644 --- a/services/distributed/include/distributed_flow_control.h +++ b/services/distributed/include/distributed_flow_control.h @@ -23,26 +23,54 @@ namespace OHOS { namespace Notification { class DistributedFlowControl { public: - DistributedFlowControl(int kvManagerSecondMaxinum = KVMANAGER_MAXINUM_PER_SECOND, - int kvManagerMinuteMaxinum = KVMANAGER_MAXINUM_PER_MINUTE, - int kvStoreSecondMaxinum = KVSTORE_MAXINUM_PER_SECOND, - int kvStoreMinuteMaxinum = KVSTORE_MAXINUM_PER_MINUTE); + /** + * @brief The constructor. + * + * @param kvManagerSecondMaxinum The maximum number of calls to DistributedKvDataManager interface per second. + * @param kvManagerMinuteMaxinum The maximum number of calls to DistributedKvDataManager interface per minute. + * @param kvStoreSecondMaxinum The maximum number of calls to SingleKvStore interface per second. + * @param kvStoreMinuteMaxinum The maximum number of calls to SingleKvStore interface per minute. + */ + DistributedFlowControl(size_t kvManagerSecondMaxinum = KVMANAGER_MAXINUM_PER_SECOND, + size_t kvManagerMinuteMaxinum = KVMANAGER_MAXINUM_PER_MINUTE, + size_t kvStoreSecondMaxinum = KVSTORE_MAXINUM_PER_SECOND, + size_t kvStoreMinuteMaxinum = KVSTORE_MAXINUM_PER_MINUTE); + + /** + * @brief Check if DistributedKvDataManager interface flow control can pass. + * + * @return True on passed, otherwise false. + */ bool KvManagerFlowControl(void); + + /** + * @brief Check if SingleKvStore interface flow control can pass. + * + * @return True on passed, otherwise false. + */ bool KvStoreFlowControl(void); + + /** + * @brief Clear DistributedKvDataManager interface flow control count. + */ void KvManagerFlowControlClear(void); + + /** + * @brief Clear SingleKvStore interface flow control count. + */ void KvStoreFlowControlClear(void); protected: - static const int KVMANAGER_MAXINUM_PER_SECOND = 50; - static const int KVMANAGER_MAXINUM_PER_MINUTE = 500; - static const int KVSTORE_MAXINUM_PER_SECOND = 1000; - static const int KVSTORE_MAXINUM_PER_MINUTE = 10000; + static const size_t KVMANAGER_MAXINUM_PER_SECOND = 50; + static const size_t KVMANAGER_MAXINUM_PER_MINUTE = 500; + static const size_t KVSTORE_MAXINUM_PER_SECOND = 1000; + static const size_t KVSTORE_MAXINUM_PER_MINUTE = 10000; private: - int kvManagerSecondMaxinum_; - int kvManagerMinuteMaxinum_; - int kvStoreSecondMaxinum_; - int kvStoreMinuteMaxinum_; + size_t kvManagerSecondMaxinum_; + size_t kvManagerMinuteMaxinum_; + size_t kvStoreSecondMaxinum_; + size_t kvStoreMinuteMaxinum_; std::list kvDataManagerTimestampList_; std::list kvStoreTimestampList_; }; diff --git a/services/distributed/include/distributed_notification_manager.h b/services/distributed/include/distributed_notification_manager.h index edcc0a973a0436d4b231befbd1b239f26c6bfa0d..796a9a54b4d7c89c0aeade42452e9b4842c1bc51 100644 --- a/services/distributed/include/distributed_notification_manager.h +++ b/services/distributed/include/distributed_notification_manager.h @@ -32,6 +32,9 @@ namespace OHOS { namespace Notification { class DistributedNotificationManager : public DelayedSingleton { public: + /** + * @brief Distributed notification callback function for remote device. + */ struct IDistributedCallback { std::function &request)> @@ -44,17 +47,86 @@ public: OnDelete; }; + /** + * @brief Publishes a local notification to remote device. + * + * @param bundleName Indicates the bundle name of the application whose notifications are to be publish. + * @param label Indicates the label of the notifications. + * @param id Indicates the bundle uid of the application whose notifications are to be publish. + * @param request Indicates the NotificationRequest object for setting the notification content. + * @return ErrCode Returns the publish result. + */ ErrCode Publish( const std::string &bundleName, const std::string &label, int32_t id, const sptr &request); + + /** + * @brief Updates infomation of local notification to remote device. + * + * @param bundleName Indicates the bundle name of the application whose notifications are to be update. + * @param label Indicates the label of the notifications. + * @param id Indicates the bundle uid of the application whose notifications are to be update. + * @param request Indicates the NotificationRequest object for setting the notification content. + * @return ErrCode Returns the update result. + */ ErrCode Update( const std::string &bundleName, const std::string &label, int32_t id, const sptr &request); + + /** + * @brief Removes a local notification. + * + * @param bundleName Indicates the bundle name of the application whose notifications are to be remove. + * @param label Indicates the label of the notifications. + * @param id Indicates the bundle uid of the application whose notifications are to be remove. + * @return ErrCode Returns the remove result. + */ ErrCode Delete(const std::string &bundleName, const std::string &label, int32_t id); + + /** + * @brief Removes a remote notification. + * + * @param deviceId Indicates the ID of the device. + * @param bundleName Indicates the bundle name of the application whose notifications are to be remove. + * @param label Indicates the label of the notifications. + * @param id Indicates the bundle uid of the application whose notifications are to be remove. + * @return ErrCode Returns the remove result. + */ ErrCode DeleteRemoteNotification( const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id); + + /** + * @brief Register callback of distributed notification changed. + * + * @param callback Indicates the callback structure + * @return ErrCode Returns the register result. + */ ErrCode RegisterCallback(const IDistributedCallback &callback); + + /** + * @brief Unregister Callback of Distributed notification changed. + * + * @return ErrCode Returns the unregister result. + */ ErrCode UngegisterCallback(void); + + /** + * @brief Get all distributed notification in database. + * + * @param requestList Indicates the list of NotificationRequest object for setting the notification content. + * @return ErrCode Returns Get all distributed notification result. + */ ErrCode GetCurrentDistributedNotification(std::vector> &requestList); + + /** + * @brief Get local device info. + * + * @param deviceInfo Indicates the infomation of local device. + * @return ErrCode Returns get device infomation result. + */ ErrCode GetLocalDeviceInfo(DistributedDatabase::DeviceInfo &deviceInfo); + + /** + * @brief Obtains the death event of the Distributed KvStore service. + */ ErrCode OnDistributedKvStoreDeathRecipient(); private: diff --git a/services/distributed/include/distributed_preferences.h b/services/distributed/include/distributed_preferences.h index 44d6d8991b69100e42bae83c54711b11040c14c2..4f04368882d84d916df5db877040ed9a09614af5 100644 --- a/services/distributed/include/distributed_preferences.h +++ b/services/distributed/include/distributed_preferences.h @@ -31,11 +31,53 @@ namespace OHOS { namespace Notification { class DistributedPreferences : public DelayedSingleton { public: + /** + * @brief Set whether the device supports distributed notifications. + * + * @param enable Specifies whether to enable the device to support distributed notification. + * @return Returns enable distributed result. + */ ErrCode SetDistributedEnable(bool isEnable); + + /** + * @brief Check if the device supports distributed notification. + * + * @param enabled True if the device supports distributed notification; false otherwise. + * @return Returns is distributed enabled result. + */ ErrCode GetDistributedEnable(bool &isEnable); + + /** + * @brief Set whether an application supports distributed notifications. + * + * @param bundleOption Indicates the bundle name and uid of an application. + * @param enabled Specifies whether to enable an application to support distributed notification. + * @return Returns enable distributed by bundle result. + */ ErrCode SetDistributedBundleEnable(const sptr &bundleOption, bool isEnable); + + /** + * @brief Check whether an application supports distributed notifications. + * + * @param bundleOption Indicates the bundle name and uid of an application. + * @param enabled True if the application supports distributed notification; false otherwise. + * @return Returns is distributed enabled by bundle result. + */ ErrCode GetDistributedBundleEnable(const sptr &bundleOption, bool &isEnable); + + /** + * @brief Remove the setting of whether the application supports distributed notification. + * + * @param bundleOption Indicates the bundle name and uid of an application. + * @return Returns remove the setting result. + */ ErrCode DeleteDistributedBundleInfo(const sptr &bundleOption); + + /** + * @brief Remove all distributed enabled setting info from DB. + * + * @return Returns remove the setting result. + */ ErrCode ClearDataInRestoreFactorySettings(); private: diff --git a/services/distributed/include/distributed_preferences_database.h b/services/distributed/include/distributed_preferences_database.h index 92b80d1f2d0059ebcd4d7b88d2e9feb184421a39..9668c349a0d89b02d74780d54238d3566eac5b80 100644 --- a/services/distributed/include/distributed_preferences_database.h +++ b/services/distributed/include/distributed_preferences_database.h @@ -36,10 +36,46 @@ public: DistributedPreferencesDatabase(); ~DistributedPreferencesDatabase(); + /** + * @brief Put a key-value to database. + * + * @param key Indicates the key. + * @param value Indicates the value. + * @return Whether to put key-value success. + */ bool PutToDistributedDB(const std::string &key, const std::string &value); + + /** + * @brief Get the value of its key from database. + * + * @param key Indicates key. + * @param value Indicates value. + * @return Whether to get key-value success. + */ bool GetFromDistributedDB(const std::string &key, std::string &value); + + /** + * @brief Get all entries which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param entries Indicates the entries will be returned in this parameter. + * @return Whether to get entries success. + */ bool GetEntriesFromDistributedDB(const std::string &prefixKey, std::vector &entries); + + /** + * @brief Delete a key-value of its key from database. + * + * @param key Indicates the key. + * @return Whether to delete key-value success. + */ bool DeleteToDistributedDB(const std::string &key); + + /** + * @brief Clear all data in database and Delete the database. + * + * @return Whether to clear database success. + */ bool ClearDatabase(void); private: diff --git a/services/distributed/include/distributed_preferences_info.h b/services/distributed/include/distributed_preferences_info.h index 840d3c95f2dd05b054d5837b05ce7df7c26b6a53..16288af7ea189f4e9e21c8e5a7c6271e9ba98657 100644 --- a/services/distributed/include/distributed_preferences_info.h +++ b/services/distributed/include/distributed_preferences_info.h @@ -25,10 +25,53 @@ class DistributedPreferencesInfo { public: DistributedPreferencesInfo(); ~DistributedPreferencesInfo(); + + /** + * @brief Set whether the device supports distributed notifications. + * + * @param enable Specifies whether to enable the device to support distributed notification. + */ void SetDistributedEnable(bool enable); + + /** + * @brief Check if the device supports distributed notification. + * + * @return True if the device supports distributed notification; false otherwise. + */ bool GetDistributedEnable(void); + + /** + * @brief Set whether an application supports distributed notifications. + * + * @param bundleOption Indicates the bundle name and uid of an application. + * @param enabled Specifies whether to enable an application to support distributed notification. + * @return Returns enable distributed by bundle result. + */ + + /** + * @brief Set whether an application supports distributed notifications. + * + * @param bundleName Indicates the bundle name of an application. + * @param uid Indicates the uid of an application. + * @param enable Specifies whether to enable an application to support distributed notification. + */ void SetDistributedBundleEnable(const std::string &bundleName, int32_t uid, bool enable); + + /** + * @brief Check whether an application supports distributed notifications. + * + * @param bundleName Indicates the bundle name of an application. + * @param uid Indicates the uid of an application. + * @return True if the application supports distributed notification; false otherwise. + */ bool GetDistributedBundleEnable(const std::string &bundleName, int32_t uid); + + /** + * @brief Remove the setting of whether the application supports distributed notification. + * + * @param bundleName Indicates the bundle name of an application. + * @param uid Indicates the uid of an application. + */ void DeleteDistributedBundleInfo(const std::string &bundleName, int32_t uid); private: diff --git a/services/distributed/include/distributed_screen_status_manager.h b/services/distributed/include/distributed_screen_status_manager.h index 9ac03bb99f9eca015b7a88ba2fe9df324179d461..049fe52a99ac73fc91e89383dd95479d047213fb 100644 --- a/services/distributed/include/distributed_screen_status_manager.h +++ b/services/distributed/include/distributed_screen_status_manager.h @@ -31,7 +31,20 @@ namespace Notification { class DistributedScreenStatusManager : private DistributedFlowControl, public DelayedSingleton { public: + /** + * @brief Check if any other device screen is on. + * + * @param isUsing True for any other device screen is on, otherwise false. + * @return Returns the error code. + */ ErrCode CheckRemoteDevicesIsUsing(bool &isUsing); + + /** + * @brief Set screen status of local device. + * + * @param screenOn Indicates the local device screen status. + * @return Returns the error code. + */ ErrCode SetLocalScreenStatus(bool screenOn); private: diff --git a/services/distributed/src/distributed_database.cpp b/services/distributed/src/distributed_database.cpp index 4b60727714d2f98101373a90123b666f4bdbf5ca..8dccefc9b6fa53d5b99ce9c42f327eb4667e12f5 100644 --- a/services/distributed/src/distributed_database.cpp +++ b/services/distributed/src/distributed_database.cpp @@ -69,6 +69,7 @@ void DistributedDatabase::GetKvStore(void) DistributedKv::Options options; options.createIfMissing = true; + options.securityLevel = DistributedKv::SecurityLevel::S1; options.autoSync = true; options.kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION; DistributedKv::AppId appId = {.appId = APP_ID}; diff --git a/services/distributed/src/distributed_database_callback.cpp b/services/distributed/src/distributed_database_callback.cpp index 53bab4807e9034fde3c293f43d2a7a85b3eee165..ee088ec92a8561a6a712215c43b71729f3531c61 100644 --- a/services/distributed/src/distributed_database_callback.cpp +++ b/services/distributed/src/distributed_database_callback.cpp @@ -25,16 +25,9 @@ DistributedDatabaseCallback::DistributedDatabaseCallback(const IDatabaseChange & DistributedDatabaseCallback::~DistributedDatabaseCallback() {} -void DistributedDatabaseCallback::OnChange(const DistributedKv::ChangeNotification &changeNotification, - std::shared_ptr snapshot) -{ - ANS_LOGI("%{public}s start", __FUNCTION__); - return; -} void DistributedDatabaseCallback::OnChange(const DistributedKv::ChangeNotification &changeNotification) { ANS_LOGI("%{public}s start", __FUNCTION__); - // const std::vector entryList; if (callback_.OnInsert) { const std::vector &entryList = changeNotification.GetInsertEntries(); diff --git a/services/distributed/src/distributed_device_callback.cpp b/services/distributed/src/distributed_device_callback.cpp index 6a556ec8a0b1cb420f1215a39d02aa21f8944cb4..d598507838722597ed9e8218a92eb6b8dbc916b5 100644 --- a/services/distributed/src/distributed_device_callback.cpp +++ b/services/distributed/src/distributed_device_callback.cpp @@ -36,7 +36,6 @@ void DistributedDeviceCallback::OnDeviceChanged( } if (type == DistributedKv::DeviceChangeType::DEVICE_OFFLINE) { - ANS_LOGI("device %{public}s is OFFLINE", info.deviceId.c_str()); if (callback_.OnDisconnected) { callback_.OnDisconnected(info.deviceId); } diff --git a/services/distributed/src/distributed_flow_control.cpp b/services/distributed/src/distributed_flow_control.cpp index fabe5b589777f392bc4f4ac568a45253657f65a7..de58271022ef6cb13dbe6004ca2c101b8d629274 100644 --- a/services/distributed/src/distributed_flow_control.cpp +++ b/services/distributed/src/distributed_flow_control.cpp @@ -18,7 +18,8 @@ namespace OHOS { namespace Notification { DistributedFlowControl::DistributedFlowControl( - int kvManagerSecondMaxinum, int kvManagerMinuteMaxinum, int kvStoreSecondMaxinum, int kvStoreMinuteMaxinum) + size_t kvManagerSecondMaxinum, size_t kvManagerMinuteMaxinum, size_t kvStoreSecondMaxinum, + size_t kvStoreMinuteMaxinum) : kvManagerSecondMaxinum_(kvManagerSecondMaxinum), kvManagerMinuteMaxinum_(kvManagerMinuteMaxinum), kvStoreSecondMaxinum_(kvStoreSecondMaxinum), @@ -32,12 +33,12 @@ bool DistributedFlowControl::KvManagerFlowControl(void) return now - value > std::chrono::minutes(1); }); - int listSize = kvStoreTimestampList_.size(); + size_t listSize = kvStoreTimestampList_.size(); if (listSize >= kvManagerMinuteMaxinum_) { return false; } - int count = 0; + size_t count = 0; for (auto value : kvDataManagerTimestampList_) { if (now - value > std::chrono::seconds(1)) { if (count >= kvManagerSecondMaxinum_) { @@ -60,12 +61,12 @@ bool DistributedFlowControl::KvStoreFlowControl(void) return now - value > std::chrono::minutes(1); }); - int listSize = kvStoreTimestampList_.size(); + size_t listSize = kvStoreTimestampList_.size(); if (listSize >= kvStoreMinuteMaxinum_) { return false; } - int count = 0; + size_t count = 0; for (auto value : kvStoreTimestampList_) { if (now - value > std::chrono::seconds(1)) { if (count >= kvStoreSecondMaxinum_) { diff --git a/services/distributed/src/distributed_notification_manager.cpp b/services/distributed/src/distributed_notification_manager.cpp index be2dba32af65c19d111c4783ef1904f6560a2528..26fb43a8d8eacd32e168442c756ed9144e3b6d87 100644 --- a/services/distributed/src/distributed_notification_manager.cpp +++ b/services/distributed/src/distributed_notification_manager.cpp @@ -19,6 +19,7 @@ #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "ans_watchdog.h" namespace OHOS { namespace Notification { @@ -30,6 +31,7 @@ DistributedNotificationManager::DistributedNotificationManager() { runner_ = OHOS::AppExecFwk::EventRunner::Create(); handler_ = std::make_shared(runner_); + AnsWatchdog::AddHandlerThread(handler_, runner_); DistributedDatabaseCallback::IDatabaseChange databaseCallback = { .OnInsert = std::bind(&DistributedNotificationManager::OnDatabaseInsert, @@ -141,7 +143,7 @@ void DistributedNotificationManager::OnDatabaseInsert( } sptr request = - NotificationJsonConverter::ConvertFromJosnString(value); + NotificationJsonConverter::ConvertFromJsonString(value); if (request == nullptr) { ANS_LOGE("convert json to request failed. key:%{public}s", key.c_str()); return; @@ -167,7 +169,7 @@ void DistributedNotificationManager::OnDatabaseUpdate( } sptr request = - NotificationJsonConverter::ConvertFromJosnString(value); + NotificationJsonConverter::ConvertFromJsonString(value); if (request == nullptr) { ANS_LOGE("convert json to request failed. key:%{public}s", key.c_str()); return; @@ -282,7 +284,7 @@ ErrCode DistributedNotificationManager::Publish( } std::string value; - if (!NotificationJsonConverter::ConvertToJosnString(request, value)) { + if (!NotificationJsonConverter::ConvertToJsonString(request, value)) { ANS_LOGE("convert request to json failed. key:%{public}s", key.c_str()); return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; } @@ -306,7 +308,7 @@ ErrCode DistributedNotificationManager::Update( } std::string value; - if (!NotificationJsonConverter::ConvertToJosnString(request, value)) { + if (!NotificationJsonConverter::ConvertToJsonString(request, value)) { ANS_LOGE("convert request to json failed. key:%{public}s", key.c_str()); return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; } @@ -382,7 +384,7 @@ ErrCode DistributedNotificationManager::GetCurrentDistributedNotification( } sptr request = - NotificationJsonConverter::ConvertFromJosnString(index.value.ToString()); + NotificationJsonConverter::ConvertFromJsonString(index.value.ToString()); if (request == nullptr) { ANS_LOGE("convert json to request failed. key:%{public}s", index.key.ToString().c_str()); continue; diff --git a/services/distributed/src/distributed_preferences.cpp b/services/distributed/src/distributed_preferences.cpp index 551fb0f1c605aa46f6326d96574c9e2f511a6f46..ba469f54d32fa6172d527643a188c6414242c719 100644 --- a/services/distributed/src/distributed_preferences.cpp +++ b/services/distributed/src/distributed_preferences.cpp @@ -59,7 +59,7 @@ bool DistributedPreferences::InitDistributedAllInfo(void) } if (resolveKey.isMainKey) { - int value = atoi(entry.value.ToString().data()); + int32_t value = atoi(entry.value.ToString().data()); preferencesInfo_->SetDistributedEnable(static_cast(value)); } else { preferencesInfo_->SetDistributedBundleEnable( @@ -78,8 +78,10 @@ void DistributedPreferences::GetDistributedMainKey(std::string &key) void DistributedPreferences::GetDistributedBundleKey( const sptr &bundleOption, std::string &key) { - key = DISTRIBUTED_LABEL + DELIMITER + BUNDLE_LABEL + DELIMITER + bundleOption->GetBundleName() + DELIMITER + - std::to_string(bundleOption->GetUid()); + if (bundleOption) { + key = DISTRIBUTED_LABEL + DELIMITER + BUNDLE_LABEL + DELIMITER + bundleOption->GetBundleName() + DELIMITER + + std::to_string(bundleOption->GetUid()); + } } bool DistributedPreferences::ResolveDistributedKey(const std::string &key, ResolveKey &resolveKey) diff --git a/services/distributed/src/distributed_screen_status_manager.cpp b/services/distributed/src/distributed_screen_status_manager.cpp index a1dddb7bd93e9442aef5310dfe5d8c020d2c279b..dfd721e4175856fb6a0f3ad2ba504f95a67d3e98 100644 --- a/services/distributed/src/distributed_screen_status_manager.cpp +++ b/services/distributed/src/distributed_screen_status_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -183,9 +183,8 @@ ErrCode DistributedScreenStatusManager::CheckRemoteDevicesIsUsing(bool &isUsing) for (auto entry : entries) { std::string key = entry.key.ToString(); std::string deviceId = key.substr(0, key.find_first_of(DELIMITER)); - ANS_LOGD("key-deviceId:%{public}s, value:%{public}s", deviceId.c_str(), entry.value.ToString().c_str()); + ANS_LOGD("value:%{public}s", entry.value.ToString().c_str()); for (auto devInfo : devInfoList) { - ANS_LOGD("list-deviceId:%{public}s", devInfo.deviceId.c_str()); if (devInfo.deviceId == deviceId) { isUsing = isUsing || (entry.value.ToString() == SCREEN_STATUS_VALUE_ON); break; diff --git a/services/distributed/test/unittest/BUILD.gn b/services/distributed/test/unittest/BUILD.gn index df3f579e28736f902386803132c5b84f9325f3bb..216faf743bfeeb6d88be67aafc4630f4114f8657 100644 --- a/services/distributed/test/unittest/BUILD.gn +++ b/services/distributed/test/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -50,8 +50,6 @@ ohos_unittest("ans_distributed_unit_test") { "${services_path}/distributed/test/unittest/mock/mock_change_notification.cpp", "${services_path}/distributed/test/unittest/mock/mock_distributed_kv_data_manager.cpp", "${services_path}/distributed/test/unittest/mock/mock_event_handler.cpp", - "${services_path}/distributed/test/unittest/mock/mock_event_runner.cpp", - "${services_path}/distributed/test/unittest/mock/mock_inner_event.cpp", ] configs = [ @@ -69,9 +67,10 @@ ohos_unittest("ans_distributed_unit_test") { external_deps = [ "ability_base:base", "ability_base:want", + "ability_base:zuri", "bundle_framework:appexecfwk_base", "distributeddatamgr:distributeddata_inner", - "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hitrace_native:libhitrace", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/distributed/test/unittest/distributed_database_test.cpp b/services/distributed/test/unittest/distributed_database_test.cpp index f94a86995b037121c46699b1fb0f8f63033e66d5..329297a7335c448291022c70584a8394ee20b4c3 100644 --- a/services/distributed/test/unittest/distributed_database_test.cpp +++ b/services/distributed/test/unittest/distributed_database_test.cpp @@ -169,7 +169,7 @@ HWTEST_F(DistributedDatabaseTest, GetLocalDeviceId_00100, Function | SmallTest | /** * @tc.name : DistributedDatabase_GetLocalDeviceInfo_00100 * @tc.number : GetLocalDeviceInfo_00100 - * @tc.desc : Get local device infomation. + * @tc.desc : Get local device information. */ HWTEST_F(DistributedDatabaseTest, GetLocalDeviceInfo_00100, Function | SmallTest | Level1) { @@ -181,7 +181,7 @@ HWTEST_F(DistributedDatabaseTest, GetLocalDeviceInfo_00100, Function | SmallTest /** * @tc.name : DistributedDatabase_GetDeviceInfoList_00100 * @tc.number : GetDeviceInfoList_00100 - * @tc.desc : Get infomations for all devices. + * @tc.desc : Get informations for all devices. */ HWTEST_F(DistributedDatabaseTest, GetDeviceInfoList_00100, Function | SmallTest | Level1) { diff --git a/services/distributed/test/unittest/distributed_notification_manager_test.cpp b/services/distributed/test/unittest/distributed_notification_manager_test.cpp index c6cac5a4cf871d27f50b2b6dd7ace51a1b93ca8d..e4ab49cf0028b9dae973cc471fe5faf479f53c01 100644 --- a/services/distributed/test/unittest/distributed_notification_manager_test.cpp +++ b/services/distributed/test/unittest/distributed_notification_manager_test.cpp @@ -173,7 +173,7 @@ HWTEST_F(DistributedNotificationManagerTest, Distributed_Get_Current_Notificatio /** * @tc.name : Distributed_Get_Local_DeviceInfo_00100 * @tc.number : Distributed_Get_Local_DeviceInfo_00100 - * @tc.desc : Get local distributed device infomation. + * @tc.desc : Get local distributed device information. */ HWTEST_F(DistributedNotificationManagerTest, Distributed_Get_Local_DeviceInfo_00100, Function | SmallTest | Level1) { diff --git a/services/distributed/test/unittest/mock/ans_test_single_kv_store.cpp b/services/distributed/test/unittest/mock/ans_test_single_kv_store.cpp index 6ae2fbf1ee9ada9215bd1d13e3ea5e3edd6ed3b3..714cec3856e2f26c9703948094821386f118385d 100644 --- a/services/distributed/test/unittest/mock/ans_test_single_kv_store.cpp +++ b/services/distributed/test/unittest/mock/ans_test_single_kv_store.cpp @@ -184,22 +184,6 @@ Status AnsTestSingleKvStore::UnsubscribeWithQuery(const std::vector return Status::SUCCESS; } -Status AnsTestSingleKvStore::GetKvStoreSnapshot( - std::shared_ptr observer, std::shared_ptr &snapshot) const -{ - return Status::NOT_SUPPORT; -} - -Status AnsTestSingleKvStore::ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) -{ - return Status::NOT_SUPPORT; -} - -Status AnsTestSingleKvStore::Clear() -{ - return Status::NOT_SUPPORT; -} - Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &output) { return Status::SUCCESS; diff --git a/services/distributed/test/unittest/mock/ans_test_single_kv_store.h b/services/distributed/test/unittest/mock/ans_test_single_kv_store.h index e930fde5d0ed25e7b57f489fe447471e26ab22a7..86a185ccf065bbba112b63cb4abc22fcdbe68249 100644 --- a/services/distributed/test/unittest/mock/ans_test_single_kv_store.h +++ b/services/distributed/test/unittest/mock/ans_test_single_kv_store.h @@ -33,82 +33,307 @@ namespace DistributedKv { // This class provides put, delete, search, sync and subscribe functions of a key-value store. class AnsTestSingleKvStore : public SingleKvStore { public: + /** + * @brief Get all entries in this store which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntries(const Key &prefixKey, std::vector &entries) const override; + /** + * @brief Get all entries in this store by query. + * + * @param query Indicates the query string. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntriesWithQuery(const std::string &query, std::vector &entries) const override; + /** + * @brief Get all entries in this store by query. + * + * @param query Indicates the query object. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntriesWithQuery(const DataQuery &query, std::vector &entries) const override; + /** + * @brief Get ResultSet in this store which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ virtual Status GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const override; - virtual Status GetResultSetWithQuery( - const std::string &query, std::shared_ptr &resultSet) const override; - - virtual Status GetResultSetWithQuery( - const DataQuery &query, std::shared_ptr &resultSet) const override; - + /** + * @brief Get ResultSet in this store by Query. + * + * @param query Indicates the query string. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ + virtual Status GetResultSetWithQuery(const std::string &query, + std::shared_ptr &resultSet) const override; + + /** + * @brief Get ResultSet in this store by Query. + * + * @param query Indicates the query object. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ + virtual Status GetResultSetWithQuery(const DataQuery &query, + std::shared_ptr &resultSet) const override; + + /** + * @brief Close the ResultSet returned by GetResultSet. + * + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status CloseResultSet(std::shared_ptr &resultSet) override; + /** + * @brief Get the number of result by query. + * + * @param query Indicates the query string. + * @param result Indicates the result. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status GetCountWithQuery(const std::string &query, int &result) const override; + /** + * @brief Get the number of result by query. + * + * @param query Indicates the query object. + * @param result Indicates the result will be returned in this parameter. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status GetCountWithQuery(const DataQuery &query, int &result) const override; + /** + * @brief Sync store with other devices. This is an asynchronous method, + * sync will fail if there is a syncing operation in progress. + * + * @param deviceIds Indicates the device list to sync. + * @param mode Indicates the sync mode, can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. + * PUSH_PULL will firstly push all not-local store to listed devices, then pull these stores back. + * @param allowedDelayMs Indicates the allowed delay milli-second to sync. default value is 0 for compatibility. + * @return Indicates the status of this Sync operation. + */ virtual Status Sync( const std::vector &deviceIds, SyncMode mode, uint32_t allowedDelayMs = 0) override; + /** + * @brief Remove the device data synced from remote. + * + * @param device Indicates the device id. + * @return Indicates the status of this remove operation. + */ virtual Status RemoveDeviceData(const std::string &device) override; + /** + * @brief Get id of this AppKvStore. + * + * @return Indicates the id of store. + */ virtual StoreId GetStoreId() const override; + /** + * @brief Delete an entry by its key. + * + * @param key Indicates the key of the entry to be deleted. + * @return Indicates the status of this delete operation. + */ virtual Status Delete(const Key &key) override; + /** + * @brief Write a pair of key and value to this store. + * + * @param key Indicates the key of this entry. Should be less than 256 bytes. key will be trimmed before store. + * @param value Indicates the value of this entry. Should be less than (1024 * 1024) bytes. + * @return Indicates the status of this put operation. + */ virtual Status Put(const Key &key, const Value &value) override; + /** + * @brief Get value from AppKvStore by its key. + * + * @param key Indicates the key of this entry. + * @param value Indicates the value will be returned in this parameter. + * @return Indicates the status of this get operation. + */ virtual Status Get(const Key &key, Value &value) override; + /** + * @brief Register change of this kvstore to a client-defined observer. + * observer->OnChange method will be called when store changes. + * One observer can subscribe more than one AppKvStore. + * + * @param subscribeType Indicates the subscribe type. + * OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, + * OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, + * OBSERVER_CHANGES_ALL means both native changes and synced data changes. + * @param observer Indicates the observer to subscribe changes. + * @return Indicates the status of this subscribe operation. + */ virtual Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + /** + * @brief Unregister a kvstore to an observer. + * + * @param subscribeType Indicates the subscribe type. + * Reserved parameter. Current is always SubscribeType::DEFAULT. + * @param observer Indicates the observer to unsubscribe this store. + * @return Indicates the status of this unsubscribe operation. + */ virtual Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + /** + * @brief Register message for sync operation. + * + * @param callback Indicates the callback to register. + * @return Indicates the status of this register operation. + */ virtual Status RegisterSyncCallback(std::shared_ptr callback) override; + /** + * @brief Unregister message for sync operation. + * + * @param callback Indicates the callback to register. + * @return Indicates the status of this register operation. + */ virtual Status UnRegisterSyncCallback() override; + /** + * @brief See Put, PutBatch put a list of entries to kvstore, + * all entries will be put in a transaction, + * if entries contains invalid entry, PutBatch will all fail. + * + * @param entries Indicates the entries. + * The entries's size should be less than 128 and memory size must be less than IPC transport limit. + * @return Indicates the status of this register operation. + */ virtual Status PutBatch(const std::vector &entries) override; + /** + * @brief Delete a list of entries in the kvstore, + * delete key not exist still return success, + * key length should not be greater than 256, and can not be empty. + * If keys contains invalid key, all delete will fail. + * + * @param keys Indicates the list of keys. + * The keys memory size should not be greater than IPC transport limit, and can not be empty. + * @return Indicates the status of this register operation. + */ virtual Status DeleteBatch(const std::vector &keys) override; + /** + * @brief Start transaction. + * All changes to this kvstore will be in a same transaction and will not change the store until Commit() or + * Rollback() is called. + * Before this transaction is committed or rollbacked, all attemption to close this store will fail. + * + * @return Indicates the status of this operation. + */ virtual Status StartTransaction() override; + /** + * @brief Commit current transaction. All changes to this store will be done after calling this method. + * Any calling of this method outside a transaction will fail. + * + * @return Indicates the status of this operation. + */ virtual Status Commit() override; + /** + * @brief Rollback current transaction. + * All changes to this store during this transaction will be rollback after calling this method. + * Any calling of this method outside a transaction will fail. + * + * @return Indicates the status of this operation. + */ virtual Status Rollback() override; + /** + * @brief Set synchronization parameters of this store. + * + * @param syncParam Indicates the sync policy parameter. + * @return Indicates the status of this operation. + */ virtual Status SetSyncParam(const KvSyncParam &syncParam) override; + /** + * @brief Get synchronization parameters of this store. + * + * @param syncParam Indicates the sync policy parameter. + * @return Indicates the status of this operation. + */ virtual Status GetSyncParam(KvSyncParam &syncParam) override; + /** + * @brief Set capability parameters of this store. + * + * @param enabled Indicates the capability Enabled status. + * @return Indicates the status of this operation. + */ virtual Status SetCapabilityEnabled(bool enabled) const override; + /** + * @brief Set capability parameters of this store. + * + * @param localLabels Indicates the labels of local. + * @param remoteSupportLabels Indicates the labels of remote support. + * @return Indicates the status of this operation. + */ virtual Status SetCapabilityRange(const std::vector &localLabels, const std::vector &remoteSupportLabels) const override; + /** + * @brief Get security level. + * + * @param securityLevel Indicates the security level. + * @return Indicates the status of this operation. + */ virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const override; + /** + * @brief Sync store with other devices only syncing the data which is satisfied with the condition. + * This is an asynchronous method, sync will fail if there is a syncing operation in progress. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * @param mode Indicates the sync mode, can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUSH_PULL. + * PUSH_PULL will firstly push all not-local store to listed devices, then pull these stores back. + * @return Indicates the status of this operation. + */ virtual Status SyncWithCondition(const std::vector &deviceIds, SyncMode mode, const DataQuery &query, std::shared_ptr syncCallback) override; + /** + * @brief Subscribe store with other devices consistently Synchronize the data which is satisfied + * with the condition. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * + * @return Indicates the status of this operation. + */ virtual Status SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; + /** + * @brief UnSubscribe store with other devices which is satisfied with the condition. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * @return Indicates the status of this UnSubscribe operation. + */ virtual Status UnsubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; - Status GetKvStoreSnapshot(std::shared_ptr observer, - std::shared_ptr &snapshot) const override; - - Status ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) override; - - Status Clear() override; - protected: KVSTORE_API virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &output) override; }; diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index a6b03d311667faa089b893ceb7fa182734fc62b2..dc91527e4712559c07c897161f273a114950c0a6 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -30,7 +30,6 @@ ohos_moduletest("ans_module_test") { sources = [ "${services_path}/ans/src/advanced_notification_service.cpp", "${services_path}/ans/src/advanced_notification_service_ability.cpp", - "${services_path}/ans/src/bundle_manager_helper.cpp", "${services_path}/ans/src/notification_preferences.cpp", "${services_path}/ans/src/notification_preferences_database.cpp", "${services_path}/ans/src/notification_preferences_info.cpp", @@ -44,7 +43,9 @@ ohos_moduletest("ans_module_test") { "ans_module_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", + "mock/mock_access_token_helper.cpp", "mock/mock_bundle_manager.cpp", + "mock/mock_bundle_manager_helper.cpp", "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", @@ -56,28 +57,28 @@ ohos_moduletest("ans_module_test") { deps = [ "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", - "//foundation/ace/ace_engine/interfaces/innerkits/ui_service_manager:ui_service_mgr", + "//foundation/arkui/ace_engine/interfaces/inner_api/ui_service_manager:ui_service_mgr", "//utils/native/base:utils", ] external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:abilitykit_native", "ability_runtime:app_manager", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "ces_standard:cesfwk_innerkits", + "common_event_service:cesfwk_innerkits", "distributeddatamgr:distributeddata_inner", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hitrace_native:libhitrace", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", "multimedia_media_standard:media_client", - "os_account_standard:os_account_innerkits", + "os_account:os_account_innerkits", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "time_native:time_service", diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp index 9ca7b24f501ffbc9c9b10d0293c4555bf86854c3..5c891cd2bc75b13741a4837384ab8cf123b080b8 100644 --- a/services/test/moduletest/ans_module_test.cpp +++ b/services/test/moduletest/ans_module_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -175,9 +175,9 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_002, Function | SmallTest | Level1) EXPECT_EQ((int)g_advancedNotificationService->Publish(label, req1), (int)ERR_OK); EXPECT_EQ((int)g_advancedNotificationService->Publish("testLabel1", req2), (int)ERR_OK); EXPECT_EQ((int)g_advancedNotificationService->GetActiveNotifications(notificationsReqs), (int)ERR_OK); - int num; + uint64_t num; g_advancedNotificationService->GetActiveNotificationNums(num); - EXPECT_EQ((int)num, (int)3); + EXPECT_EQ(num, 3); EXPECT_EQ((int)g_advancedNotificationService->Cancel(2, "testLabel1"), (int)ERR_OK); EXPECT_EQ((int)g_advancedNotificationService->GetAllActiveNotifications(notifications), (int)ERR_OK); EXPECT_EQ((int)notifications.size(), (int)2); @@ -1748,7 +1748,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0107, Function | SmallTest | Level1) // remove request g_advancedNotificationService->Delete("_0_1_testLabel_0"); g_advancedNotificationService->Delete("_0_1_testLabel_1"); - int nums = -1; + uint64_t nums = 0; g_advancedNotificationService->GetActiveNotificationNums(nums); EXPECT_EQ(nums, 0); g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); @@ -1797,7 +1797,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0108, Function | SmallTest | Level1) // remove request g_advancedNotificationService->DeleteAllByUser(0); - int nums = -1; + uint64_t nums = 0; g_advancedNotificationService->GetActiveNotificationNums(nums); EXPECT_EQ(nums, 0); g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); @@ -2620,7 +2620,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0132, Function | SmallTest | Level1) sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); - EXPECT_EQ(g_advancedNotificationService->SetDoNotDisturbDate(date), ERR_OK); + EXPECT_EQ(g_advancedNotificationService->SetDoNotDisturbDate(100, date), ERR_OK); EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); EXPECT_EQ(g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr), ERR_OK); @@ -2662,7 +2662,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0133, Function | SmallTest | Level1) int64_t endDate = endDuration.count(); sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); - EXPECT_EQ(g_advancedNotificationService->SetDoNotDisturbDate(date), ERR_OK); + EXPECT_EQ(g_advancedNotificationService->SetDoNotDisturbDate(100, date), ERR_OK); EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); EXPECT_EQ(g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr), ERR_OK); @@ -2704,7 +2704,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0134, Function | SmallTest | Level1) int64_t endDate = endDuration.count(); sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); - EXPECT_EQ(g_advancedNotificationService->SetDoNotDisturbDate(date), ERR_OK); + EXPECT_EQ(g_advancedNotificationService->SetDoNotDisturbDate(100, date), ERR_OK); EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); EXPECT_EQ(g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr), ERR_OK); @@ -2746,7 +2746,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0135, Function | SmallTest | Level1) int64_t endDate = endDuration.count(); sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::CLEARLY, beginDate, endDate); - EXPECT_EQ(g_advancedNotificationService->SetDoNotDisturbDate(date), ERR_OK); + EXPECT_EQ(g_advancedNotificationService->SetDoNotDisturbDate(100, date), ERR_OK); EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); EXPECT_EQ(g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr), ERR_OK); diff --git a/services/test/moduletest/mock/include/mock_bundle_manager.h b/services/test/moduletest/mock/include/mock_bundle_manager.h index ab205c7aa8765526693d8c76fde33c9ca1a94e62..caa83a306d667cd0671761dd2263ad82e90aec02 100644 --- a/services/test/moduletest/mock/include/mock_bundle_manager.h +++ b/services/test/moduletest/mock/include/mock_bundle_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -22,9 +22,9 @@ #include "application_info.h" #include "bundle_mgr_host.h" #include "bundle_mgr_interface.h" -#include "ohos/aafwk/content/want.h" #include "iremote_proxy.h" #include "iremote_stub.h" +#include "want.h" namespace OHOS { namespace AppExecFwk { @@ -39,6 +39,7 @@ public: /** * @brief Obtains the ApplicationInfo based on a given bundle name. + * * @param appName Indicates the application bundle name to be queried. * @param flag Indicates the flag used to specify information contained * in the ApplicationInfo object that will be returned. @@ -53,6 +54,7 @@ public: } /** * @brief Obtains information about all installed applications of a specified user. + * * @param flag Indicates the flag used to specify information contained * in the ApplicationInfo objects that will be returned. * @param userId Indicates the user ID. @@ -66,6 +68,7 @@ public: } /** * @brief Obtains the BundleInfo based on a given bundle name. + * * @param bundleName Indicates the application bundle name to be queried. * @param flag Indicates the information contained in the BundleInfo object to be returned. * @param bundleInfo Indicates the obtained BundleInfo object. @@ -79,6 +82,7 @@ public: } /** * @brief Obtains BundleInfo of all bundles available in the system. + * * @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned. * @param bundleInfos Indicates all of the obtained BundleInfo objects. * @param userId Indicates the user ID. @@ -91,6 +95,7 @@ public: }; /** * @brief Obtains the application UID based on the given bundle name and user ID. + * * @param bundleName Indicates the bundle name of the application. * @param userId Indicates the user ID. * @return Returns the uid if successfully obtained; returns -1 otherwise. @@ -101,6 +106,7 @@ public: } /** * @brief Obtains the bundle name of a specified application based on the given UID. + * * @param uid Indicates the uid. * @param bundleName Indicates the obtained bundle name. * @return Returns true if the bundle name is successfully obtained; returns false otherwise. @@ -112,6 +118,7 @@ public: } /** * @brief Obtains an array of all group IDs associated with a specified bundle. + * * @param bundleName Indicates the bundle name. * @param gids Indicates the group IDs associated with the specified bundle. * @return Returns true if the gids is successfully obtained; returns false otherwise. @@ -122,6 +129,7 @@ public: } /** * @brief Obtains the type of a specified application based on the given bundle name. + * * @param bundleName Indicates the bundle name. * @return Returns "system" if the bundle is a system application; returns "third-party" otherwise. */ @@ -131,6 +139,7 @@ public: } /** * @brief Check whether the app is system app by it's UID. + * * @param uid Indicates the uid. * @return Returns true if the bundle is a system application; returns false otherwise. */ @@ -138,6 +147,7 @@ public: /** * @brief Obtains the BundleInfo of application bundles based on the specified metaData. + * * @param metaData Indicates the metadata to get in the bundle. * @param bundleInfos Indicates all of the obtained BundleInfo objects. * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. @@ -148,7 +158,8 @@ public: } /** * @brief Query the AbilityInfo by the given Want. - * @param want Indicates the infomation of the ability. + * + * @param want Indicates the information of the ability. * @param abilityInfo Indicates the obtained AbilityInfo object. * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. */ @@ -158,6 +169,7 @@ public: } /** * @brief Query the AbilityInfo by ability.uri in config.json. + * * @param abilityUri Indicates the uri of the ability. * @param abilityInfo Indicates the obtained AbilityInfo object. * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. @@ -168,6 +180,7 @@ public: } /** * @brief Obtains the BundleInfo of all keep-alive applications in the system. + * * @param bundleInfos Indicates all of the obtained BundleInfo objects. * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. */ @@ -175,18 +188,9 @@ public: { return true; }; - /** - * @brief Obtains the label of a specified ability. - * @param bundleName Indicates the bundle name. - * @param className Indicates the ability class name. - * @return Returns the label of the ability if exist; returns empty string otherwise. - */ - virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override - { - return ""; - } /** * @brief Obtains information about an application bundle contained in a ohos Ability Package (HAP). + * * @param hapFilePath Indicates the absolute file path of the HAP. * @param flag Indicates the information contained in the BundleInfo object to be returned. * @param bundleInfo Indicates the obtained BundleInfo object. @@ -199,6 +203,7 @@ public: } /** * @brief Obtain the HAP module info of a specific ability. + * * @param abilityInfo Indicates the ability. * @param hapModuleInfo Indicates the obtained HapModuleInfo object. * @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise. @@ -209,6 +214,7 @@ public: } /** * @brief Obtains the Want for starting the main ability of an application based on the given bundle name. + * * @param bundleName Indicates the bundle name. * @param want Indicates the obtained launch Want object. * @return Returns true if the launch Want object is successfully obtained; returns false otherwise. @@ -217,23 +223,9 @@ public: { return true; } - /** - * @brief Confirms with the permission management module to check whether a request prompt is required for granting - * a certain permission. - * @param bundleName Indicates the name of the bundle to check. - * @param permission Indicates the permission to check. - * @param userId Indicates the user id. - * @return Returns true if the current application does not have the permission and the user does not turn off - * further requests; returns false if the current application already has the permission, the permission is rejected - * by the system, or the permission is denied by the user and the user has turned off further requests. - */ - virtual bool CanRequestPermission( - const std::string &bundleName, const std::string &permissionName, const int userId) override - { - return true; - } /** * @brief Checks whether the publickeys of two bundles are the same. + * * @param firstBundleName Indicates the first bundle name. * @param secondBundleName Indicates the second bundle name. * @return Returns SIGNATURE_UNKNOWN_BUNDLE if at least one of the given bundles is not found; @@ -244,15 +236,9 @@ public: { return 0; } - /** - * @brief Checks whether a specified bundle has been granted a specific permission. - * @param bundleName Indicates the name of the bundle to check. - * @param permission Indicates the permission to check. - * @return Returns 0 if the bundle has the permission; returns -1 otherwise. - */ - virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override; /** * @brief Obtains detailed information about a specified permission. + * * @param permissionName Indicates the name of the ohos permission. * @param permissionDef Indicates the object containing detailed information about the given ohos permission. * @return Returns true if the PermissionDef object is successfully obtained; returns false otherwise. @@ -261,40 +247,9 @@ public: { return true; } - /** - * @brief Obtains all known permission groups in the system. - * @param permissionDefs Indicates the list of objects containing the permission group information. - * @return Returns true if the PermissionDef objects is successfully obtained; returns false otherwise. - */ - virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override - { - return true; - } - /** - * @brief Obtains all known permission groups in the system. - * @param permissions Indicates the permission array. - * @param appNames Indicates the list of application names that have the specified permissions. - * @return Returns true if the application names is successfully obtained; returns false otherwise. - */ - virtual bool GetAppsGrantedPermissions( - const std::vector &permissions, std::vector &appNames) override - { - return true; - } - /** - * @brief Requests a certain permission from user. - * @param bundleName Indicates the name of the bundle to request permission. - * @param permission Indicates the permission to request permission. - * @param userId Indicates the user id. - * @return Returns true if the permission request successfully; returns false otherwise. - */ - virtual bool RequestPermissionFromUser( - const std::string &bundleName, const std::string &permission, const int userId) override - { - return true; - } /** * @brief Checks whether the system has a specified capability. + * * @param capName Indicates the name of the system feature to check. * @return Returns true if the given feature specified by name is available in the system; returns false otherwise. */ @@ -304,6 +259,7 @@ public: } /** * @brief Obtains the capabilities that are available in the system. + * * @param systemCaps Indicates the list of capabilities available in the system. * @return Returns true if capabilities in the system are successfully obtained; returns false otherwise. */ @@ -313,6 +269,7 @@ public: } /** * @brief Checks whether the current device has been started in safe mode. + * * @return Returns true if the device is in safe mode; returns false otherwise. */ virtual bool IsSafeMode() override @@ -321,6 +278,7 @@ public: } /** * @brief Clears application running data of a specified application. + * * @param bundleName Indicates the bundle name of the application whose data is to be cleared. * @return Returns true if the data cleared successfully; returns false otherwise. */ @@ -330,6 +288,7 @@ public: } /** * @brief Register the specific bundle status callback. + * * @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result. * @return Returns true if this function is successfully called; returns false otherwise. */ @@ -339,6 +298,7 @@ public: } /** * @brief Clear the specific bundle status callback. + * * @param bundleStatusCallback Indicates the callback to be cleared. * @return Returns true if this function is successfully called; returns false otherwise. */ @@ -348,6 +308,7 @@ public: } /** * @brief Unregister all the callbacks of status changed. + * * @return Returns true if this function is successfully called; returns false otherwise. */ virtual bool UnregisterBundleStatusCallback() override @@ -355,11 +316,12 @@ public: return true; } /** - * @brief Dump the bundle informations with specifc flags. + * @brief Dump the bundle informations with specific flags. + * * @param flag Indicates the information contained in the dump result. * @param bundleName Indicates the bundle name if needed. * @param userId Indicates the user ID. - * @param result Indicates the dump infomation result. + * @param result Indicates the dump information result. * @return Returns true if the dump result is successfully obtained; returns false otherwise. */ virtual bool DumpInfos( @@ -369,6 +331,7 @@ public: } /** * @brief Checks whether a specified application is enabled. + * * @param bundleName Indicates the bundle name of the application. * @return Returns true if the application is enabled; returns false otherwise. */ @@ -378,6 +341,7 @@ public: } /** * @brief Obtains the interface used to install and uninstall bundles. + * * @return Returns a pointer to IBundleInstaller class if exist; returns nullptr otherwise. */ virtual sptr GetBundleInstaller() override @@ -386,6 +350,7 @@ public: } /** * @brief Obtains the interface used to create or delete user. + * * @return Returns a pointer to IBundleUserMgr class if exist; returns nullptr otherwise. */ virtual sptr GetBundleUserMgr() override @@ -393,6 +358,11 @@ public: return nullptr; } + /** + * @brief Set whether the bundle is systemapp. + * + * @param isSystemApp Indicates the system app flag. + */ void MockSetIsSystemApp(bool isSystemApp); private: diff --git a/services/test/moduletest/mock/include/mock_single_kv_store.h b/services/test/moduletest/mock/include/mock_single_kv_store.h index b682e43151bbd0c60c21ec51decf5460a8b8ee01..930f66ed4192e70ab9c567a4a1a489f2a3879a76 100644 --- a/services/test/moduletest/mock/include/mock_single_kv_store.h +++ b/services/test/moduletest/mock/include/mock_single_kv_store.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -33,81 +33,307 @@ namespace DistributedKv { // This class provides put, delete, search, sync and subscribe functions of a key-value store. class AnsTestSingleKvStore : public SingleKvStore { public: + /** + * @brief Get all entries in this store which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntries(const Key &prefixKey, std::vector &entries) const override; + /** + * @brief Get all entries in this store by query. + * + * @param query Indicates the query string. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntriesWithQuery(const std::string &query, std::vector &entries) const override; + /** + * @brief Get all entries in this store by query. + * + * @param query Indicates the query object. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ virtual Status GetEntriesWithQuery(const DataQuery &query, std::vector &entries) const override; + /** + * @brief Get ResultSet in this store which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ virtual Status GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const override; + /** + * @brief Get ResultSet in this store by Query. + * + * @param query Indicates the query string. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ virtual Status GetResultSetWithQuery(const std::string &query, std::shared_ptr &resultSet) const override; + /** + * @brief Get ResultSet in this store by Query. + * + * @param query Indicates the query object. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ virtual Status GetResultSetWithQuery(const DataQuery &query, std::shared_ptr &resultSet) const override; + /** + * @brief Close the ResultSet returned by GetResultSet. + * + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status CloseResultSet(std::shared_ptr &resultSet) override; + /** + * @brief Get the number of result by query. + * + * @param query Indicates the query string. + * @param result Indicates the result. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status GetCountWithQuery(const std::string &query, int &result) const override; + /** + * @brief Get the number of result by query. + * + * @param query Indicates the query object. + * @param result Indicates the result will be returned in this parameter. + * @return Indicates the status of this CloseResultSet operation. + */ virtual Status GetCountWithQuery(const DataQuery &query, int &result) const override; + /** + * @brief Sync store with other devices. This is an asynchronous method, + * sync will fail if there is a syncing operation in progress. + * + * @param deviceIds Indicates the device list to sync. + * @param mode Indicates the sync mode, can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. + * PUSH_PULL will firstly push all not-local store to listed devices, then pull these stores back. + * @param allowedDelayMs Indicates the allowed delay milli-second to sync. default value is 0 for compatibility. + * @return Indicates the status of this Sync operation. + */ virtual Status Sync( const std::vector &deviceIds, SyncMode mode, uint32_t allowedDelayMs = 0) override; + /** + * @brief Remove the device data synced from remote. + * + * @param device Indicates the device id. + * @return Indicates the status of this remove operation. + */ virtual Status RemoveDeviceData(const std::string &device) override; + /** + * @brief Get id of this AppKvStore. + * + * @return Indicates the id of store. + */ virtual StoreId GetStoreId() const override; + /** + * @brief Delete an entry by its key. + * + * @param key Indicates the key of the entry to be deleted. + * @return Indicates the status of this delete operation. + */ virtual Status Delete(const Key &key) override; + /** + * @brief Write a pair of key and value to this store. + * + * @param key Indicates the key of this entry. Should be less than 256 bytes. key will be trimmed before store. + * @param value Indicates the value of this entry. Should be less than (1024 * 1024) bytes. + * @return Indicates the status of this put operation. + */ virtual Status Put(const Key &key, const Value &value) override; + /** + * @brief Get value from AppKvStore by its key. + * + * @param key Indicates the key of this entry. + * @param value Indicates the value will be returned in this parameter. + * @return Indicates the status of this get operation. + */ virtual Status Get(const Key &key, Value &value) override; + /** + * @brief Register change of this kvstore to a client-defined observer. + * observer->OnChange method will be called when store changes. + * One observer can subscribe more than one AppKvStore. + * + * @param subscribeType Indicates the subscribe type. + * OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, + * OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, + * OBSERVER_CHANGES_ALL means both native changes and synced data changes. + * @param observer Indicates the observer to subscribe changes. + * @return Indicates the status of this subscribe operation. + */ virtual Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + /** + * @brief Unregister a kvstore to an observer. + * + * @param subscribeType Indicates the subscribe type. + * Reserved parameter. Current is always SubscribeType::DEFAULT. + * @param observer Indicates the observer to unsubscribe this store. + * @return Indicates the status of this unsubscribe operation. + */ virtual Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + /** + * @brief Register message for sync operation. + * + * @param callback Indicates the callback to register. + * @return Indicates the status of this register operation. + */ virtual Status RegisterSyncCallback(std::shared_ptr callback) override; + /** + * @brief Unregister message for sync operation. + * + * @param callback Indicates the callback to register. + * @return Indicates the status of this register operation. + */ virtual Status UnRegisterSyncCallback() override; + /** + * @brief See Put, PutBatch put a list of entries to kvstore, + * all entries will be put in a transaction, + * if entries contains invalid entry, PutBatch will all fail. + * + * @param entries Indicates the entries. + * The entries's size should be less than 128 and memory size must be less than IPC transport limit. + * @return Indicates the status of this register operation. + */ virtual Status PutBatch(const std::vector &entries) override; + /** + * @brief Delete a list of entries in the kvstore, + * delete key not exist still return success, + * key length should not be greater than 256, and can not be empty. + * If keys contains invalid key, all delete will fail. + * + * @param keys Indicates the list of keys. + * The keys memory size should not be greater than IPC transport limit, and can not be empty. + * @return Indicates the status of this register operation. + */ virtual Status DeleteBatch(const std::vector &keys) override; + /** + * @brief Start transaction. + * All changes to this kvstore will be in a same transaction and will not change the store until Commit() or + * Rollback() is called. + * Before this transaction is committed or rollbacked, all attemption to close this store will fail. + * + * @return Indicates the status of this operation. + */ virtual Status StartTransaction() override; + /** + * @brief Commit current transaction. All changes to this store will be done after calling this method. + * Any calling of this method outside a transaction will fail. + * + * @return Indicates the status of this operation. + */ virtual Status Commit() override; + /** + * @brief Rollback current transaction. + * All changes to this store during this transaction will be rollback after calling this method. + * Any calling of this method outside a transaction will fail. + * + * @return Indicates the status of this operation. + */ virtual Status Rollback() override; + /** + * @brief Set synchronization parameters of this store. + * + * @param syncParam Indicates the sync policy parameter. + * @return Indicates the status of this operation. + */ virtual Status SetSyncParam(const KvSyncParam &syncParam) override; + /** + * @brief Get synchronization parameters of this store. + * + * @param syncParam Indicates the sync policy parameter. + * @return Indicates the status of this operation. + */ virtual Status GetSyncParam(KvSyncParam &syncParam) override; + /** + * @brief Set capability parameters of this store. + * + * @param enabled Indicates the capability Enabled status. + * @return Indicates the status of this operation. + */ virtual Status SetCapabilityEnabled(bool enabled) const override; + /** + * @brief Set capability parameters of this store. + * + * @param localLabels Indicates the labels of local. + * @param remoteSupportLabels Indicates the labels of remote support. + * @return Indicates the status of this operation. + */ virtual Status SetCapabilityRange(const std::vector &localLabels, const std::vector &remoteSupportLabels) const override; + /** + * @brief Get security level. + * + * @param securityLevel Indicates the security level. + * @return Indicates the status of this operation. + */ virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const override; + /** + * @brief Sync store with other devices only syncing the data which is satisfied with the condition. + * This is an asynchronous method, sync will fail if there is a syncing operation in progress. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * @param mode Indicates the sync mode, can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUSH_PULL. + * PUSH_PULL will firstly push all not-local store to listed devices, then pull these stores back. + * @return Indicates the status of this operation. + */ virtual Status SyncWithCondition(const std::vector &deviceIds, SyncMode mode, const DataQuery &query, std::shared_ptr syncCallback) override; + /** + * @brief Subscribe store with other devices consistently Synchronize the data which is satisfied + * with the condition. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * + * @return Indicates the status of this operation. + */ virtual Status SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; + /** + * @brief UnSubscribe store with other devices which is satisfied with the condition. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * @return Indicates the status of this UnSubscribe operation. + */ virtual Status UnsubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; - Status GetKvStoreSnapshot(std::shared_ptr observer, - std::shared_ptr &snapshot) const override; - - Status ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) override; - - Status Clear() override; protected: KVSTORE_API virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &output) override; }; diff --git a/services/distributed/test/unittest/mock/mock_inner_event.cpp b/services/test/moduletest/mock/mock_access_token_helper.cpp similarity index 64% rename from services/distributed/test/unittest/mock/mock_inner_event.cpp rename to services/test/moduletest/mock/mock_access_token_helper.cpp index 857a69c73e490dce1d0a2bc840fcfcb3b747bb3b..51c2f039e007568d3be76eafd903af52e6383d50 100644 --- a/services/distributed/test/unittest/mock/mock_inner_event.cpp +++ b/services/test/moduletest/mock/mock_access_token_helper.cpp @@ -13,16 +13,19 @@ * limitations under the License. */ -#include "inner_event.h" +#include "access_token_helper.h" namespace OHOS { -namespace AppExecFwk { -InnerEvent::Pointer InnerEvent::Get(const Callback &callback, const std::string &name) +namespace Notification { +bool AccessTokenHelper::VerifyCallerPermission( + const Security::AccessToken::AccessTokenID &tokenCaller, const std::string &permission) { - InnerEvent::Pointer pointer = InnerEvent::Pointer(new InnerEvent, [](InnerEvent *event) {}); - pointer->taskCallback_ = callback; - pointer->taskName_ = name; - return pointer; + return true; } -} // namespace AppExecFwk + +bool AccessTokenHelper::VerifyNativeToken(const Security::AccessToken::AccessTokenID &callerToken) +{ + return true; +} +} // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/mock/mock_bundle_manager.cpp b/services/test/moduletest/mock/mock_bundle_manager.cpp index cdb047eceb67099cb8db3c1339f4e0fbcbfe6dc4..b6da2c96aa5cdd1038a38be512d131dc06d2b52d 100644 --- a/services/test/moduletest/mock/mock_bundle_manager.cpp +++ b/services/test/moduletest/mock/mock_bundle_manager.cpp @@ -34,14 +34,5 @@ bool MockBundleMgrService::CheckIsSystemAppByUid(const int uid) } return (uid < SYSTEMAPP_UUID) ? false : true; } - -int MockBundleMgrService::CheckPermission(const std::string &bundleName, const std::string &permission) -{ - if (!bundleName.compare("hello")) { - return 0; - } else { - return -1; - } -} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp index 70406de1d4b1be368e3aabad9393e3e451ccdb84..38de76c01e2f8df937aac4cf356a268635654aa0 100644 --- a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -40,6 +40,22 @@ bool BundleManagerHelper::IsSystemApp(int uid) return true; } +bool BundleManagerHelper::CheckApiCompatibility(const sptr &bundleOption) +{ + return true; +} + +int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId) +{ + return 1000; +} + +bool BundleManagerHelper::GetBundleInfoByBundleName( + const std::string bundle, const int32_t userId, AppExecFwk::BundleInfo &bundleInfo) +{ + return true; +} + void BundleManagerHelper::Connect() {} diff --git a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp index f40336c905ff100728728da1c1ae7b9bf6567122..d38187389baf578f7cfb7e6de2151a7728048e59 100644 --- a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -115,11 +115,6 @@ bool BundleMgrProxy::QueryKeepAliveBundleInfos(std::vector &bundleIn return true; } -std::string BundleMgrProxy::GetAbilityLabel(const std::string &bundleName, const std::string &className) -{ - return "reply.ReadString()"; -} - bool BundleMgrProxy::GetBundleArchiveInfo(const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) { return true; @@ -140,27 +135,11 @@ int BundleMgrProxy::CheckPublicKeys(const std::string &firstBundleName, const st return 1; } -int BundleMgrProxy::CheckPermission(const std::string &bundleName, const std::string &permission) -{ - return 1; -} - bool BundleMgrProxy::GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) { return true; } -bool BundleMgrProxy::GetAllPermissionGroupDefs(std::vector &permissionDefs) -{ - return true; -} - -bool BundleMgrProxy::GetAppsGrantedPermissions( - const std::vector &permissions, std::vector &appNames) -{ - return true; -} - bool BundleMgrProxy::HasSystemCapability(const std::string &capName) { return true; @@ -213,39 +192,6 @@ bool BundleMgrProxy::IsAbilityEnabled(const AbilityInfo &abilityInfo) return true; } -std::string BundleMgrProxy::GetAbilityIcon(const std::string &bundleName, const std::string &className) -{ - return "AbilityIcon"; -} - -bool BundleMgrProxy::CanRequestPermission( - const std::string &bundleName, const std::string &permissionName, const int userId) -{ - return true; -} - -bool BundleMgrProxy::RequestPermissionFromUser( - const std::string &bundleName, const std::string &permission, const int userId) -{ - return true; -} - -bool BundleMgrProxy::RegisterAllPermissionsChanged(const sptr &callback) -{ - return true; -} - -bool BundleMgrProxy::RegisterPermissionsChanged( - const std::vector &uids, const sptr &callback) -{ - return true; -} - -bool BundleMgrProxy::UnregisterPermissionsChanged(const sptr &callback) -{ - return true; -} - template bool BundleMgrProxy::GetParcelableInfo(IBundleMgr::Message code, MessageParcel &data, T &parcelableInfo) { diff --git a/services/test/moduletest/mock/mock_ipc.cpp b/services/test/moduletest/mock/mock_ipc.cpp index 6a93d95c4fb403e104c9312a49881a7cfc957b7b..94550af6c992fef6c782c65c340db09e8732bda1 100644 --- a/services/test/moduletest/mock/mock_ipc.cpp +++ b/services/test/moduletest/mock/mock_ipc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -21,7 +21,6 @@ using namespace IPC_SINGLE; #endif int IPCSkeleton::GetCallingUid() { - int uid = 1; - return uid; + return 1; } } // namespace OHOS diff --git a/services/test/moduletest/mock/mock_single_kv_store.cpp b/services/test/moduletest/mock/mock_single_kv_store.cpp index 83e719b8156413abb149c208cb0aa46624edb8b1..68edb372e0020fad87b048626fc3b5f682f1e458 100644 --- a/services/test/moduletest/mock/mock_single_kv_store.cpp +++ b/services/test/moduletest/mock/mock_single_kv_store.cpp @@ -174,17 +174,6 @@ Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam return Status::SUCCESS; } -Status AnsTestSingleKvStore::GetKvStoreSnapshot(std::shared_ptr observer, - std::shared_ptr &snapshot) const -{ - return Status::NOT_SUPPORT; -} - -Status AnsTestSingleKvStore::ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) -{ - return Status::NOT_SUPPORT; -} - Status AnsTestSingleKvStore::SyncWithCondition(const std::vector &deviceIds, SyncMode mode, const DataQuery &query, std::shared_ptr syncCallback) { @@ -200,10 +189,5 @@ Status AnsTestSingleKvStore::UnsubscribeWithQuery(const std::vector { return Status::SUCCESS; } - -Status AnsTestSingleKvStore::Clear() -{ - return Status::NOT_SUPPORT; -} } // namespace DistributedKv } // namespace OHOS diff --git a/test/bechmarktest/BUILD.gn b/test/bechmarktest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8c70f9303876f2acacc5c3a6fd962ae221b5ffaf --- /dev/null +++ b/test/bechmarktest/BUILD.gn @@ -0,0 +1,29 @@ +# 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. + +import("//build/ohos.gni") + +config("bechmark_test_config") { + include_dirs = [ "//third_party/json/include" ] + + configs = [] +} + +group("benchmarktest") { + testonly = true + + deps = [ + "notification_publish_test:benchmarktest", + "notification_services_test:benchmarktest", + ] +} diff --git a/test/bechmarktest/notification_publish_test/BUILD.gn b/test/bechmarktest/notification_publish_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..89201bd7bd0b525da9df9d73219e61d9a6721b77 --- /dev/null +++ b/test/bechmarktest/notification_publish_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 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. + +import("//base/notification/ans_standard/notification.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/benchmarktest" + +ohos_benchmarktest("Benchmark_Publish_Test") { + module_out_path = module_output_path + include_dirs = [ + "${interfaces_path}/ans/native/include", + "${services_path}/ans/include", + ] + + sources = [ "notification_publish_test.cpp" ] + + deps = [ + "${frameworks_path}/ans/core:ans_core", + "${frameworks_path}/ans/native:ans_innerkits", + "//third_party/benchmark:benchmark", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:wantagent_innerkits", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] + subsystem_name = "notification" + part_name = "ans_standard" +} + +group("benchmarktest") { + testonly = true + deps = [] + + deps += [ + # deps file + ":Benchmark_Publish_Test", + ] +} diff --git a/test/bechmarktest/notification_publish_test/notification_publish_test.cpp b/test/bechmarktest/notification_publish_test/notification_publish_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..02a3485802b9500d78cb49dd9c9036aee0ea3bc0 --- /dev/null +++ b/test/bechmarktest/notification_publish_test/notification_publish_test.cpp @@ -0,0 +1,199 @@ +/* + * 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. + */ + +#include +#include +#include + +#include "notification_action_button.h" +#include "notification_request.h" +#include "notification_content.h" +#include "notification_helper.h" +#include "want_agent_helper.h" +#include "want_agent_info.h" + +using namespace OHOS; +using namespace OHOS::Notification; +using namespace OHOS::AbilityRuntime; + +namespace { +class BenchmarkNotificationPublish : public benchmark::Fixture { +public: + BenchmarkNotificationPublish() + { + Iterations(iterations); + Repetitions(repetitions); + ReportAggregatesOnly(); + + InitTextRequest(); + InitWantAgentRequest(); + InitButtonRequest(); + } + + virtual ~BenchmarkNotificationPublish() override = default; + + void SetUp(const ::benchmark::State &state) override + {} + + void TearDown(const ::benchmark::State &state) override + {} + +protected: + void InitTextRequest(); + void InitWantAgentRequest(); + void InitButtonRequest(); + + const int32_t repetitions = 1; + const int32_t iterations = 100; + + NotificationRequest req_; + NotificationRequest reqWantAgent_; + NotificationRequest reqButton_; +}; + +void BenchmarkNotificationPublish::InitTextRequest() +{ + std::shared_ptr mediaContent = std::make_shared(); + std::shared_ptr content = std::make_shared(mediaContent); + req_.SetContent(content); + req_.SetSlotType(NotificationConstant::OTHER); + std::vector style; + style.push_back("style"); + req_.SetNotificationUserInputHistory(style); + req_.SetOwnerBundleName("bundleName"); + req_.SetLabel("Text"); +} + +void BenchmarkNotificationPublish::InitWantAgentRequest() +{ + std::shared_ptr mediaContent = std::make_shared(); + std::shared_ptr content = std::make_shared(mediaContent); + AbilityRuntime::WantAgent::WantAgentInfo paramsInfo; + std::shared_ptr wantAgent = + AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(paramsInfo); + reqWantAgent_.SetContent(content); + reqWantAgent_.SetSlotType(NotificationConstant::OTHER); + reqWantAgent_.SetWantAgent(wantAgent); + reqWantAgent_.SetOwnerBundleName("bundleName"); + reqWantAgent_.SetLabel("Text"); +} + +void BenchmarkNotificationPublish::InitButtonRequest() +{ + std::shared_ptr mediaContent = std::make_shared(); + std::shared_ptr content = std::make_shared(mediaContent); + AbilityRuntime::WantAgent::WantAgentInfo paramsInfo; + std::shared_ptr wantAgent = + AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(paramsInfo); + std::shared_ptr actionButton = + NotificationActionButton::Create(nullptr, "title", wantAgent); + std::shared_ptr onlyUserInput = NotificationUserInput::Create("onlyUserInputKey"); + AAFwk::WantParams additional; + actionButton->AddAdditionalData(additional); + actionButton->SetSemanticActionButton(NotificationConstant::NONE_ACTION_BUTTON); + actionButton->SetAutoCreatedReplies(true); + actionButton->AddMimeTypeOnlyUserInput(onlyUserInput); + actionButton->SetContextDependent(true); + reqButton_.SetContent(content); + reqButton_.SetSlotType(NotificationConstant::OTHER); + reqButton_.AddActionButton(actionButton); + reqButton_.SetOwnerBundleName("bundleName"); + reqButton_.SetLabel("Text"); +} + +/** +* @tc.name: PublishNotificationTestCase001 +* @tc.desc: publish text notifcation +* @tc.type: FUNC +* @tc.require: +*/ +BENCHMARK_F(BenchmarkNotificationPublish, PublishNotificationTestCase001)(benchmark::State &state) +{ + int id = 0; + while (state.KeepRunning()) { + req_.SetNotificationId(id++); + NotificationHelper::PublishNotification(req_); + } +} + +/** +* @tc.name: CancelNotificationTestCase +* @tc.desc: cancel notification +* @tc.type: FUNC +* @tc.require: +*/ +BENCHMARK_F(BenchmarkNotificationPublish, CancelNotificationTestCase)(benchmark::State &state) +{ + int id = 100; + while (state.KeepRunning()) { + id--; + NotificationHelper::CancelNotification(id); + } +} + +/** +* @tc.name: PublishNotificationTestCase002 +* @tc.desc: publish wantAgent notifcation +* @tc.type: FUNC +* @tc.require: +*/ +BENCHMARK_F(BenchmarkNotificationPublish, PublishNotificationTestCase002)(benchmark::State &state) +{ + int id = 0; + while (state.KeepRunning()) { + reqWantAgent_.SetNotificationId(id++); + NotificationHelper::PublishNotification(reqWantAgent_); + } +} + +BENCHMARK_REGISTER_F(BenchmarkNotificationPublish, CancelNotificationTestCase)->Iterations(100)-> + Repetitions(1)->ReportAggregatesOnly(); + +/** +* @tc.name: PublishNotificationTestCase003 +* @tc.desc: publish wantAgent notifcation +* @tc.type: FUNC +* @tc.require: +*/ +BENCHMARK_F(BenchmarkNotificationPublish, PublishNotificationTestCase003)(benchmark::State &state) +{ + int id = 0; + while (state.KeepRunning()) { + reqButton_.SetNotificationId(id++); + NotificationHelper::PublishNotification(reqButton_); + } +} + +BENCHMARK_REGISTER_F(BenchmarkNotificationPublish, CancelNotificationTestCase)->Iterations(100)-> + Repetitions(1)->ReportAggregatesOnly(); + +/** +* @tc.name: RemoveNotificationTestCase +* @tc.desc: remove notification +* @tc.type: FUNC +* @tc.require: +*/ +BENCHMARK_F(BenchmarkNotificationPublish, RemoveNotificationTestCase)(benchmark::State &state) +{ + int id = 100; + while (state.KeepRunning()) { + id--; + NotificationHelper::RemoveNotifications(); + } +} +} + +// Run the benchmark +BENCHMARK_MAIN(); \ No newline at end of file diff --git a/test/bechmarktest/notification_services_test/BUILD.gn b/test/bechmarktest/notification_services_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7f6ad1fd25afbc8b12ae89b295e04c1fb4e37dd6 --- /dev/null +++ b/test/bechmarktest/notification_services_test/BUILD.gn @@ -0,0 +1,62 @@ +# Copyright (c) 2021 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. + +import("//base/notification/ans_standard/notification.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/benchmarktest" + +ohos_benchmarktest("Benchmark_Notification_Servece_Test") { + module_out_path = module_output_path + include_dirs = [ + "include", + "mock/include", + "${services_path}/ans/include", + ] + + sources = [ + "mock/mock_bundle_manager_helper.cpp", + "mock/mock_ipc.cpp", + "notification_service_test.cpp", + ] + + deps = [ + "${frameworks_path}/ans/core:ans_core", + "${frameworks_path}/ans/native:ans_innerkits", + "${services_path}/ans:libans", + "//third_party/benchmark:benchmark", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:wantagent_innerkits", + "common_event_service:cesfwk_innerkits", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] + subsystem_name = "notification" + part_name = "ans_standard" +} + +group("benchmarktest") { + testonly = true + deps = [] + + deps += [ + # deps file + ":Benchmark_Notification_Servece_Test", + ] +} diff --git a/test/bechmarktest/notification_services_test/mock/include/mock_ipc_skeleton.h b/test/bechmarktest/notification_services_test/mock/include/mock_ipc_skeleton.h new file mode 100644 index 0000000000000000000000000000000000000000..a954c7e984fcb213bbf424da29454bba3de76e6d --- /dev/null +++ b/test/bechmarktest/notification_services_test/mock/include/mock_ipc_skeleton.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 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 OHOS_MOCK_IPC_SKELETON_H +#define OHOS_MOCK_IPC_SKELETON_H + +#include "iremote_object.h" + +namespace OHOS { +class IPCSkeleton { +public: + IPCSkeleton() = default; + ~IPCSkeleton() = default; + + // default max is 4, only if you need a customize value + static bool SetMaxWorkThreadNum(int maxThreadNum); + + // join current thread into work loop. + static void JoinWorkThread(); + + // remove current thread from work loop. + static void StopWorkThread(); + + static pid_t GetCallingPid(); + + static pid_t GetCallingUid(); + + static std::string GetLocalDeviceID(); + + static std::string GetCallingDeviceID(); + + static bool IsLocalCalling(); + + static IPCSkeleton &GetInstance(); + + static sptr GetContextObject(); + + static bool SetContextObject(sptr &object); + + static int FlushCommands(IRemoteObject *object); + + static std::string ResetCallingIdentity(); + + static bool SetCallingIdentity(std::string &identity); + + static void SetCallingUid(pid_t uid); +}; +} // namespace OHOS +#endif // OHOS_MOCK_IPC_SKELETON_H diff --git a/test/bechmarktest/notification_services_test/mock/mock_bundle_manager_helper.cpp b/test/bechmarktest/notification_services_test/mock/mock_bundle_manager_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..72e792b407396ec86ebf7222fdacd6e59f4aa9b8 --- /dev/null +++ b/test/bechmarktest/notification_services_test/mock/mock_bundle_manager_helper.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021-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. + */ + +#include "bundle_manager_helper.h" + +namespace OHOS { +namespace Notification { +BundleManagerHelper::BundleManagerHelper() +{} + +BundleManagerHelper::~BundleManagerHelper() +{} + +void BundleManagerHelper::OnRemoteDied(const wptr &object) +{} + +std::string BundleManagerHelper::GetBundleNameByUid(int uid) +{ + return "bundleName"; +} + +int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId) +{ + return 10000; +} + +bool BundleManagerHelper::IsSystemApp(int uid) +{ + return true; +} + +bool BundleManagerHelper::CheckApiCompatibility(const sptr &bundleOption) +{ + return true; +} + +bool BundleManagerHelper::GetBundleInfoByBundleName( + const std::string bundle, const int32_t userId, AppExecFwk::BundleInfo &bundleInfo) +{ + return true; +} + +void BundleManagerHelper::Connect() +{} + +void BundleManagerHelper::Disconnect() +{} + +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &bundleName, const int userId) +{ + return true; +} +#endif +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/test/bechmarktest/notification_services_test/mock/mock_ipc.cpp b/test/bechmarktest/notification_services_test/mock/mock_ipc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e533d584f9b55b9ada190103f22a6ba1139e71f1 --- /dev/null +++ b/test/bechmarktest/notification_services_test/mock/mock_ipc.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 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 "mock_ipc_skeleton.h" + +namespace OHOS { +#ifdef CONFIG_IPC_SINGLE +using namespace IPC_SINGLE; +#endif + +pid_t uid_ = 1000; + +pid_t IPCSkeleton::GetCallingUid() +{ + return uid_; +} + +pid_t IPCSkeleton::GetCallingPid() +{ + return 1; +} + +void IPCSkeleton::SetCallingUid(pid_t uid) +{ + uid_ = uid; +} +} // namespace OHOS diff --git a/test/bechmarktest/notification_services_test/notification_service_test.cpp b/test/bechmarktest/notification_services_test/notification_service_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2cb35a80ac6d858ab725cd40b01555b5b1588b10 --- /dev/null +++ b/test/bechmarktest/notification_services_test/notification_service_test.cpp @@ -0,0 +1,444 @@ +/* + * 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. + */ + +#include +#include +#include +#include + +#define private public +#include "advanced_notification_service.h" +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "mock_ipc_skeleton.h" +#include "notification.h" +#include "notification_subscriber.h" + + +using namespace OHOS; +using namespace OHOS::Notification; +using namespace OHOS::AbilityRuntime; + +namespace { +class TestAnsSubscriber : public NotificationSubscriber { +public: + void OnConnected() override + {} + void OnDisconnected() override + {} + void OnDied() override + {} + void OnUpdate(const std::shared_ptr &sortingMap) override + {} + void OnDoNotDisturbDateChange(const std::shared_ptr &date) override + {} + void OnEnabledNotificationChanged( + const std::shared_ptr &callbackData) override + {} + void OnCanceled(const std::shared_ptr &request) override + {} + void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override + {} + void OnConsumed(const std::shared_ptr &request) override + {} + void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override + {} +}; + +class BenchmarkNotificationService : public benchmark::Fixture { +public: + BenchmarkNotificationService() + { + Iterations(iterations); + Repetitions(repetitions); + ReportAggregatesOnly(); + } + + virtual ~BenchmarkNotificationService() override = default; + + void SetUp(const ::benchmark::State &state) override + {} + void TearDown(const ::benchmark::State &state) override + {} + +protected: + const int32_t repetitions = 3; + const int32_t iterations = 100; + static sptr advancedNotificationService_; +}; + +sptr BenchmarkNotificationService::advancedNotificationService_ = + AdvancedNotificationService::GetInstance(); + +/** + * @tc.name: AddSlotTestCase + * @tc.desc: AddSlot + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, AddSlotTestCase)(benchmark::State &state) +{ + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CUSTOM); + slots.push_back(slot); + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->AddSlots(slots); + if (errCode != ERR_OK) { + state.SkipWithError("AddSlotTestCase failed."); + } + } +} + +/** + * @tc.name: RemoveSlotByTypeTestCase + * @tc.desc: RemoveSlotByType + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, RemoveSlotByTypeTestCase)(benchmark::State &state) +{ + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CUSTOM); + slots.push_back(slot); + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->AddSlots(slots); + if (errCode != ERR_OK) { + state.SkipWithError("RemoveSlotByTypeTestCase add failed."); + } + + errCode = advancedNotificationService_->RemoveSlotByType(NotificationConstant::SlotType::CUSTOM); + if (errCode != ERR_OK) { + state.SkipWithError("RemoveSlotByTypeTestCase remove failed."); + } + } +} + +/** + * @tc.name: AddSlotGroupTestCase + * @tc.desc: AddSlotGroup + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, AddSlotGroupTestCase)(benchmark::State &state) +{ + std::vector> groups; + sptr group = new NotificationSlotGroup("id0", "name0"); + groups.push_back(group); + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->AddSlotGroups(groups); + if (errCode != ERR_OK) { + state.SkipWithError("AddSlotGroupTestCase failed."); + } + } +} + +/** + * @tc.name: RemoveSlotGroupsTestCase + * @tc.desc: RemoveSlotGroups + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, RemoveSlotGroupsTestCase)(benchmark::State &state) +{ + std::vector> groups; + sptr group = new NotificationSlotGroup("id0", "name0"); + groups.push_back(group); + std::vector groupIds; + groupIds.push_back("id0"); + + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->AddSlotGroups(groups); + if (errCode != ERR_OK) { + state.SkipWithError("RemoveSlotGroupsTestCase add failed."); + } + + errCode = advancedNotificationService_->RemoveSlotGroups(groupIds); + if (errCode != ERR_OK) { + state.SkipWithError("RemoveSlotGroupsTestCase remove failed."); + } + } +} + +/** + * @tc.name: SubscribeTestCase + * @tc.desc: Subscribe + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, SubscribeTestCase)(benchmark::State &state) +{ + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->Subscribe(subscriber->GetImpl(), info); + if (errCode != ERR_OK) { + state.SkipWithError("SubscribeTestCase failed."); + } + } +} + +/** + * @tc.name: PublishNotificationTestCase001 + * @tc.desc: Publish a normal text type notification. + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, PublishNotificationTestCase001)(benchmark::State &state) +{ + sptr req = new (std::nothrow) NotificationRequest(1); + EXPECT_NE(req, nullptr); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); + req->SetContent(content); + + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->Publish(label, req); + if (errCode != ERR_OK) { + state.SkipWithError("PublishNotificationTestCase001 failed."); + } + } +} + +/** + * @tc.name: CancelNotificationTestCase001 + * @tc.desc: Cancel a normal text type notification. + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, CancelNotificationTestCase001)(benchmark::State &state) +{ + sptr req = new (std::nothrow) NotificationRequest(0); + EXPECT_NE(req, nullptr); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); + req->SetContent(content); + + int id = 0; + while (state.KeepRunning()) { + req->SetNotificationId(id); + ErrCode errCode = advancedNotificationService_->Publish(label, req); + if (errCode != ERR_OK) { + state.SkipWithError("CancelNotificationTestCase001 publish failed."); + } + advancedNotificationService_->Cancel(id, label); + id++; + } +} + +/** + * @tc.name: SetNotificationBadgeNumTestCase + * @tc.desc: SetNotificationBadgeNum + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, SetNotificationBadgeNumTestCase)(benchmark::State &state) +{ + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->SetNotificationBadgeNum(2); + if (errCode != ERR_OK) { + state.SkipWithError("SetNotificationBadgeNumTestCase failed."); + } + } +} + +/** + * @tc.name: GetBundleImportanceTestCase + * @tc.desc: GetBundleImportance + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, GetBundleImportanceTestCase)(benchmark::State &state) +{ + int importance = 0; + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->GetBundleImportance(importance); + if (errCode != ERR_OK) { + state.SkipWithError("GetBundleImportanceTestCase failed."); + } + } +} + +/** + * @tc.name: SetPrivateNotificationsAllowedTestCase + * @tc.desc: SetPrivateNotificationsAllowed + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, SetPrivateNotificationsAllowedTestCase)(benchmark::State &state) +{ + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->SetPrivateNotificationsAllowed(true); + if (errCode != ERR_OK) { + state.SkipWithError("SetPrivateNotificationsAllowedTestCase failed."); + } + } +} + +/** + * @tc.name: GetPrivateNotificationsAllowedTestCase + * @tc.desc: GetPrivateNotificationsAllowed + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, GetPrivateNotificationsAllowedTestCase)(benchmark::State &state) +{ + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->SetPrivateNotificationsAllowed(true); + if (errCode != ERR_OK) { + state.SkipWithError("GetPrivateNotificationsAllowed set failed."); + } + + bool allow = false; + errCode = advancedNotificationService_->GetPrivateNotificationsAllowed(allow); + if (!allow || errCode != ERR_OK) { + state.SkipWithError("GetPrivateNotificationsAllowed get failed."); + } + } +} + +/** + * @tc.name: SetShowBadgeEnabledForBundleTestCase + * @tc.desc: SetShowBadgeEnabledForBundle + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, SetShowBadgeEnabledForBundleTestCase)(benchmark::State &state) +{ + sptr bundleOption = new NotificationBundleOption("bundleName", 1000); + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->SetShowBadgeEnabledForBundle(bundleOption, true); + if (errCode != ERR_OK) { + state.SkipWithError("SetShowBadgeEnabledForBundleTestCase failed."); + } + } +} + +/** + * @tc.name: GetShowBadgeEnabledForBundleTestCase + * @tc.desc: GetShowBadgeEnabledForBundle + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, GetShowBadgeEnabledForBundleTestCase)(benchmark::State &state) +{ + sptr bundleOption = new NotificationBundleOption("bundleName", 1000); + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->SetShowBadgeEnabledForBundle(bundleOption, true); + if (errCode != ERR_OK) { + state.SkipWithError("GetShowBadgeEnabledForBundleTestCase set failed."); + } + + bool allow = false; + errCode = advancedNotificationService_->GetShowBadgeEnabledForBundle(bundleOption, allow); + if (!allow || errCode != ERR_OK) { + state.SkipWithError("GetShowBadgeEnabledForBundleTestCase get failed."); + } + } +} + +/** + * @tc.name: GetAllActiveNotificationsTestCase + * @tc.desc: GetAllActiveNotifications + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, GetAllActiveNotificationsTestCase)(benchmark::State &state) +{ + std::vector> notifications; + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->GetAllActiveNotifications(notifications); + if (errCode != ERR_OK) { + state.SkipWithError("GetAllActiveNotificationsTestCase failed."); + } + } +} + +/** + * @tc.name: SetNotificationsEnabledForAllBundlesTestCase + * @tc.desc: SetNotificationsEnabledForAllBundles + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, SetNotificationsEnabledForAllBundlesTestCase)(benchmark::State &state) +{ + std::vector> notifications; + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true); + if (errCode != ERR_OK) { + state.SkipWithError("SetNotificationsEnabledForAllBundlesTestCase failed."); + } + } +} + +/** + * @tc.name: IsAllowedNotifyTestCase + * @tc.desc: IsAllowedNotify + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, IsAllowedNotifyTestCase)(benchmark::State &state) +{ + std::vector> notifications; + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true); + if (errCode != ERR_OK) { + state.SkipWithError("IsAllowedNotifyTestCase set failed."); + } + + bool allowed = false; + errCode = advancedNotificationService_->IsAllowedNotify(allowed); + if (!allowed || errCode != ERR_OK) { + state.SkipWithError("IsAllowedNotifyTestCase get failed."); + } + } +} + +/** + * @tc.name: SetNotificationsEnabledForSpecialBundleTestCase + * @tc.desc: SetNotificationsEnabledForSpecialBundle + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(BenchmarkNotificationService, SetNotificationsEnabledForSpecialBundleTestCase)(benchmark::State &state) +{ + sptr bundleOption = new NotificationBundleOption("bundleName", 1000); + while (state.KeepRunning()) { + ErrCode errCode = advancedNotificationService_->SetNotificationsEnabledForSpecialBundle( + std::string(), bundleOption, true); + if (errCode != ERR_OK) { + state.SkipWithError("SetNotificationsEnabledForSpecialBundleTestCase failed."); + } + } +} +} + +// Run the benchmark +BENCHMARK_MAIN(); \ No newline at end of file diff --git a/test/common/acts/BUILD.gn b/test/common/acts/BUILD.gn index 190963cd382dd11ed485006a75c5f3a49501d2cc..d8b4ffc88334446f36a75c7ef8d5be34f289b430 100644 --- a/test/common/acts/BUILD.gn +++ b/test/common/acts/BUILD.gn @@ -11,7 +11,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//base/notification/ces_standard/event.gni") import("//build/ohos.gni") config("ansfwk_kits_test_config") { @@ -19,11 +18,8 @@ config("ansfwk_kits_test_config") { include_dirs = [ "//utils/native/base/include", - "//foundation/appexecfwk/standard/common/log/include", - "//foundation/appexecfwk/standard/services/bundlemgr/include", "//utils/system/safwk/native/include", "${services_path}/include", - "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "//foundation/distributedschedule/safwk/services/safwk/include", ] } diff --git a/test/common/acts/actsnotificationfuzztest/BUILD.gn b/test/common/acts/actsnotificationfuzztest/BUILD.gn index 02432ad5b039a0a059db7e3595808b7b3f8d7b71..6a5f25374dbe45750c7f14dcdf7b615359c3e422 100644 --- a/test/common/acts/actsnotificationfuzztest/BUILD.gn +++ b/test/common/acts/actsnotificationfuzztest/BUILD.gn @@ -35,16 +35,11 @@ ohos_systemtest("ActsNotificationFuzzTest") { "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", "//base/notification/ans_standard/services/ans/include", "//third_party/json/single_include", - "//foundation/appexecfwk/standard/kits/appkit/native/app/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/appexecfwk_base/include", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/multimodalinput/input/interfaces/native/innerkits/event/include", "//foundation/aafwk/standard/frameworks/kits/app/native/app/include/task", - "//foundation/aafwk/standard/common/task_dispatcher/include/threading", - "//foundation/aafwk/standard/common/task_dispatcher/include/dispatcher", - "//foundation/aafwk/standard/common/task_dispatcher/include/task", ] cflags = [] @@ -54,14 +49,11 @@ ohos_systemtest("ActsNotificationFuzzTest") { } deps = [ - "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//base/global/resource_management/frameworks/resmgr:global_resmgr", "//base/notification/ans_standard/frameworks/ans/core:ans_core", "//base/notification/ans_standard/frameworks/ans/native:ans_innerkits", "//base/notification/ans_standard/frameworks/wantagent:native_wantagent", "//base/notification/ans_standard/services/ans:ans_targets", - "//base/notification/ces_standard/frameworks/common:libevent_common", - "//base/notification/ces_standard/frameworks/native:cesfwk_innerkits", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/multimodalinput/input/frameworks/proxy:libmmi-client", @@ -80,7 +72,7 @@ ohos_systemtest("ActsNotificationFuzzTest") { "ability_runtime:abilitykit_native", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "dmsfwk_standard:zuri", + "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/test/fuzztest/BUILD.gn b/test/fuzztest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fe3200325902e967e047390da07dc03684500c9f --- /dev/null +++ b/test/fuzztest/BUILD.gn @@ -0,0 +1,33 @@ +# 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. + +import("//base/notification/ans_standard/notification.gni") + +group("fuzztest") { + testonly = true + + deps = [ + "addnotificationslotgroups_fuzzer:AddNotificationSlotGroupsFuzzTest", + "addnotificationslots_fuzzer:AddNotificationSlotsFuzzTest", + "addslotbytype_fuzzer:AddSlotByTypeFuzzTest", + "cancelnotification_fuzzer:CancelNotificationFuzzTest", + "getnotificationslot_fuzzer:GetNotificationSlotFuzzTest", + "getnotificationslotgroup_fuzzer:GetNotificationSlotGroupFuzzTest", + "getnotificationslotnumasbundle_fuzzer:GetNotificationSlotNumAsBundleFuzzTest", + "publishnotification_fuzzer:PublishNotificationFuzzTest", + "removenotification_fuzzer:RemoveNotificationFuzzTest", + "removenotificationslot_fuzzer:RemoveNotificationSlotFuzzTest", + "removenotificationslotgroup_fuzzer:RemoveNotificationSlotGroupFuzzTest", + "setnotificationbadgenum_fuzzer:SetNotificationBadgeNumFuzzTest", + ] +} diff --git a/test/fuzztest/addnotificationslotgroups_fuzzer/BUILD.gn b/test/fuzztest/addnotificationslotgroups_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f6ab4a7c5f0d757acb90d69f739743050ff18194 --- /dev/null +++ b/test/fuzztest/addnotificationslotgroups_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("AddNotificationSlotGroupsFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/addnotificationslotgroups_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "addnotificationslotgroups_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":AddNotificationSlotGroupsFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/addnotificationslotgroups_fuzzer/addnotificationslotgroups_fuzzer.cpp b/test/fuzztest/addnotificationslotgroups_fuzzer/addnotificationslotgroups_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49af1e97c6399ccd8f4d706b44647469bb63ae77 --- /dev/null +++ b/test/fuzztest/addnotificationslotgroups_fuzzer/addnotificationslotgroups_fuzzer.cpp @@ -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. + */ + +#include "addnotificationslotgroups_fuzzer.h" + +#define private public +#include "notification_helper.h" +#undef private + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + std::string description = reinterpret_cast(data); + Notification::NotificationSlotGroup group; + group.SetDescription(description); + + Notification::NotificationSlot slot; + std::vector slots; + slots.emplace_back(slot); + group.SetSlots(slots); + + std::vector groups; + groups.emplace_back(group); + return Notification::NotificationHelper::AddNotificationSlotGroups(groups) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/addnotificationslotgroups_fuzzer/addnotificationslotgroups_fuzzer.h b/test/fuzztest/addnotificationslotgroups_fuzzer/addnotificationslotgroups_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..ff2c49f89ab1080e9b15a705079d77b1f3d32cf3 --- /dev/null +++ b/test/fuzztest/addnotificationslotgroups_fuzzer/addnotificationslotgroups_fuzzer.h @@ -0,0 +1,29 @@ +/* + * 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 TEST_FUZZTEST_ADDNOTIFICATIONSLOTGROUPS_FUZZER_ADDNOTIFICATIONSLOTGROUPS_FUZZER_H +#define TEST_FUZZTEST_ADDNOTIFICATIONSLOTGROUPS_FUZZER_ADDNOTIFICATIONSLOTGROUPS_FUZZER_H + +#define FUZZ_PROJECT_NAME "addnotificationslotgroups_fuzzer" + +#include + +uint32_t U32_AT(const uint8_t *ptr) +{ + // convert fuzz input data to an integer + return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; +} + +#endif // TEST_FUZZTEST_ADDNOTIFICATIONSLOTGROUPS_FUZZER_ADDNOTIFICATIONSLOTGROUPS_FUZZER_H diff --git a/test/fuzztest/addnotificationslotgroups_fuzzer/corpus/init b/test/fuzztest/addnotificationslotgroups_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/addnotificationslotgroups_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/addnotificationslotgroups_fuzzer/project.xml b/test/fuzztest/addnotificationslotgroups_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/addnotificationslotgroups_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/addnotificationslots_fuzzer/BUILD.gn b/test/fuzztest/addnotificationslots_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a3922757475a21542f596c74487158c14862928a --- /dev/null +++ b/test/fuzztest/addnotificationslots_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("AddNotificationSlotsFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/addnotificationslots_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "addnotificationslots_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":AddNotificationSlotsFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/addnotificationslots_fuzzer/addnotificationslots_fuzzer.cpp b/test/fuzztest/addnotificationslots_fuzzer/addnotificationslots_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30aa44aad3dcd3e8c08301bd052c4b10c1ad3d86 --- /dev/null +++ b/test/fuzztest/addnotificationslots_fuzzer/addnotificationslots_fuzzer.cpp @@ -0,0 +1,64 @@ +/* + * 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. + */ + +#include "addnotificationslots_fuzzer.h" + +#include "notification_helper.h" + +constexpr uint8_t ENABLE = 2; +constexpr uint8_t SLOT_LEVEL_NUM = 6; +constexpr uint8_t SLOT_VISIBLENESS_TYPE_NUM = 4; +constexpr uint8_t SLOT_TYPE_NUM = 5; + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + std::string stringData = reinterpret_cast(data); + + Notification::NotificationSlot slot; + slot.SetDescription(stringData); + slot.SetEnableLight(*data % ENABLE); + slot.SetEnableVibration(*data % ENABLE); + slot.SetLedLightColor(U32_AT(data)); + + uint8_t level = *data % SLOT_LEVEL_NUM; + Notification::NotificationSlot::NotificationLevel notificatoinLevel = + Notification::NotificationSlot::NotificationLevel(level); + slot.SetLevel(notificatoinLevel); + + uint8_t visibleness = *data % SLOT_VISIBLENESS_TYPE_NUM; + Notification::NotificationConstant::VisiblenessType visiblenessType = + Notification::NotificationConstant::VisiblenessType(visibleness); + slot.SetLockscreenVisibleness(visiblenessType); + + slot.SetSlotGroup(stringData); + + uint8_t type = *data % SLOT_TYPE_NUM; + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType(type); + slot.SetType(slotType); + + std::vector slots; + slots.emplace_back(slot); + return Notification::NotificationHelper::AddNotificationSlots(slots) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/addnotificationslots_fuzzer/addnotificationslots_fuzzer.h b/test/fuzztest/addnotificationslots_fuzzer/addnotificationslots_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..5b3992afcb68da4bed2b68b1087ea9e4da1405f8 --- /dev/null +++ b/test/fuzztest/addnotificationslots_fuzzer/addnotificationslots_fuzzer.h @@ -0,0 +1,29 @@ +/* + * 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 TEST_FUZZTEST_ADDNOTIFICATIONSLOTS_FUZZER_ADDNOTIFICATIONSLOTS_FUZZER_H +#define TEST_FUZZTEST_ADDNOTIFICATIONSLOTS_FUZZER_ADDNOTIFICATIONSLOTS_FUZZER_H + +#define FUZZ_PROJECT_NAME "addnotificationslots_fuzzer" + +#include + +uint32_t U32_AT(const uint8_t *ptr) +{ + // convert fuzz input data to an integer + return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; +} + +#endif // TEST_FUZZTEST_ADDNOTIFICATIONSLOTS_FUZZER_ADDNOTIFICATIONSLOTS_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/addnotificationslots_fuzzer/corpus/init b/test/fuzztest/addnotificationslots_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/addnotificationslots_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/addnotificationslots_fuzzer/project.xml b/test/fuzztest/addnotificationslots_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/addnotificationslots_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/addslotbytype_fuzzer/BUILD.gn b/test/fuzztest/addslotbytype_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7fefb92e5c6fb57b79af727bc17a2247f34a17b1 --- /dev/null +++ b/test/fuzztest/addslotbytype_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("AddSlotByTypeFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/addslotbytype_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "addslotbytype_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":AddSlotByTypeFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/addslotbytype_fuzzer/addslotbytype_fuzzer.cpp b/test/fuzztest/addslotbytype_fuzzer/addslotbytype_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..545293a851903c1b094508f533a85cd90f55f481 --- /dev/null +++ b/test/fuzztest/addslotbytype_fuzzer/addslotbytype_fuzzer.cpp @@ -0,0 +1,37 @@ +/* + * 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. + */ + +#include "addslotbytype_fuzzer.h" + +#include "notification_helper.h" + +constexpr uint8_t SLOT_TYPE_NUM = 5; + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + uint8_t type = *data % SLOT_TYPE_NUM; + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType(type); + return Notification::NotificationHelper::AddSlotByType(slotType) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/addslotbytype_fuzzer/addslotbytype_fuzzer.h b/test/fuzztest/addslotbytype_fuzzer/addslotbytype_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..a53388f4245e771bfe9f46455d624a52133ce736 --- /dev/null +++ b/test/fuzztest/addslotbytype_fuzzer/addslotbytype_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 TEST_FUZZTEST_ADDSLOTBYTYPE_FUZZER_ADDSLOTBYTYPE_FUZZER_H +#define TEST_FUZZTEST_ADDSLOTBYTYPE_FUZZER_ADDSLOTBYTYPE_FUZZER_H + +#define FUZZ_PROJECT_NAME "AddSlotByType_fuzzer" + +#endif // TEST_FUZZTEST_ADDSLOTBYTYPE_FUZZER_ADDSLOTBYTYPE_FUZZER_H diff --git a/test/fuzztest/addslotbytype_fuzzer/corpus/init b/test/fuzztest/addslotbytype_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/addslotbytype_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/addslotbytype_fuzzer/project.xml b/test/fuzztest/addslotbytype_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/addslotbytype_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/cancelnotification_fuzzer/BUILD.gn b/test/fuzztest/cancelnotification_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e30e01020dce5a1c2b00fc752bf91d83557fafc3 --- /dev/null +++ b/test/fuzztest/cancelnotification_fuzzer/BUILD.gn @@ -0,0 +1,55 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("CancelNotificationFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "//base/notification/ans_standard/test/fuzztest/cancelnotification_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "cancelnotification_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":CancelNotificationFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/cancelnotification_fuzzer/cancelnotification_fuzzer.cpp b/test/fuzztest/cancelnotification_fuzzer/cancelnotification_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5d76b9da5cdfab63f92b36d1be67f780954b5b9 --- /dev/null +++ b/test/fuzztest/cancelnotification_fuzzer/cancelnotification_fuzzer.cpp @@ -0,0 +1,35 @@ +/* + * 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. + */ + +#include "cancelnotification_fuzzer.h" + +#include "notification_helper.h" + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + std::string label = reinterpret_cast(data); + int32_t notificationId = static_cast(U32_AT(data)); + return Notification::NotificationHelper::CancelNotification(label, notificationId) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/cancelnotification_fuzzer/cancelnotification_fuzzer.h b/test/fuzztest/cancelnotification_fuzzer/cancelnotification_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..51bb27c9da63d87f29f127d91528758c1682c78b --- /dev/null +++ b/test/fuzztest/cancelnotification_fuzzer/cancelnotification_fuzzer.h @@ -0,0 +1,28 @@ +/* + * 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 TEST_FUZZTEST_CANCELNOTIFICATION_FUZZER_CANCELNOTIFICATION_FUZZER_H +#define TEST_FUZZTEST_CANCELNOTIFICATION_FUZZER_CANCELNOTIFICATION_FUZZER_H + +#define FUZZ_PROJECT_NAME "cancelnotification_fuzzer" + +#include + +uint32_t U32_AT(const uint8_t *ptr) +{ + // convert fuzz input data to an integer + return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; +} +#endif // TEST_FUZZTEST_CANCELNOTIFICATION_FUZZER_CANCELNOTIFICATION_FUZZER_H diff --git a/test/fuzztest/cancelnotification_fuzzer/corpus/init b/test/fuzztest/cancelnotification_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/cancelnotification_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/cancelnotification_fuzzer/project.xml b/test/fuzztest/cancelnotification_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/cancelnotification_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/getnotificationslot_fuzzer/BUILD.gn b/test/fuzztest/getnotificationslot_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..da01174f821b678b3e509161a588f2daa6627953 --- /dev/null +++ b/test/fuzztest/getnotificationslot_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("GetNotificationSlotFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/getnotificationslot_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "getnotificationslot_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":GetNotificationSlotFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/getnotificationslot_fuzzer/corpus/init b/test/fuzztest/getnotificationslot_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/getnotificationslot_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/getnotificationslot_fuzzer/getnotificationslot_fuzzer.cpp b/test/fuzztest/getnotificationslot_fuzzer/getnotificationslot_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efa8cf4679240edf4b768b60282978381518d8b8 --- /dev/null +++ b/test/fuzztest/getnotificationslot_fuzzer/getnotificationslot_fuzzer.cpp @@ -0,0 +1,38 @@ +/* + * 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. + */ + +#include "getnotificationslot_fuzzer.h" + +#include "notification_helper.h" + +constexpr uint8_t SLOT_TYPE_NUM = 5; + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + uint8_t type = *data % SLOT_TYPE_NUM; + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType(type); + sptr slot = nullptr; + return Notification::NotificationHelper::GetNotificationSlot(slotType, slot) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/getnotificationslot_fuzzer/getnotificationslot_fuzzer.h b/test/fuzztest/getnotificationslot_fuzzer/getnotificationslot_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..d704a6a7a3aa2712bc1afd23151d502028bc591e --- /dev/null +++ b/test/fuzztest/getnotificationslot_fuzzer/getnotificationslot_fuzzer.h @@ -0,0 +1,29 @@ +/* + * 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 TEST_FUZZTEST_GETNOTIFICATIONSLOT_FUZZER_GETNOTIFICATIONSLOT_FUZZER_H +#define TEST_FUZZTEST_GETNOTIFICATIONSLOT_FUZZER_GETNOTIFICATIONSLOT_FUZZER_H + +#define FUZZ_PROJECT_NAME "getnotificationslot_fuzzer" + +#include + +uint32_t U32_AT(const uint8_t *ptr) +{ + // convert fuzz input data to an integer + return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; +} + +#endif // TEST_FUZZTEST_GETNOTIFICATIONSLOT_FUZZER_GETNOTIFICATIONSLOT_FUZZER_H diff --git a/test/fuzztest/getnotificationslot_fuzzer/project.xml b/test/fuzztest/getnotificationslot_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/getnotificationslot_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/getnotificationslotgroup_fuzzer/BUILD.gn b/test/fuzztest/getnotificationslotgroup_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0d74bc02adb9ac1073efcb7dea6d7fb1a1dfd827 --- /dev/null +++ b/test/fuzztest/getnotificationslotgroup_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("GetNotificationSlotGroupFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/getnotificationslotgroup_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "getnotificationslotgroup_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":GetNotificationSlotGroupFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/getnotificationslotgroup_fuzzer/corpus/init b/test/fuzztest/getnotificationslotgroup_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/getnotificationslotgroup_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/getnotificationslotgroup_fuzzer/getnotificationslotgroup_fuzzer.cpp b/test/fuzztest/getnotificationslotgroup_fuzzer/getnotificationslotgroup_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8529f71dd225cabfa0f365789e881c08ba8c8f2c --- /dev/null +++ b/test/fuzztest/getnotificationslotgroup_fuzzer/getnotificationslotgroup_fuzzer.cpp @@ -0,0 +1,35 @@ +/* + * 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. + */ + +#include "getnotificationslotgroup_fuzzer.h" + +#include "notification_helper.h" + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + std::string groupId = reinterpret_cast(data); + sptr group = nullptr; + return Notification::NotificationHelper::GetNotificationSlotGroup(groupId, group) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/getnotificationslotgroup_fuzzer/getnotificationslotgroup_fuzzer.h b/test/fuzztest/getnotificationslotgroup_fuzzer/getnotificationslotgroup_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..529d8be3c3f3804c3fab595ff21632801cf3d93f --- /dev/null +++ b/test/fuzztest/getnotificationslotgroup_fuzzer/getnotificationslotgroup_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 TEST_FUZZTEST_GETNOTIFICATIONSLOTGROUP_FUZZER_GETNOTIFICATIONSLOTGROUP_FUZZER_H +#define TEST_FUZZTEST_GETNOTIFICATIONSLOTGROUP_FUZZER_GETNOTIFICATIONSLOTGROUP_FUZZER_H + +#define FUZZ_PROJECT_NAME "getnotificationslotgroups_fuzzer" + +#endif // TEST_FUZZTEST_GETNOTIFICATIONSLOTGROUP_FUZZER_GETNOTIFICATIONSLOTGROUP_FUZZER_H diff --git a/test/fuzztest/getnotificationslotgroup_fuzzer/project.xml b/test/fuzztest/getnotificationslotgroup_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/getnotificationslotgroup_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/getnotificationslotnumasbundle_fuzzer/BUILD.gn b/test/fuzztest/getnotificationslotnumasbundle_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..27790672e50602dfb808ac72c9b1e4c565934c05 --- /dev/null +++ b/test/fuzztest/getnotificationslotnumasbundle_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("GetNotificationSlotNumAsBundleFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/getnotificationslotnumasbundle_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "getnotificationslotnumasbundle_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":GetNotificationSlotNumAsBundleFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/getnotificationslotnumasbundle_fuzzer/corpus/init b/test/fuzztest/getnotificationslotnumasbundle_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/getnotificationslotnumasbundle_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/getnotificationslotnumasbundle_fuzzer/getnotificationslotnumasbundle_fuzzer.cpp b/test/fuzztest/getnotificationslotnumasbundle_fuzzer/getnotificationslotnumasbundle_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14da1968cc0435f92aa3d3c703e2ac71c9fc7e75 --- /dev/null +++ b/test/fuzztest/getnotificationslotnumasbundle_fuzzer/getnotificationslotnumasbundle_fuzzer.cpp @@ -0,0 +1,39 @@ +/* + * 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. + */ + +#include "getnotificationslotnumasbundle_fuzzer.h" + +#include "notification_helper.h" + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + Notification::NotificationBundleOption bundleOption; + std::string bundleName = reinterpret_cast(data); + bundleOption.SetBundleName(bundleName); + int32_t uid = static_cast(U32_AT(data)); + bundleOption.SetUid(uid); + uint64_t num; + return Notification::NotificationHelper::GetNotificationSlotNumAsBundle(bundleOption, num) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/getnotificationslotnumasbundle_fuzzer/getnotificationslotnumasbundle_fuzzer.h b/test/fuzztest/getnotificationslotnumasbundle_fuzzer/getnotificationslotnumasbundle_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..7f361f4f35435f5a0ad1488f16f94e5e73c174d4 --- /dev/null +++ b/test/fuzztest/getnotificationslotnumasbundle_fuzzer/getnotificationslotnumasbundle_fuzzer.h @@ -0,0 +1,29 @@ +/* + * 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 TEST_FUZZTEST_GETNOTIFICATIONSLOTNUMASBUNDLE_FUZZER_GETNOTIFICATIONSLOTNUMASBUNDLE_FUZZER_H +#define TEST_FUZZTEST_GETNOTIFICATIONSLOTNUMASBUNDLE_FUZZER_GETNOTIFICATIONSLOTNUMASBUNDLE_FUZZER_H + +#include + +#define FUZZ_PROJECT_NAME "getnotificationslotnumasbundle_fuzzer" + +uint32_t U32_AT(const uint8_t *ptr) +{ + // convert fuzz input data to an integer + return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; +} + +#endif // TEST_FUZZTEST_GETNOTIFICATIONSLOTNUMASBUNDLE_FUZZER_GETNOTIFICATIONSLOTNUMASBUNDLE_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/getnotificationslotnumasbundle_fuzzer/project.xml b/test/fuzztest/getnotificationslotnumasbundle_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/getnotificationslotnumasbundle_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/publishnotification_fuzzer/BUILD.gn b/test/fuzztest/publishnotification_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d99bd90e78e57423505bb1d6059a5830aee02961 --- /dev/null +++ b/test/fuzztest/publishnotification_fuzzer/BUILD.gn @@ -0,0 +1,53 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("PublishNotificationFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/publishnotification_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "publishnotification_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [ ":PublishNotificationFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/publishnotification_fuzzer/corpus/init b/test/fuzztest/publishnotification_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/publishnotification_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/publishnotification_fuzzer/project.xml b/test/fuzztest/publishnotification_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/publishnotification_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/publishnotification_fuzzer/publishnotification_fuzzer.cpp b/test/fuzztest/publishnotification_fuzzer/publishnotification_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e77c99167020793edcbd74cdd007cb45a55ee853 --- /dev/null +++ b/test/fuzztest/publishnotification_fuzzer/publishnotification_fuzzer.cpp @@ -0,0 +1,88 @@ +/* + * 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. + */ + +#include "publishnotification_fuzzer.h" + +#include "notification_helper.h" + +namespace OHOS { + namespace { + constexpr uint8_t ENABLE = 2; + constexpr uint8_t SLOT_TYPE_NUM = 5; + constexpr uint8_t FLAG_STATUS = 3; + } + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + std::string stringData = reinterpret_cast(data); + Notification::NotificationRequest request; + request.SetAlertOneTime(*data % ENABLE); + + int32_t style = static_cast(U32_AT(data)); + Notification::NotificationRequest::BadgeStyle badgeStyle = + Notification::NotificationRequest::BadgeStyle(style); + request.SetBadgeIconStyle(badgeStyle); + request.SetBadgeNumber(style); + request.SetClassification(stringData); + + uint32_t color = U32_AT(data); + request.SetColor(color); + request.SetColorEnabled(*data % ENABLE); + + std::shared_ptr contentType = + std::make_shared(); + contentType->SetText(stringData); + contentType->SetTitle(stringData); + contentType->SetAdditionalText(stringData); + std::shared_ptr content = + std::make_shared(contentType); + request.SetContent(content); + request.SetCountdownTimer(*data % ENABLE); + request.SetCreatorBundleName(stringData); + request.SetDeliveryTime(style); + + std::shared_ptr notificationFlages = + std::make_shared(); + int32_t soundEnabled = static_cast(*data % FLAG_STATUS); + Notification::NotificationConstant::FlagStatus sound = + Notification::NotificationConstant::FlagStatus(soundEnabled); + notificationFlages->SetSoundEnabled(sound); + notificationFlages->SetVibrationEnabled(sound); + request.SetFlags(notificationFlages); + + Notification::NotificationRequest::GroupAlertType groupAlertType = + Notification::NotificationRequest::GroupAlertType(color); + request.SetGroupAlertType(groupAlertType); + + request.SetGroupName(stringData); + request.SetGroupOverview(*data % ENABLE); + request.SetLabel(stringData); + request.SetNotificationId(style); + request.SetOwnerBundleName(stringData); + + uint8_t types = *data % SLOT_TYPE_NUM; + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType(types); + request.SetSlotType(slotType); + + return Notification::NotificationHelper::PublishNotification(stringData, request) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/publishnotification_fuzzer/publishnotification_fuzzer.h b/test/fuzztest/publishnotification_fuzzer/publishnotification_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..cf6356f20f33aa7e4d950aa3049aeb2cc616c0f9 --- /dev/null +++ b/test/fuzztest/publishnotification_fuzzer/publishnotification_fuzzer.h @@ -0,0 +1,29 @@ +/* + * 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 TEST_FUZZTEST_PUBLISHNOTIFICATION_FUZZER_PUBLISHNOTIFICATION_FUZZER_H +#define TEST_FUZZTEST_PUBLISHNOTIFICATION_FUZZER_PUBLISHNOTIFICATION_FUZZER_H + +#define FUZZ_PROJECT_NAME "publishnotification_fuzzer" + +#include + +uint32_t U32_AT(const uint8_t *ptr) +{ + // convert fuzz input data to an integer + return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; +} + +#endif // TEST_FUZZTEST_PUBLISHNOTIFICATION_FUZZER_PUBLISHNOTIFICATION_FUZZER_H diff --git a/test/fuzztest/removenotification_fuzzer/BUILD.gn b/test/fuzztest/removenotification_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8f12f91db56cce7cad2aca646ede5d335ac3b8e3 --- /dev/null +++ b/test/fuzztest/removenotification_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("RemoveNotificationFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/removenotification_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "removenotification_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":RemoveNotificationFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/removenotification_fuzzer/corpus/init b/test/fuzztest/removenotification_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/removenotification_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/removenotification_fuzzer/project.xml b/test/fuzztest/removenotification_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/removenotification_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/removenotification_fuzzer/removenotification_fuzzer.cpp b/test/fuzztest/removenotification_fuzzer/removenotification_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0ffe410bbe1fcbbaf80df4e3d106464c428be04 --- /dev/null +++ b/test/fuzztest/removenotification_fuzzer/removenotification_fuzzer.cpp @@ -0,0 +1,35 @@ +/* + * 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. + */ + +#include "removenotification_fuzzer.h" + +#include "notification_helper.h" + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + std::string key = reinterpret_cast(data); + return Notification::NotificationHelper::RemoveNotification(key); + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} + diff --git a/test/fuzztest/removenotification_fuzzer/removenotification_fuzzer.h b/test/fuzztest/removenotification_fuzzer/removenotification_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..9ce1fca6dfc578b9ce27ee7855f3b5253f19886c --- /dev/null +++ b/test/fuzztest/removenotification_fuzzer/removenotification_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 TEST_FUZZTEST_REMOVENOTIFICATION_FUZZER_REMOVENOTIFICATION_FUZZER_H +#define TEST_FUZZTEST_REMOVENOTIFICATION_FUZZER_REMOVENOTIFICATION_FUZZER_H + +#define FUZZ_PROJECT_NAME "removenotification_fuzzer" + +#endif // TEST_FUZZTEST_REMOVENOTIFICATION_FUZZER_REMOVENOTIFICATION_FUZZER_H diff --git a/test/fuzztest/removenotificationslot_fuzzer/BUILD.gn b/test/fuzztest/removenotificationslot_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d39af9af2832df3c354c29a5c4fbe39513b05176 --- /dev/null +++ b/test/fuzztest/removenotificationslot_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("RemoveNotificationSlotFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/removenotificationslot_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "removenotificationslot_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":RemoveNotificationSlotFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/removenotificationslot_fuzzer/corpus/init b/test/fuzztest/removenotificationslot_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/removenotificationslot_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/removenotificationslot_fuzzer/project.xml b/test/fuzztest/removenotificationslot_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/removenotificationslot_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/removenotificationslot_fuzzer/removenotificationslot_fuzzer.cpp b/test/fuzztest/removenotificationslot_fuzzer/removenotificationslot_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e10f807c3df789f482f39b2635321edc4d85cccc --- /dev/null +++ b/test/fuzztest/removenotificationslot_fuzzer/removenotificationslot_fuzzer.cpp @@ -0,0 +1,37 @@ +/* + * 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. + */ + +#include "removenotificationslot_fuzzer.h" + +#include "notification_helper.h" + +constexpr uint8_t SLOT_TYPE_NUM = 5; + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + uint8_t type = *data % SLOT_TYPE_NUM; + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType(type); + return Notification::NotificationHelper::RemoveNotificationSlot(slotType) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/removenotificationslot_fuzzer/removenotificationslot_fuzzer.h b/test/fuzztest/removenotificationslot_fuzzer/removenotificationslot_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..4649800f301e175be29980251df58c164ede57c2 --- /dev/null +++ b/test/fuzztest/removenotificationslot_fuzzer/removenotificationslot_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 TEST_FUZZTEST_REMOVENOTIFICATIONSLOT_FUZZER_REMOVENOTIFICATIONSLOT_FUZZER_H +#define TEST_FUZZTEST_REMOVENOTIFICATIONSLOT_FUZZER_REMOVENOTIFICATIONSLOT_FUZZER_H + +#define FUZZ_PROJECT_NAME "removenotificationslot_fuzzer" + +#endif // TEST_FUZZTEST_REMOVENOTIFICATIONSLOT_FUZZER_REMOVENOTIFICATIONSLOT_FUZZER_H diff --git a/test/fuzztest/removenotificationslotgroup_fuzzer/BUILD.gn b/test/fuzztest/removenotificationslotgroup_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..07b196af99878c68062a0475f5930d94b143ca22 --- /dev/null +++ b/test/fuzztest/removenotificationslotgroup_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("RemoveNotificationSlotGroupFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/removenotificationslotgroup_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "removenotificationslotgroup_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":RemoveNotificationSlotGroupFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/removenotificationslotgroup_fuzzer/corpus/init b/test/fuzztest/removenotificationslotgroup_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/removenotificationslotgroup_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/removenotificationslotgroup_fuzzer/project.xml b/test/fuzztest/removenotificationslotgroup_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/removenotificationslotgroup_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/removenotificationslotgroup_fuzzer/removenotificationslotgroup_fuzzer.cpp b/test/fuzztest/removenotificationslotgroup_fuzzer/removenotificationslotgroup_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50b4ede4bea9d7b84f9f62028a9f79e5b63763fe --- /dev/null +++ b/test/fuzztest/removenotificationslotgroup_fuzzer/removenotificationslotgroup_fuzzer.cpp @@ -0,0 +1,34 @@ +/* + * 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. + */ + +#include "removenotificationslotgroup_fuzzer.h" + +#include "notification_helper.h" + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + std::string slotGroupId = reinterpret_cast(data); + return Notification::NotificationHelper::RemoveNotificationSlotGroup(slotGroupId) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/removenotificationslotgroup_fuzzer/removenotificationslotgroup_fuzzer.h b/test/fuzztest/removenotificationslotgroup_fuzzer/removenotificationslotgroup_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..2b1fd85bc9b702c58edc1af3575c6aae67d10389 --- /dev/null +++ b/test/fuzztest/removenotificationslotgroup_fuzzer/removenotificationslotgroup_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 TEST_FUZZTEST_REMOVENOTIFICATIONSLOTGROUP_FUZZER_REMOVENOTIFICATIONSLOTGROUP_FUZZER_H +#define TEST_FUZZTEST_REMOVENOTIFICATIONSLOTGROUP_FUZZER_REMOVENOTIFICATIONSLOTGROUP_FUZZER_H + +#define FUZZ_PROJECT_NAME "removenotificationslotgroup_fuzzer" + +#endif // TEST_FUZZTEST_REMOVENOTIFICATIONSLOTGROUP_FUZZER_REMOVENOTIFICATIONSLOTGROUP_FUZZER_H diff --git a/test/fuzztest/setnotificationbadgenum_fuzzer/BUILD.gn b/test/fuzztest/setnotificationbadgenum_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3900332f4cd10d78df8883c98c359bba2b854985 --- /dev/null +++ b/test/fuzztest/setnotificationbadgenum_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//base/notification/ans_standard/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") +module_output_path = "ans_standard/services" + +##############################fuzztest########################################## +ohos_fuzztest("SetNotificationBadgeNumFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/notification/ans_standard/test/fuzztest/setnotificationbadgenum_fuzzer" + + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "setnotificationbadgenum_fuzzer.cpp" ] + + deps = [ + "${frameworks_path}/ans/native:ans_innerkits", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "hiviewdfx_hilog_native:libhilog", + "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":SetNotificationBadgeNumFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/setnotificationbadgenum_fuzzer/corpus/init b/test/fuzztest/setnotificationbadgenum_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..1b910144fb1ff33a40a44b1d2a491b1ab05b598b --- /dev/null +++ b/test/fuzztest/setnotificationbadgenum_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/fuzztest/setnotificationbadgenum_fuzzer/project.xml b/test/fuzztest/setnotificationbadgenum_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/setnotificationbadgenum_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/setnotificationbadgenum_fuzzer/setnotificationbadgenum_fuzzer.cpp b/test/fuzztest/setnotificationbadgenum_fuzzer/setnotificationbadgenum_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b89068681e6e83ca3edccc0a63f93f1aee29477a --- /dev/null +++ b/test/fuzztest/setnotificationbadgenum_fuzzer/setnotificationbadgenum_fuzzer.cpp @@ -0,0 +1,33 @@ +/* + * 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. + */ + +#include "setnotificationbadgenum_fuzzer.h" + +#include "notification_helper.h" + +namespace OHOS { + bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) + { + return Notification::NotificationHelper::SetNotificationBadgeNum(U32_AT(data)) == ERR_OK; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/test/fuzztest/setnotificationbadgenum_fuzzer/setnotificationbadgenum_fuzzer.h b/test/fuzztest/setnotificationbadgenum_fuzzer/setnotificationbadgenum_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..1d2517607943541672dd1031a7a9d561146b0126 --- /dev/null +++ b/test/fuzztest/setnotificationbadgenum_fuzzer/setnotificationbadgenum_fuzzer.h @@ -0,0 +1,29 @@ +/* + * 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 TEST_FUZZTEST_SETNOTIFICATIONBADGENUM_FUZZER_SETNOTIFICATIONBADGENUM_FUZZER_H +#define TEST_FUZZTEST_SETNOTIFICATIONBADGENUM_FUZZER_SETNOTIFICATIONBADGENUM_FUZZER_H + +#include + +#define FUZZ_PROJECT_NAME "setnotificationbadgenum_fuzzer" + +uint32_t U32_AT(const uint8_t *ptr) +{ + // convert fuzz input data to an integer + return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; +} + +#endif // TEST_FUZZTEST_SETNOTIFICATIONBADGENUM_FUZZER_SETNOTIFICATIONBADGENUM_FUZZER_H \ No newline at end of file diff --git a/test/resource/ansSTSlotGroupTest/BUILD.gn b/test/resource/ansSTSlotGroupTest/BUILD.gn index df98efbd15490f289a1bcf22e6ba55ba3cccae15..43f672940e622815fa8e23279cdd3689ab572624 100644 --- a/test/resource/ansSTSlotGroupTest/BUILD.gn +++ b/test/resource/ansSTSlotGroupTest/BUILD.gn @@ -27,10 +27,7 @@ config("ansSTSlotGroupTestConfig") { include_dirs = [ "${SUBDEMOSYSTEM_DIR}/include", "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", - "//foundation/appexecfwk/standard/services/bundlemgr/include", "//foundation/aafwk/standard/services/abilitymgr/include", - "//foundation/appexecfwk/standard/common/log/include", - "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${interfaces_path}/innerkits/ans/native/include", ] @@ -49,8 +46,6 @@ ohos_shared_library("libraryAnsSTSlotGroupTest") { "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", - "//foundation/appexecfwk/standard/common:libappexecfwk_common", - "//foundation/appexecfwk/standard/services/bundlemgr:libbms", "//utils/native/base:utilsbase", ] diff --git a/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h b/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h index d0a492b1dc35f126b1547211ebc80856c4f78afb..bee6ada540c8d240dd2fb5ab2ae8f9215478f4a0 100644 --- a/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h +++ b/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h @@ -33,6 +33,12 @@ struct FuzzTestData { class NotificationFuzzConfigParser { public: + /** + * @brief Loads interface list from the configuration file. + * + * @param path The path of configuration file. + * @param ftd Records the configuration file. + */ void ParseFromFile4FuzzTest(const std::string &path, FuzzTestData &ftd) const { std::cout << __func__ << std::endl; diff --git a/test/resource/notificationfuzztest/include/notificationfuzztestmanager.h b/test/resource/notificationfuzztest/include/notificationfuzztestmanager.h index cce89899fc0c3754f415a68d1d0dafe1f4f39c6d..e1c48e64b3249c9ef0241e254f4e5a8ac43b1d9b 100644 --- a/test/resource/notificationfuzztest/include/notificationfuzztestmanager.h +++ b/test/resource/notificationfuzztest/include/notificationfuzztestmanager.h @@ -24,8 +24,18 @@ namespace Notification { class NotificationFuzzTestManager { public: using Ptr = std::shared_ptr; + + /** + * @brief Default deconstructor used to deconstruct. + */ ~NotificationFuzzTestManager() {} + + /** + * @brief Obtains the instance of the fuzz test. + * + * @return Returns the instance of the fuzz test. + */ static Ptr GetInstance() { if (instance == nullptr) { @@ -35,6 +45,9 @@ public: return instance; } + /** + * @brief Starts the fuzz test. + */ void StartFuzzTest(); private: diff --git a/test/resource/notificationfuzztest/include/notificationgetparam.h b/test/resource/notificationfuzztest/include/notificationgetparam.h index 73b884065c2ed19efc665329777e17384426b7de..873d64e3adec0db685a4c1ef282469f3a81a38e1 100644 --- a/test/resource/notificationfuzztest/include/notificationgetparam.h +++ b/test/resource/notificationfuzztest/include/notificationgetparam.h @@ -24,15 +24,11 @@ #include "ability_manager.h" #include "ability_manager_interface.h" #include "ability_manager_service.h" -#include "base_task_dispatcher.h" #include "data_uri_utils.h" #include "element_name.h" #include "event_runner.h" #include "launcher_ability_info.h" #include "launcher_service.h" -#include "spec_task_dispatcher.h" -#include "task_dispatcher.h" -#include "task_dispatcher_context.h" #include "uri.h" #include "want.h" @@ -148,54 +144,120 @@ std::shared_ptr GetParamNotifi OHOS::Notification::NotificationConstant::DoNotDisturbType GetParamDoNotDisturbType(); class TestRemoteObject : public IRemoteObject { public: + /** + * @brief Default constructor used to construct. + */ TestRemoteObject(); + + /** + * @brief Default deconstructor used to deconstruct. + */ ~TestRemoteObject(); + /** + * @brief Override GetObjectRefCount. + * + * @return Returns a fixed value of type int_32. + */ int32_t GetObjectRefCount() override { return 0; } + /** + * @brief Override SendRequest. + * + * @param code The uint32_t type input parameter. + * @param data The MessageParcel type input parameter. + * @param reply The MessageOption type input parameter. + * @param option The MessageOption type input parameter. + * @return Returns a fixed value of type int. + */ int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override { return 0; } + /** + * @brief Override IsProxyObject. + * + * @return Returns a fixed value of type bool. + */ bool IsProxyObject() const override { return true; } + /** + * @brief Override CheckObjectLegality. + * + * @return Returns a fixed value of type bool. + */ bool CheckObjectLegality() const override { return true; } + /** + * @brief Override AddDeathRecipient. + * + * @param recipient The DeathRecipient type point input parameter. + * @return Returns a fixed value of type bool. + */ bool AddDeathRecipient(const sptr &recipient) override { return true; } + /** + * @brief Override RemoveDeathRecipient. + * + * @param recipient The DeathRecipient type point input parameter. + * @return Returns a fixed value of type bool. + */ bool RemoveDeathRecipient(const sptr &recipient) override { return true; } + /** + * @brief Override Marshalling. + * + * @param parcel The Parcel type input parameter. + * @return Returns a fixed value of type bool. + */ bool Marshalling(Parcel &parcel) const override { return true; } + /** + * @brief Override AsInterface. + * + * @return Returns a null pointer. + */ sptr AsInterface() override { return nullptr; } + /** + * @brief Override Dump. + * + * @param fd The int type input parameter. + * @param args The u16string type vector input parameter. + * @return Returns a fixed value of type int. + */ int Dump(int fd, const std::vector &args) override { return 0; } + /** + * @brief Override GetObjectDescriptor + * + * @return Returns a random value of type u16string. + */ std::u16string GetObjectDescriptor() const { std::u16string descriptor = std::u16string(); @@ -205,44 +267,118 @@ public: class TestIBundleStatusCallback : public OHOS::AppExecFwk::IBundleStatusCallback { public: + /** + * @brief Default constructor used to construct. + */ TestIBundleStatusCallback() {} + + /** + * @brief Override OnBundleStateChanged. + * + * @param installType The uint8_t type input parameter. + * @param resultCode The int32_t type input parameter. + * @param resultMsg The string type input parameter. + * @param bundleName The string type input parameter. + */ void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) override {} + + /** + * @brief Default deconstructor used to deconstruct. + */ virtual ~TestIBundleStatusCallback() {} }; class TestAnsSubscriber : public OHOS::Notification::NotificationSubscriber { public: + /** + * @brief Default constructor used to create subscriber. + */ TestAnsSubscriber() {} + + /** + * @brief Default deconstructor used to deconstruct. + */ ~TestAnsSubscriber() {} + + /** + * @brief Override OnConnected. + */ void OnConnected() override { std::cout << "TestAnsSubscriber OnConnected" << std::endl; mutex.unlock(); } + + /** + * @brief Override OnDisconnected. + */ void OnDisconnected() override { std::cout << "TestAnsSubscriber OnDisconnected" << std::endl; mutex.unlock(); } + + /** + * @brief Override OnDied. + */ void OnDied() override {} + + /** + * @brief Override OnUpdate. + * + * @param sortingMap The NotificationSortingMap type point input parameter. + */ void OnUpdate(const std::shared_ptr &sortingMap) override {} + + /** + * @brief Override OnDoNotDisturbDateChange. + * + * @param date The NotificationDoNotDisturbDate type point input parameter. + */ void OnDoNotDisturbDateChange(const std::shared_ptr &date) override {} + + /** + * @brief Override OnCanceled. + * + * @param request The Notification type point input parameter. + */ void OnCanceled(const std::shared_ptr &request) override {} + + /** + * @brief Override OnCanceled. + * + * @param request The Notification type point input parameter. + * @param request The NotificationSortingMap type point input parameter. + * @param deleteReason The int type input parameter. + */ void OnCanceled(const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason) override {} + + /** + * @brief Override OnConsumed. + * + * @param request The Notification type point input parameter. + */ void OnConsumed(const std::shared_ptr &request) override {} + + /** + * @brief Override OnConsumed. + * + * @param request The Notification type point input parameter. + * @param sortingMap The NotificationSortingMap type point input parameter. + */ void OnConsumed(const std::shared_ptr &request, const std::shared_ptr &sortingMap) override {} @@ -259,40 +395,102 @@ class TestCompletedCallback : public OHOS::AbilityRuntime::WantAgent::CompletedC class TestCancelListener : public OHOS::AbilityRuntime::WantAgent::CancelListener { public: + /** + * @brief Override OnCancelled. + */ void OnCancelled(int resultCode) override {} }; class TestOnPermissionChangedCallback : public OHOS::AppExecFwk::OnPermissionChangedCallback { public: + /** + * @brief Override OnChanged. + * + * @param uid Records the uid. + */ void OnChanged(const int32_t uid) override {} }; class TestAbilityLifecycleCallbacks : public OHOS::AppExecFwk::AbilityLifecycleCallbacks { public: + /** + * @brief Default constructor used to construct. + */ TestAbilityLifecycleCallbacks() = default; + + /** + * @brief Default deconstructor used to deconstruct. + */ virtual ~TestAbilityLifecycleCallbacks() = default; + + /** + * @brief Override OnAbilityStart. + * + * @param ability The ability to records the start state. + */ virtual void OnAbilityStart(const std::shared_ptr &ability) {} + + /** + * @brief Override OnAbilityInactive. + * + * @param ability The ability to records the inactive state. + */ virtual void OnAbilityInactive(const std::shared_ptr &ability) {} + + /** + * @brief Override OnAbilityBackground. + * + * @param ability The ability to records the background state. + */ virtual void OnAbilityBackground(const std::shared_ptr &ability) {} + + /** + * @brief Override OnAbilityForeground. + * + * @param ability The ability to records the foreground state. + */ virtual void OnAbilityForeground(const std::shared_ptr &ability) {} + + /** + * @brief Override OnAbilityActive. + * + * @param ability The ability to records the active state. + */ virtual void OnAbilityActive(const std::shared_ptr &ability) {} + + /** + * @brief Override OnAbilityStop. + * + * @param ability The ability to records the stop state. + */ virtual void OnAbilityStop(const std::shared_ptr &ability) {} + + /** + * @brief Override OnAbilitySaveState. + * + * @param outState Output status. + */ virtual void OnAbilitySaveState(const OHOS::AppExecFwk::PacMap &outState) {} }; class WantSender : public OHOS::AAFwk::WantSenderStub { public: + /** + * @brief Override Send. + * + * @param senderInfo Sender information. + */ void Send(OHOS::AAFwk::SenderInfo &senderInfo) override {} }; } // namespace Notification } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/test/resource/notificationfuzztest/src/notificationgetparam.cpp b/test/resource/notificationfuzztest/src/notificationgetparam.cpp index 99c54eae6e13fee5d0b66cad511cdfff6ac7c7ae..ce9232bca912cb4ec157d01cdc1f2f13f806140e 100644 --- a/test/resource/notificationfuzztest/src/notificationgetparam.cpp +++ b/test/resource/notificationfuzztest/src/notificationgetparam.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -816,11 +816,11 @@ std::vector> GetParamNotificationSptrVect std::shared_ptr GetParamPendingWant() { sptr target = new WantSender(); - sptr whitelistToken = GetParamSptrRemote(); + sptr allowlistToken = GetParamSptrRemote(); if (GetBoolParam()) { return std::make_shared(target); } else { - return std::make_shared(target, whitelistToken); + return std::make_shared(target, allowlistToken); } } std::shared_ptr GetParamWantAgent() @@ -971,16 +971,12 @@ OHOS::Notification::NotificationConstant::SubscribeResult GetParamSubscribeResul switch (GetIntParam() % INDEX_THREE) { case INDEX_ZERO: return OHOS::Notification::NotificationConstant::SubscribeResult::SUCCESS; - break; case INDEX_ONE: return OHOS::Notification::NotificationConstant::SubscribeResult::PREMISSION_FAIL; - break; case INDEX_TWO: return OHOS::Notification::NotificationConstant::SubscribeResult::RESOURCES_FAIL; - break; default: return OHOS::Notification::NotificationConstant::SubscribeResult::SUCCESS; - break; } } @@ -1005,16 +1001,12 @@ std::shared_ptr GetParamBaseTaskDispatcher switch (GetIntParam() % INDEX_THREE) { case INDEX_ZERO: return context->CreateSerialDispatcher(GetStringParam(), GetParamTaskPriority()); - break; case INDEX_ONE: return context->CreateParallelDispatcher(GetStringParam(), GetParamTaskPriority()); - break; case INDEX_TWO: return specTaskDispatcher; - break; default: return context->CreateSerialDispatcher(GetStringParam(), GetParamTaskPriority()); - break; } } diff --git a/tools/dump/BUILD.gn b/tools/dump/BUILD.gn index e894222376946e2cca99d5e069a2a0d150f1272e..0d583b0bdaba600010fae62e5df3f594c1a04b12 100644 --- a/tools/dump/BUILD.gn +++ b/tools/dump/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-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 @@ -50,6 +50,7 @@ ohos_executable("anm") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", ] external_deps += ans_standard_external_deps diff --git a/tools/dump/include/notification_shell_command.h b/tools/dump/include/notification_shell_command.h index 26fc5199e25195ffb6f9dacbaedf1ce9eb993a78..2d481dc3d8d7233c5349690bc831fc08d9f883d9 100644 --- a/tools/dump/include/notification_shell_command.h +++ b/tools/dump/include/notification_shell_command.h @@ -23,7 +23,17 @@ namespace OHOS { namespace Notification { class NotificationShellCommand : public OHOS::Notification::ShellCommand { public: + /** + * @brief The constructor. + * + * @param argc Indicates the count of arguments. + * @param argv Indicates the arguments. + */ NotificationShellCommand(int argc, char *argv[]); + + /** + * @brief The deconstructor. + */ ~NotificationShellCommand() override {}; private: diff --git a/tools/dump/include/shell_command.h b/tools/dump/include/shell_command.h index 00c14fdbe5afe0c5075af15a7ba23df05ef26154..3e335aaa3ab630e49740ea3744098a700f04ca75 100644 --- a/tools/dump/include/shell_command.h +++ b/tools/dump/include/shell_command.h @@ -27,21 +27,80 @@ namespace OHOS { namespace Notification { class ShellCommand { public: + /** + * @brief Constructor. + * + * @param argc Indicates the count of arguments. + * @param argv Indicates the arguments. + * @param name Indicates the tool name. + */ ShellCommand(int argc, char *argv[], std::string name); + + /** + * @brief Destructor. + */ virtual ~ShellCommand(); + /** + * @brief Process the command. + * + * @return Indicates the command result code. + */ ErrCode OnCommand(); + + /** + * @brief Execute the command. + * + * @return Indicates the output text. + */ std::string ExecCommand(); + + /** + * @brief Get the error message of the command. + * + * @return Indicates the error message. + */ std::string GetCommandErrorMsg() const; + + /** + * @brief Get the error message of the unknown option. + * + * @param unknownOption Indicates the unknown option. + * @return Indicates the error message. + */ std::string GetUnknownOptionMsg(std::string &unknownOption) const; + + /** + * @brief Get the message from the code. + * + * @param code Indicates the code. + * @return Indicates the message. + */ std::string GetMessageFromCode(const int32_t code) const; + /** + * @brief Create the command map. + * + * @return Indicates the result code. + */ virtual ErrCode CreateCommandMap() = 0; + + /** + * @brief Create the message map. + * + * @return Indicates the result code. + */ virtual ErrCode CreateMessageMap() = 0; + + /** + * @brief The initialize function. + * + * @return Indicates the result code. + */ virtual ErrCode init() = 0; protected: - static constexpr int MIN_ARGUMENT_NUMBER = 2; + static constexpr int32_t MIN_ARGUMENT_NUMBER = 2; int argc_; char **argv_; diff --git a/tools/dump/src/notification_shell_command.cpp b/tools/dump/src/notification_shell_command.cpp index 97de8dd95d8b5da05f66b0ac7be1481c1e99cda2..886d6fecbc3179498657e96368c43ad3a3f90097 100644 --- a/tools/dump/src/notification_shell_command.cpp +++ b/tools/dump/src/notification_shell_command.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -49,7 +49,7 @@ static const std::string DUMP_HELP_MSG = #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED " --distributed, -D list all distributed notifications by remote device\n" #endif - " --setRecentCount set the max count of recent notification keeping in memory\n"; + " --setRecentCount set the max count of recent notifications keeping in memory\n"; } // namespace NotificationShellCommand::NotificationShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, "anm_dump") diff --git a/tools/dump/src/shell_command.cpp b/tools/dump/src/shell_command.cpp index 215018965951789df781c2be85d741b7a4fc7182..4f44c803006e85f2133c17d5400614c29617a837 100644 --- a/tools/dump/src/shell_command.cpp +++ b/tools/dump/src/shell_command.cpp @@ -41,7 +41,7 @@ ShellCommand::~ShellCommand() ErrCode ShellCommand::OnCommand() { - int result = OHOS::ERR_OK; + int32_t result = OHOS::ERR_OK; auto respond = commandMap_[cmd_]; if (respond == nullptr) { resultReceiver_.append(GetCommandErrorMsg()); @@ -57,7 +57,7 @@ ErrCode ShellCommand::OnCommand() std::string ShellCommand::ExecCommand() { - int result = CreateCommandMap(); + int32_t result = CreateCommandMap(); if (result != OHOS::ERR_OK) { ANS_LOGE("failed to create command map.\n"); }