diff --git a/bundle.json b/bundle.json index 0bd1b2ce2d3d181edf7df38e843269c9b76afd7f..7b232ca938d929be4b58482470c724897fafa939 100644 --- a/bundle.json +++ b/bundle.json @@ -40,9 +40,13 @@ "subsystem": "notification", "syscap": [ "SystemCapability.Notification.Notification", - "SystemCapability.Notification.ReminderAgent" + "SystemCapability.Notification.ReminderAgent", + "SystemCapability.Notification.NotificationSettings" + ], + "features": [ + "distributed_notification_service_feature_summary", + "distributed_notification_service_feature_enable_fa_model" ], - "features": ["distributed_notification_service_feature_summary"], "adapted_system_type": [ "standard" ], @@ -84,7 +88,8 @@ "resource_management", "config_policy", "screenlock_mgr", - "ace_engine" + "ace_engine", + "openssl" ], "third_party": [ "libuv", @@ -100,7 +105,8 @@ "fwk_group": [ "//base/notification/distributed_notification_service/frameworks/ans:ans_client", "//base/notification/distributed_notification_service/frameworks/js/napi:napi_notification", - "//base/notification/distributed_notification_service/frameworks/js/napi:napi_reminder" + "//base/notification/distributed_notification_service/frameworks/js/napi:napi_reminder", + "//base/notification/distributed_notification_service/interfaces/ndk:ohnotification" ], "service_group": [ "//base/notification/distributed_notification_service/sa_profile:ans_sa_profile", diff --git a/frameworks/ans/BUILD.gn b/frameworks/ans/BUILD.gn index 24bfef29e297e3549216a0d6a0d98ebbcd0adadd..0636bb553c92a78c3f6d697775d3b67a56cb1ad6 100644 --- a/frameworks/ans/BUILD.gn +++ b/frameworks/ans/BUILD.gn @@ -62,6 +62,7 @@ ohos_shared_library("ans_innerkits") { "${core_path}/src/ans_manager_stub.cpp", "${core_path}/src/ans_manager_stub_invalid.cpp", "${core_path}/src/ans_notification.cpp", + "${core_path}/src/ans_subscriber_listener.cpp", "${core_path}/src/ans_subscriber_local_live_view_proxy.cpp", "${core_path}/src/ans_subscriber_local_live_view_stub.cpp", "${core_path}/src/ans_subscriber_proxy.cpp", @@ -116,9 +117,6 @@ ohos_shared_library("ans_innerkits") { "${frameworks_module_ans_path}/src/reminder_request_alarm.cpp", "${frameworks_module_ans_path}/src/reminder_request_calendar.cpp", "${frameworks_module_ans_path}/src/reminder_request_timer.cpp", - "${frameworks_module_ans_path}/src/reminder_store.cpp", - "${frameworks_module_ans_path}/src/reminder_table.cpp", - "${frameworks_module_ans_path}/src/reminder_table_old.cpp", ] public_configs = [ ":ans_innerkits_public_config" ] @@ -137,8 +135,6 @@ ohos_shared_library("ans_innerkits") { "hilog:libhilog", "i18n:intl_util", "ipc:ipc_core", - "os_account:os_account_innerkits", - "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", "time_service:time_client", diff --git a/frameworks/ans/src/notification.cpp b/frameworks/ans/src/notification.cpp index ca7903ae7c2001e782d8a939de15039501821e34..669fe67a8902c2c4232bda2701442c27a4fbcb86 100644 --- a/frameworks/ans/src/notification.cpp +++ b/frameworks/ans/src/notification.cpp @@ -592,5 +592,15 @@ uint64_t Notification::GetArchiveTimer() const { return archiveTimerId_; } + +void Notification::SetAutoDeletedTimer(uint64_t autoDeletedTimerId) +{ + autoDeletedTimerId_ = autoDeletedTimerId; +} + +uint64_t Notification::GetAutoDeletedTimer() const +{ + return autoDeletedTimerId_; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/src/notification_bundle_option.cpp b/frameworks/ans/src/notification_bundle_option.cpp index bead64f85d34b81dbb1132b780dcad1f9f906e29..fee77488dd6f77857181056d47e39df6fe41d298 100644 --- a/frameworks/ans/src/notification_bundle_option.cpp +++ b/frameworks/ans/src/notification_bundle_option.cpp @@ -59,12 +59,23 @@ int32_t NotificationBundleOption::GetInstanceKey() const return instanceKey_; } +void NotificationBundleOption::SetAppIndex(const int32_t appIndex) +{ + appIndex_ = appIndex; +} + +int32_t NotificationBundleOption::GetAppIndex() const +{ + return appIndex_; +} + std::string NotificationBundleOption::Dump() { return "NotificationBundleOption{ " "bundleName = " + bundleName_ + ", uid = " + std::to_string(uid_) + ", instanceKey = " + std::to_string(instanceKey_) + + ", appIndex = " + std::to_string(appIndex_) + " }"; } @@ -118,6 +129,7 @@ bool NotificationBundleOption::ToJson(nlohmann::json &jsonObject) const jsonObject["uid"] = uid_; jsonObject["bundleName"] = bundleName_; jsonObject["instanceKey"] = instanceKey_; + jsonObject["appIndex"] = appIndex_; return true; } @@ -148,6 +160,9 @@ NotificationBundleOption *NotificationBundleOption::FromJson(const nlohmann::jso pBundle->instanceKey_ = jsonObject.at("instanceKey").get(); } + if (jsonObject.find("appIndex") != jsonEnd && jsonObject.at("appIndex").is_number_integer()) { + pBundle->appIndex_ = jsonObject.at("appIndex").get(); + } return pBundle; } diff --git a/frameworks/ans/src/notification_do_not_disturb_profile.cpp b/frameworks/ans/src/notification_do_not_disturb_profile.cpp index 2da7e16d6b4dd06bcbed13be07a9626dbb35e244..f13a47d575b614e63f974c99dd53e74102601be6 100644 --- a/frameworks/ans/src/notification_do_not_disturb_profile.cpp +++ b/frameworks/ans/src/notification_do_not_disturb_profile.cpp @@ -119,6 +119,13 @@ bool NotificationDoNotDisturbProfile::ReadFromParcel(Parcel &parcel) } std::string NotificationDoNotDisturbProfile::ToJson() +{ + nlohmann::json jsonObject; + GetProfileJson(jsonObject); + return jsonObject.dump(); +} + +void NotificationDoNotDisturbProfile::GetProfileJson(nlohmann::json &jsonObject) const { nlohmann::json jsonNodes = nlohmann::json::array(); for (size_t index = 0; index < trustList_.size(); index++) { @@ -127,17 +134,19 @@ std::string NotificationDoNotDisturbProfile::ToJson() jsonNodes.emplace_back(jsonNode); } } - nlohmann::json jsonObject { - {DO_NOT_DISTURB_PROFILE_ID, id_}, - {DO_NOT_DISTURB_PROFILE_NAME, name_}, - {DO_NOT_DISTURB_PROFILE_TRUSTLIST, jsonNodes} - }; - return jsonObject.dump(); + + jsonObject[DO_NOT_DISTURB_PROFILE_ID] = id_; + jsonObject[DO_NOT_DISTURB_PROFILE_NAME] = name_; + jsonObject[DO_NOT_DISTURB_PROFILE_TRUSTLIST] = jsonNodes; } void NotificationDoNotDisturbProfile::FromJson(const std::string &jsonObj) { nlohmann::json jsonObject = nlohmann::json::parse(jsonObj, nullptr, false); + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } if (jsonObject.is_discarded()) { ANS_LOGE("Failed to parse json string."); return; @@ -155,9 +164,10 @@ void NotificationDoNotDisturbProfile::FromJson(const std::string &jsonObj) if (bundleOption == nullptr) { continue; } - trustList_.emplace_back(*bundleOption); + trustList_.push_back(*bundleOption); + delete bundleOption; } } } } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 9a14e6989669ea4427130a4e216404fff8373f31..ccfb6618b5a07031263e1eeb02e6e0eb9df6309c 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -16,6 +16,7 @@ #include "notification_helper.h" #include "ans_notification.h" #include "singleton.h" +#include namespace OHOS { namespace Notification { @@ -82,6 +83,11 @@ ErrCode NotificationHelper::PublishNotification(const std::string &label, const return DelayedSingleton::GetInstance()->PublishNotification(label, request); } +ErrCode NotificationHelper::PublishNotificationForIndirectProxy(const NotificationRequest &request) +{ + return DelayedSingleton::GetInstance()->PublishNotificationForIndirectProxy(request); +} + ErrCode NotificationHelper::CancelNotification(int32_t notificationId) { return DelayedSingleton::GetInstance()->CancelNotification(notificationId); @@ -170,6 +176,11 @@ ErrCode NotificationHelper::CanPopEnableNotificationDialog(sptr::GetInstance()->RemoveEnableNotificationDialog(); +} + ErrCode NotificationHelper::RequestEnableNotification(std::string &deviceId, sptr &hostClient, sptr &callerToken) @@ -193,11 +204,21 @@ ErrCode NotificationHelper::SubscribeNotification(const NotificationSubscriber & return DelayedSingleton::GetInstance()->SubscribeNotification(subscriber); } +ErrCode NotificationHelper::SubscribeNotification(const std::shared_ptr &subscriber) +{ + return DelayedSingleton::GetInstance()->SubscribeNotification(subscriber, nullptr); +} + ErrCode NotificationHelper::SubscribeNotificationSelf(const NotificationSubscriber &subscriber) { return DelayedSingleton::GetInstance()->SubscribeNotificationSelf(subscriber); } +ErrCode NotificationHelper::SubscribeNotificationSelf(const std::shared_ptr &subscriber) +{ + return DelayedSingleton::GetInstance()->SubscribeNotificationSelf(subscriber); +} + ErrCode NotificationHelper::SubscribeLocalLiveViewNotification(const NotificationLocalLiveViewSubscriber &subscriber, const bool isNative) { @@ -210,17 +231,34 @@ ErrCode NotificationHelper::SubscribeNotification( return DelayedSingleton::GetInstance()->SubscribeNotification(subscriber, subscribeInfo); } +ErrCode NotificationHelper::SubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo) +{ + return DelayedSingleton::GetInstance()->SubscribeNotification(subscriber, subscribeInfo); +} + ErrCode NotificationHelper::UnSubscribeNotification(NotificationSubscriber &subscriber) { return DelayedSingleton::GetInstance()->UnSubscribeNotification(subscriber); } +ErrCode NotificationHelper::UnSubscribeNotification(const std::shared_ptr &subscriber) +{ + return DelayedSingleton::GetInstance()->UnSubscribeNotification(subscriber); +} + ErrCode NotificationHelper::UnSubscribeNotification( NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo) { return DelayedSingleton::GetInstance()->UnSubscribeNotification(subscriber, subscribeInfo); } +ErrCode NotificationHelper::UnSubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo) +{ + return DelayedSingleton::GetInstance()->UnSubscribeNotification(subscriber, subscribeInfo); +} + ErrCode NotificationHelper::TriggerLocalLiveView(const NotificationBundleOption &bundleOption, const int32_t notificationId, const NotificationButtonOption &buttonOption) { @@ -370,6 +408,11 @@ ErrCode NotificationHelper::DoesSupportDoNotDisturbMode(bool &doesSupport) return DelayedSingleton::GetInstance()->DoesSupportDoNotDisturbMode(doesSupport); } +ErrCode NotificationHelper::IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) +{ + return DelayedSingleton::GetInstance()->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); +} + ErrCode NotificationHelper::IsDistributedEnabled(bool &enabled) { return DelayedSingleton::GetInstance()->IsDistributedEnabled(enabled); @@ -545,5 +588,14 @@ ErrCode NotificationHelper::RegisterSwingCallback(const std::function &profile) +{ + return DelayedSingleton::GetInstance()->GetDoNotDisturbProfile(id, profile); +} + +ErrCode NotificationHelper::UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) +{ + return DelayedSingleton::GetInstance()->UpdateNotificationTimerByUid(uid, isPaused); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/src/notification_local_live_view_button.cpp b/frameworks/ans/src/notification_local_live_view_button.cpp index 81d163d5172dc3e92962acafd51d732f81b50221..526324138df076797c457527ced880a424ce1ff0 100644 --- a/frameworks/ans/src/notification_local_live_view_button.cpp +++ b/frameworks/ans/src/notification_local_live_view_button.cpp @@ -16,6 +16,7 @@ #include "notification_local_live_view_button.h" #include +#include #include // for basic_string, operator+, basic_string<>... #include // for shared_ptr, shared_ptr<>::element_type #include @@ -172,6 +173,7 @@ NotificationLocalLiveViewButton *NotificationLocalLiveViewButton::FromJson(const auto pIcon = AnsImageUtil::UnPackImage(iconObj.get()); if (pIcon == nullptr) { ANS_LOGE("Failed to parse button icon"); + delete button; return nullptr; } button->buttonIcons_.emplace_back(pIcon); @@ -257,9 +259,19 @@ bool NotificationLocalLiveViewButton::ReadFromParcel(Parcel &parcel) ANS_LOGE("Failed to read button names"); return false; } + if (iconsResource.size() < BUTTON_RESOURCE_SIZE) { + ANS_LOGE("Invalid input for button icons resource"); + return false; + } auto resource = std::make_shared(); resource->bundleName = iconsResource[RESOURCE_BUNDLENAME_INDEX]; resource->moduleName = iconsResource[RESOURCE_MODULENAME_INDEX]; + std::stringstream sin(iconsResource[RESOURCE_ID_INDEX]); + int32_t checknum; + if (!(sin >> checknum)) { + ANS_LOGE("Invalid input for button icons resource"); + return false; + } resource->id = std::stoi(iconsResource[RESOURCE_ID_INDEX]); buttonIconsResource_.emplace_back(resource); } diff --git a/frameworks/ans/src/notification_long_text_content.cpp b/frameworks/ans/src/notification_long_text_content.cpp index 72f6931101af5f7353f25d07e76844af0f53e87b..8efbac17eef4bd8c29f5f358fa590f1a6b4981b7 100644 --- a/frameworks/ans/src/notification_long_text_content.cpp +++ b/frameworks/ans/src/notification_long_text_content.cpp @@ -25,7 +25,7 @@ namespace OHOS { namespace Notification { -const std::size_t NotificationLongTextContent::MAX_LONGTEXT_LENGTH {1024}; +const std::size_t NotificationLongTextContent::MAX_LONGTEXT_LENGTH {3072}; NotificationLongTextContent::NotificationLongTextContent(const std::string &longText) { diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index 9dbb6e96b6e9d895fe9c0cc1671e27faef0cd95b..928f33d3b619c13e3f58614411347c5d591ebe21 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -312,6 +312,11 @@ void NotificationRequest::SetBigIcon(const std::shared_ptr &big bigIcon_ = bigIcon; } +void NotificationRequest::ResetBigIcon() const +{ + bigIcon_ = nullptr; +} + const std::shared_ptr NotificationRequest::GetBigIcon() const { return bigIcon_; @@ -867,7 +872,12 @@ NotificationRequest *NotificationRequest::FromJson(const nlohmann::json &jsonObj if (jsonObject.find("wantAgent") != jsonEnd && jsonObject.at("wantAgent").is_string()) { auto wantAgentValue = jsonObject.at("wantAgent").get(); - pRequest->wantAgent_ = AbilityRuntime::WantAgent::WantAgentHelper::FromString(wantAgentValue); + int32_t targetUid = -1; + if (pRequest->GetOwnerUid() != DEFAULT_UID) { + targetUid = pRequest->GetOwnerUid(); + } + ANS_LOGI("wantAgent Fromjson, uid = %{public}d ", targetUid); + pRequest->wantAgent_ = AbilityRuntime::WantAgent::WantAgentHelper::FromString(wantAgentValue, targetUid); } if (!ConvertJsonToNotificationContent(pRequest, jsonObject)) { @@ -1502,11 +1512,50 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) return false; } - slotType_ = static_cast(parcel.ReadInt32()); - groupAlertType_ = static_cast(parcel.ReadInt32()); - visiblenessType_ = static_cast(parcel.ReadInt32()); - badgeStyle_ = static_cast(parcel.ReadInt32()); - notificationContentType_ = static_cast(parcel.ReadInt32()); + int32_t slotTypeValue = parcel.ReadInt32(); + if (slotTypeValue < 0 || + slotTypeValue >= static_cast(NotificationConstant::SlotType::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid slot type value :%{public}d. It should be in [0 , %{public}d).", + slotTypeValue, static_cast(NotificationConstant::SlotType::ILLEGAL_TYPE)); + return false; + } + slotType_ = static_cast(slotTypeValue); + int32_t groupAlertTypeValue = parcel.ReadInt32(); + if (groupAlertTypeValue < 0 || + groupAlertTypeValue >= static_cast(NotificationRequest::GroupAlertType::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid groupAlert type value :%{public}d. It should be in [0 , %{public}d).", + groupAlertTypeValue, static_cast(NotificationRequest::GroupAlertType::ILLEGAL_TYPE)); + return false; + } + groupAlertType_ = static_cast(groupAlertTypeValue); + int32_t visiblenessTypeValue = parcel.ReadInt32(); + if (visiblenessTypeValue < 0 || + visiblenessTypeValue >= static_cast(NotificationConstant::VisiblenessType::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid visibleness type value :%{public}d. It should be in [0 , %{public}d).", + visiblenessTypeValue, static_cast(NotificationConstant::VisiblenessType::ILLEGAL_TYPE)); + return false; + } + visiblenessType_ = static_cast(visiblenessTypeValue); + int32_t badgeStyleValue = parcel.ReadInt32(); + if (badgeStyleValue < 0) { + ANS_LOGE("Invalid badge style value :%{public}d. It should be greater than 0.", badgeStyleValue); + return false; + } + if (badgeStyleValue >= static_cast(NotificationRequest::BadgeStyle::ILLEGAL_TYPE)) { + badgeStyleValue = static_cast(NotificationRequest::BadgeStyle::NONE); + ANS_LOGE("The badge style value is too large, set it to the default enumeration value: %{public}d.", + static_cast(NotificationRequest::BadgeStyle::NONE)); + } + badgeStyle_ = static_cast(badgeStyleValue); + int32_t notificationContentTypeValue = parcel.ReadInt32(); + if (notificationContentTypeValue <= static_cast(NotificationContent::Type::NONE) || + notificationContentTypeValue >= static_cast(NotificationContent::Type::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid notification content type value :%{public}d. It should be in (%{public}d , %{public}d)", + notificationContentTypeValue, static_cast(NotificationContent::Type::NONE), + static_cast(NotificationContent::Type::ILLEGAL_TYPE)); + return false; + } + notificationContentType_ = static_cast(notificationContentTypeValue); showDeliveryTime_ = parcel.ReadBool(); tapDismissed_ = parcel.ReadBool(); @@ -1568,10 +1617,6 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) valid = parcel.ReadBool(); if (valid) { littleIcon_ = std::shared_ptr(parcel.ReadParcelable()); - if (!littleIcon_) { - ANS_LOGE("Failed to read littleIcon"); - return false; - } } valid = parcel.ReadBool(); @@ -1918,7 +1963,6 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const extraInfoStr = wWrapper.ToString(); } jsonObject["extraInfo"] = extraInfoStr; - jsonObject["smallIcon"] = AnsImageUtil::PackImage(littleIcon_); jsonObject["largeIcon"] = AnsImageUtil::PackImage(bigIcon_); jsonObject["overlayIcon"] = overlayIcon_ ? AnsImageUtil::PackImage(overlayIcon_) : ""; @@ -2166,7 +2210,7 @@ void NotificationRequest::ConvertJsonToPixelMap(NotificationRequest *target, con const auto &jsonEnd = jsonObject.cend(); if (jsonObject.find("smallIcon") != jsonEnd && jsonObject.at("smallIcon").is_string()) { - auto littleIconStr = jsonObject.at("smallIcon").get(); + auto littleIconStr = jsonObject.at("smallIcon").get(); target->littleIcon_ = AnsImageUtil::UnPackImage(littleIconStr); } @@ -2253,6 +2297,7 @@ bool NotificationRequest::ConvertJsonToNotificationDistributedOptions( } target->distributedOptions_ = *pOpt; + delete pOpt; } } @@ -2503,6 +2548,14 @@ std::string NotificationRequest::GetKey() return stream.str(); } +std::string NotificationRequest::GetSecureKey() +{ + std::stringstream stream; + const char *keySpliter = "_"; + stream << REQUEST_STORAGE_SECURE_KEY_PREFIX << keySpliter << GetBaseKey(""); + return stream.str(); +} + bool NotificationRequest::CheckImageOverSizeForPixelMap( const std::shared_ptr &pixelMap, uint32_t maxSize) { @@ -2645,10 +2698,10 @@ std::string NotificationRequest::GenerateUniqueKey() std::stringstream stream; if (IsAgentNotification()) { - stream << ownerUserId_ << keySpliter << ownerBundleName_ << keySpliter << + stream << ownerUid_ << keySpliter << ownerBundleName_ << keySpliter << ownerUserId_ << keySpliter << typeFlag << keySpliter << appMessageId_; } else { - stream << creatorUserId_ << keySpliter << creatorBundleName_ << keySpliter << + stream << creatorUid_ << keySpliter << creatorBundleName_ << keySpliter << creatorUserId_ << keySpliter << typeFlag << keySpliter << appMessageId_; } return stream.str(); @@ -2693,5 +2746,10 @@ bool NotificationRequest::IsUpdateByOwnerAllowed() const { return isUpdateByOwnerAllowed_; } + +const std::string NotificationRequest::GetLittleIconType() const +{ + return littleIconType_; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/src/notification_slot.cpp b/frameworks/ans/src/notification_slot.cpp index 1ecac11bec3ed75c951773c9e9e7d081c862264e..ecc092e9d721d8f450e63fe2dcd96d2a23ecbad0 100644 --- a/frameworks/ans/src/notification_slot.cpp +++ b/frameworks/ans/src/notification_slot.cpp @@ -19,7 +19,16 @@ namespace OHOS { namespace Notification { -std::map NotificationSlot::convertStrToSlotType_; +std::map NotificationSlot::convertStrToSlotType_ = { + {SOCIAL_COMMUNICATION, NotificationConstant::SlotType::SOCIAL_COMMUNICATION}, + {SERVICE_REMINDER, NotificationConstant::SlotType::SERVICE_REMINDER}, + {CONTENT_INFORMATION, NotificationConstant::SlotType::CONTENT_INFORMATION}, + {OTHER, NotificationConstant::SlotType::OTHER}, + {LIVE_VIEW, NotificationConstant::SlotType::LIVE_VIEW}, + {CUSTOM_SERVICE, NotificationConstant::SlotType::CUSTOMER_SERVICE}, + {EMERGENCY_INFORMATION, NotificationConstant::SlotType::EMERGENCY_INFORMATION} +}; + const int32_t MAX_TEXT_LENGTH = 1000; const uint32_t SOUND_OPNE = 1 << 0; const uint32_t LOCKSCREEN_OPNE = 1 << 1; @@ -488,15 +497,6 @@ std::string NotificationSlot::TruncateString(const std::string &in) bool NotificationSlot::GetSlotTypeByString( const std::string &strSlotType, NotificationConstant::SlotType &slotType) { - if (convertStrToSlotType_.size() <= 0) { - convertStrToSlotType_[SOCIAL_COMMUNICATION] = NotificationConstant::SlotType::SOCIAL_COMMUNICATION; - convertStrToSlotType_[SERVICE_REMINDER] = NotificationConstant::SlotType::SERVICE_REMINDER; - convertStrToSlotType_[CONTENT_INFORMATION] = NotificationConstant::SlotType::CONTENT_INFORMATION; - convertStrToSlotType_[OTHER] = NotificationConstant::SlotType::OTHER; - convertStrToSlotType_[LIVE_VIEW] = NotificationConstant::SlotType::LIVE_VIEW; - convertStrToSlotType_[CUSTOM_SERVICE] = NotificationConstant::SlotType::CUSTOMER_SERVICE; - convertStrToSlotType_[EMERGENCY_INFORMATION] = NotificationConstant::SlotType::EMERGENCY_INFORMATION; - } auto iterSlotType = convertStrToSlotType_.find(strSlotType); if (iterSlotType != convertStrToSlotType_.end()) { slotType = iterSlotType->second; diff --git a/frameworks/ans/src/notification_sorting.cpp b/frameworks/ans/src/notification_sorting.cpp index 78699b112ca9c87693d2e2f91cccbc54013cd354..6a392de8bc5760b72b98f8da0eb860e66bbf8880 100644 --- a/frameworks/ans/src/notification_sorting.cpp +++ b/frameworks/ans/src/notification_sorting.cpp @@ -135,6 +135,10 @@ bool NotificationSorting::ReadFromParcel(Parcel &parcel) // read slot_ slot_ = parcel.ReadStrongParcelable(); + if (!slot_) { + ANS_LOGE("read slot failed."); + return false; + } return true; } @@ -143,6 +147,7 @@ NotificationSorting *NotificationSorting::Unmarshalling(Parcel &parcel) { NotificationSorting *sorting = new (std::nothrow) NotificationSorting(); if (sorting && !sorting->ReadFromParcel(parcel)) { + ANS_LOGE("NotificationSorting Unmarshalling failed."); delete sorting; sorting = nullptr; } diff --git a/frameworks/ans/src/notification_sorting_map.cpp b/frameworks/ans/src/notification_sorting_map.cpp index 919c88a8cfbc1d512383450de848f81ef650a4fd..09b41fb3ba2586c94061c4968fcb0a0ae73d6312 100644 --- a/frameworks/ans/src/notification_sorting_map.cpp +++ b/frameworks/ans/src/notification_sorting_map.cpp @@ -81,7 +81,6 @@ bool NotificationSortingMap::Marshalling(Parcel &parcel) const break; } } - return ret; } diff --git a/frameworks/ans/src/notification_subscriber.cpp b/frameworks/ans/src/notification_subscriber.cpp index 9b97dfb8701083594d2f1cdfdc81d8c7218f8022..5e56611880afa9baf125937eeb7849abf0570981 100644 --- a/frameworks/ans/src/notification_subscriber.cpp +++ b/frameworks/ans/src/notification_subscriber.cpp @@ -29,7 +29,11 @@ NotificationSubscriber::NotificationSubscriber() }; NotificationSubscriber::~NotificationSubscriber() -{} +{ + if (impl_ != nullptr) { + impl_->OnSubscriberDestory(); + } +} void NotificationSubscriber::SetDeviceType(const std::string &deviceType) { @@ -56,6 +60,9 @@ bool NotificationSubscriber::ProcessSyncDecision( } auto flagIter = flagsMap->find(deviceType); if (flagIter != flagsMap->end() && flagIter->second != nullptr) { + ANS_LOGI("SetFlags-before filte, notificationKey = %{public}s flagIter \ + flags = %{public}d, deviceType:%{public}s", + request->GetKey().c_str(), flagIter->second->GetReminderFlags(), deviceType.c_str()); std::shared_ptr tempFlags = request->GetFlags(); tempFlags->SetSoundEnabled(DowngradeReminder(tempFlags->IsSoundEnabled(), flagIter->second->IsSoundEnabled())); tempFlags->SetVibrationEnabled( @@ -67,6 +74,8 @@ bool NotificationSubscriber::ProcessSyncDecision( tempFlags->SetLightScreenEnabled( tempFlags->IsLightScreenEnabled() && flagIter->second->IsLightScreenEnabled()); request->SetFlags(tempFlags); + ANS_LOGI("SetFlags-after filte, notificationKey = %{public}s flags = %{public}d", + request->GetKey().c_str(), tempFlags->GetReminderFlags()); return true; } if (deviceType.size() <= 0 || deviceType.compare(NotificationConstant::CURRENT_DEVICE_TYPE) == 0) { @@ -100,8 +109,16 @@ NotificationSubscriber::SubscriberImpl::SubscriberImpl(NotificationSubscriber &s recipient_ = new (std::nothrow) DeathRecipient(*this); }; +void NotificationSubscriber::SubscriberImpl::OnSubscriberDestory() +{ + isSubscriberDestory_.store(true); +} + void NotificationSubscriber::SubscriberImpl::OnConnected() { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); sptr proxy = GetAnsManagerProxy(); if (proxy != nullptr) { @@ -113,6 +130,9 @@ void NotificationSubscriber::SubscriberImpl::OnConnected() void NotificationSubscriber::SubscriberImpl::OnDisconnected() { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); sptr proxy = GetAnsManagerProxy(); if (proxy != nullptr) { @@ -125,6 +145,9 @@ void NotificationSubscriber::SubscriberImpl::OnDisconnected() void NotificationSubscriber::SubscriberImpl::OnConsumed( const sptr ¬ification, const sptr ¬ificationMap) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); std::shared_ptr sharedNotification = std::make_shared(*notification); #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED @@ -139,6 +162,9 @@ void NotificationSubscriber::SubscriberImpl::OnConsumed( void NotificationSubscriber::SubscriberImpl::OnConsumedList(const std::vector> ¬ifications, const sptr ¬ificationMap) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); for (auto notification : notifications) { OnConsumed(notification, notificationMap); @@ -148,6 +174,9 @@ void NotificationSubscriber::SubscriberImpl::OnConsumedList(const std::vector ¬ification, const sptr ¬ificationMap, int32_t deleteReason) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); if (notificationMap == nullptr) { subscriber_.OnCanceled(std::make_shared(*notification), @@ -161,6 +190,9 @@ void NotificationSubscriber::SubscriberImpl::OnCanceled( void NotificationSubscriber::SubscriberImpl::OnBatchCanceled(const std::vector> ¬ifications, const sptr ¬ificationMap, int32_t deleteReason) { + if (isSubscriberDestory_.load()) { + return; + } std::vector> notificationList; for (auto notification : notifications) { notificationList.emplace_back(std::make_shared(*notification)); @@ -174,10 +206,12 @@ void NotificationSubscriber::SubscriberImpl::OnBatchCanceled(const std::vector> ¬ifications, const sptr ¬ificationMap, int32_t deleteReason) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); if (subscriber_.HasOnBatchCancelCallback()) { OnBatchCanceled(notifications, notificationMap, deleteReason); @@ -190,23 +224,35 @@ void NotificationSubscriber::SubscriberImpl::OnCanceledList(const std::vector ¬ificationMap) { + if (isSubscriberDestory_.load()) { + return; + } subscriber_.OnUpdate(std::make_shared(*notificationMap)); } void NotificationSubscriber::SubscriberImpl::OnDoNotDisturbDateChange(const sptr &date) { + if (isSubscriberDestory_.load()) { + return; + } subscriber_.OnDoNotDisturbDateChange(std::make_shared(*date)); } void NotificationSubscriber::SubscriberImpl::OnEnabledNotificationChanged( const sptr &callbackData) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); subscriber_.OnEnabledNotificationChanged(std::make_shared(*callbackData)); } void NotificationSubscriber::SubscriberImpl::OnBadgeChanged(const sptr &badgeData) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); subscriber_.OnBadgeChanged(std::make_shared(*badgeData)); } @@ -214,6 +260,9 @@ void NotificationSubscriber::SubscriberImpl::OnBadgeChanged(const sptr &callbackData) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); subscriber_.OnBadgeEnabledChanged(callbackData); } diff --git a/frameworks/ans/src/reminder_request.cpp b/frameworks/ans/src/reminder_request.cpp index 43fed25103d8f302661ae5fc4775f28b9019e0ee..f338ac850790a76c3795e22efcdbd2b37f2fec81 100644 --- a/frameworks/ans/src/reminder_request.cpp +++ b/frameworks/ans/src/reminder_request.cpp @@ -15,8 +15,6 @@ #include "reminder_request.h" -#include "reminder_table.h" -#include "reminder_table_old.h" #include "ans_const_define.h" #include "ans_log_wrapper.h" #include "bundle_mgr_interface.h" @@ -25,8 +23,6 @@ #include "ipc_skeleton.h" #include "iservice_registry.h" #include "locale_config.h" -#include "os_account_manager.h" -#include "reminder_store.h" #include "system_ability_definition.h" #include "want_agent_helper.h" #include "nlohmann/json.hpp" @@ -47,6 +43,8 @@ const int32_t BUTTON_PKG_INDEX = 2; const int32_t BUTTON_ABILITY_INDEX = 3; const int32_t WANT_AGENT_URI_INDEX = 2; const int32_t INDENT = -1; + +const char* const PARAM_EXTRA_KEY = "NotificationRequest_extraInfo"; } int32_t ReminderRequest::GLOBAL_ID = 0; @@ -480,118 +478,6 @@ 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; - ReminderStore::GetInt32Val(resultSet, columnName, value); - return static_cast(value); - } - case (DbRecoveryType::LONG): { - int64_t value; - ReminderStore::GetInt64Val(resultSet, columnName, value); - return value; - } - default: { - ANSR_LOGD("ColumnType not support."); - break; - } - } - ANSR_LOGE("Recover data error"); - return 0; -} - -void ReminderRequest::RecoverBasicFromDb(const std::shared_ptr& resultSet) -{ - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::REMINDER_ID, reminderId_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::PACKAGE_NAME, bundleName_); - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::USER_ID, userId_); - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::UID, uid_); - - std::string isSysApp; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::SYSTEM_APP, isSysApp); - isSystemApp_ = isSysApp == "true" ? true : false; - - int32_t reminderType; - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::REMINDER_TYPE, reminderType); - reminderType_ = ReminderType(reminderType); - - ReminderStore::GetUInt64Val(resultSet, ReminderBaseTable::REMINDER_TIME, reminderTimeInMilli_); - ReminderStore::GetUInt64Val(resultSet, ReminderBaseTable::TRIGGER_TIME, triggerTimeInMilli_); - - uint64_t timeIntervalInSecond = 0; - ReminderStore::GetUInt64Val(resultSet, ReminderBaseTable::TIME_INTERVAL, timeIntervalInSecond); - SetTimeInterval(timeIntervalInSecond); - - ReminderStore::GetUInt8Val(resultSet, ReminderBaseTable::SNOOZE_TIMES, snoozeTimes_); - ReminderStore::GetUInt8Val(resultSet, ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, snoozeTimesDynamic_); - - uint64_t ringDurationInSecond; - ReminderStore::GetUInt64Val(resultSet, ReminderBaseTable::RING_DURATION, ringDurationInSecond); - SetRingDuration(ringDurationInSecond); - - std::string isExpired; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::IS_EXPIRED, isExpired); - isExpired_ = isExpired == "true" ? true : false; - - ReminderStore::GetUInt8Val(resultSet, ReminderBaseTable::STATE, state_); - - // action buttons - RecoverActionButton(resultSet); - - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::CUSTOM_BUTTON_URI, customButtonUri_); - - int32_t slotType; - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::SLOT_ID, slotType); - slotType_ = NotificationConstant::SlotType(slotType); - - int32_t snoozeSlotType; - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::SNOOZE_SLOT_ID, snoozeSlotType); - snoozeSlotType_ = NotificationConstant::SlotType(snoozeSlotType); - - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::NOTIFICATION_ID, notificationId_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::TITLE, title_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::CONTENT, content_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::SNOOZE_CONTENT, snoozeContent_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::EXPIRED_CONTENT, expiredContent_); - - InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent -} - -void ReminderRequest::RecoverFromDbBase(const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - RecoverBasicFromDb(resultSet); - - std::string wantAgent; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::WANT_AGENT, wantAgent); - RecoverWantAgent(wantAgent, 0); - - std::string maxScreenWantAgent; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::MAX_SCREEN_WANT_AGENT, maxScreenWantAgent); - RecoverWantAgent(maxScreenWantAgent, 1); - - std::string tapDismissed; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::TAP_DISMISSED, tapDismissed); - tapDismissed_ = tapDismissed == "true" ? true : false; - - ReminderStore::GetInt64Val(resultSet, ReminderBaseTable::AUTO_DELETED_TIME, autoDeletedTime_); - - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::GROUP_ID, groupId_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::CUSTOM_RING_URI, customRingUri_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::CREATOR_BUNDLE_NAME, creatorBundleName_); - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::CREATOR_UID, creatorUid_); -} - void ReminderRequest::RecoverActionButtonJsonMode(const std::string &jsonString) { if (!nlohmann::json::accept(jsonString)) { @@ -630,15 +516,9 @@ void ReminderRequest::RecoverActionButtonJsonMode(const std::string &jsonString) resource, buttonWantAgent, buttonDataShareUpdate); } -void ReminderRequest::RecoverActionButton(const std::shared_ptr &resultSet) +void ReminderRequest::DeserializeButtonInfo(const std::string& buttonInfoStr) { - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - std::string actionButtonInfo; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::ACTION_BUTTON_INFO, actionButtonInfo); - std::vector multiButton = StringSplit(actionButtonInfo, SEP_BUTTON_MULTI); + std::vector multiButton = StringSplit(buttonInfoStr, SEP_BUTTON_MULTI); for (auto button : multiButton) { std::vector singleButton = StringSplit(button, SEP_BUTTON_SINGLE); if (singleButton.size() <= SINGLE_BUTTON_INVALID) { @@ -733,7 +613,7 @@ void ReminderRequest::RecoverWantAgentByJson(const std::string& wantAgentInfo, c } } -void ReminderRequest::RecoverWantAgent(const std::string &wantAgentInfo, const uint8_t &type) +void ReminderRequest::DeserializeWantAgent(const std::string &wantAgentInfo, const uint8_t type) { if (nlohmann::json::accept(wantAgentInfo)) { RecoverWantAgentByJson(wantAgentInfo, type); @@ -1004,6 +884,21 @@ std::string ReminderRequest::GetBundleName() const return bundleName_; } +void ReminderRequest::SetReminderType(const ReminderType type) +{ + reminderType_ = type; +} + +void ReminderRequest::SetState(const uint8_t state) +{ + state_ = state; +} + +void ReminderRequest::SetRepeatDaysOfWeek(const uint8_t repeatDaysOfWeek) +{ + repeatDaysOfWeek_ = repeatDaysOfWeek; +} + void ReminderRequest::SetSystemApp(bool isSystem) { isSystemApp_ = isSystem; @@ -1054,6 +949,16 @@ std::string ReminderRequest::GetCustomRingUri() const return customRingUri_; } +sptr ReminderRequest::GetNotificationBundleOption() const +{ + return notificationOption_; +} + +void ReminderRequest::SetNotificationBundleOption(const sptr& option) +{ + notificationOption_ = option; +} + std::shared_ptr ReminderRequest::GetWantAgentInfo() const { return wantAgentInfo_; @@ -1079,11 +984,21 @@ bool ReminderRequest::SetNextTriggerTime() return false; } +void ReminderRequest::SetWantAgentStr(const std::string& wantStr) +{ + wantAgentStr_ = wantStr; +} + std::string ReminderRequest::GetWantAgentStr() { return wantAgentStr_; } +void ReminderRequest::SetMaxWantAgentStr(const std::string& maxWantStr) +{ + maxWantAgentStr_ = maxWantStr; +} + std::string ReminderRequest::GetMaxWantAgentStr() { return maxWantAgentStr_; @@ -1110,6 +1025,7 @@ void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std ANSR_LOGI("UpdateNotification want_agent"); AppExecFwk::ElementName wantAgent("", wantAgentInfo_->pkgName, wantAgentInfo_->abilityName); SetWantAgent(wantAgent); + SetExtraInfo(wantAgentInfo_->parameters); break; } case UpdateNotificationType::MAX_SCREEN_WANT_AGENT: { @@ -1378,7 +1294,6 @@ bool ReminderRequest::InitNotificationRequest() return false; } displayContent_ = content_; - AddActionButtons(true); return true; } @@ -1411,7 +1326,7 @@ std::string ReminderRequest::GetDateTimeInfo(const time_t &timeInSecond) const return GetTimeInfoInner(timeInSecond, TimeFormat::YMDHMS, true); } -std::string ReminderRequest::GetButtonInfo() const +std::string ReminderRequest::SerializeButtonInfo() const { std::string info = ""; bool isFirst = true; @@ -1668,6 +1583,15 @@ void ReminderRequest::SetWantAgent(AppExecFwk::ElementName &element) notificationRequest_->SetWantAgent(wantAgent); } +void ReminderRequest::SetExtraInfo(const AAFwk::WantParams& params) +{ + if (params.HasParam(PARAM_EXTRA_KEY)) { + std::shared_ptr extras = std::make_shared( + params.GetWantParams(PARAM_EXTRA_KEY)); + notificationRequest_->SetAdditionalData(extras); + } +} + void ReminderRequest::SetState(bool deSet, const uint8_t newState, std::string function) { uint8_t oldState = state_; @@ -1762,13 +1686,9 @@ void ReminderRequest::UpdateNotificationBundleInfo() ANSR_LOGD("ownerBundleName=%{public}s, bundleName_=%{public}s", ownerBundleName.c_str(), bundleName_.c_str()); notificationRequest_->SetOwnerBundleName(bundleName_); + notificationRequest_->SetOwnerUid(uid_); 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_); } @@ -1851,76 +1771,17 @@ int32_t ReminderRequest::GetCTime(const TimeTransferType &type, int32_t actualTi } } -int32_t ReminderRequest::GetUid(const int32_t &userId, const std::string &bundleName) -{ - 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); - if (remoteObject == nullptr) { - ANSR_LOGE("Fail to get bundle manager proxy"); - return -1; - } - sptr bundleMgr = iface_cast(remoteObject); - if (bundleMgr == nullptr) { - ANSR_LOGE("Bundle mgr proxy is nullptr"); - return -1; - } - int32_t uid = bundleMgr->GetUidByBundleName(bundleName, userId); - ANSR_LOGD("uid=%{public}d", uid); - return uid; -} - -int32_t ReminderRequest::GetAppIndex(const int32_t uid) -{ - const int32_t defaultAppIndex = 0; // failed return main apps - sptr systemAbilityManager - = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemAbilityManager == nullptr) { - ANSR_LOGE("Failed to get app index due to get systemAbilityManager is null."); - return defaultAppIndex; - } - sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (remoteObject == nullptr) { - ANSR_LOGE("Fail to get bundle manager proxy"); - return defaultAppIndex; - } - sptr bundleMgr = iface_cast(remoteObject); - if (bundleMgr == nullptr) { - ANSR_LOGE("Bundle mgr proxy is nullptr"); - return defaultAppIndex; - } - std::string bundleName; - int32_t appIndex = 0; - bundleMgr->GetNameAndIndexForUid(uid, bundleName, appIndex); - ANSR_LOGD("appIndex=%{public}d", appIndex); - return appIndex; -} - -int32_t ReminderRequest::GetUserId(const int32_t &uid) -{ - int32_t userId = -1; - AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); - ANSR_LOGD("userId=%{private}d", userId); - return userId; -} - -void ReminderRequest::AppendWantAgentValuesBucket(const sptr& reminder, - NativeRdb::ValuesBucket& values) +void ReminderRequest::SerializeWantAgent(std::string& wantInfoStr, std::string& maxWantInfoStr) { std::string pkgName; std::string abilityName; std::string uri; std::string parameters; - auto wantAgentInfo = reminder->GetWantAgentInfo(); - if (wantAgentInfo != nullptr) { - pkgName = wantAgentInfo->pkgName; - abilityName = wantAgentInfo->abilityName; - uri = wantAgentInfo->uri; - AAFwk::WantParamWrapper wrapper(wantAgentInfo->parameters); + if (wantAgentInfo_ != nullptr) { + pkgName = wantAgentInfo_->pkgName; + abilityName = wantAgentInfo_->abilityName; + uri = wantAgentInfo_->uri; + AAFwk::WantParamWrapper wrapper(wantAgentInfo_->parameters); parameters = wrapper.ToString(); } nlohmann::json wantInfo; @@ -1928,13 +1789,11 @@ void ReminderRequest::AppendWantAgentValuesBucket(const sptr& r wantInfo["abilityName"] = abilityName; wantInfo["uri"] = uri; wantInfo["parameters"] = parameters; - std::string info = wantInfo.dump(INDENT, ' ', false, nlohmann::json::error_handler_t::replace); - values.PutString(ReminderBaseTable::WANT_AGENT, info); + wantInfoStr = wantInfo.dump(INDENT, ' ', false, nlohmann::json::error_handler_t::replace); - auto maxScreenWantAgentInfo = reminder->GetMaxScreenWantAgentInfo(); - if (maxScreenWantAgentInfo != nullptr) { - pkgName = maxScreenWantAgentInfo->pkgName; - abilityName = maxScreenWantAgentInfo->abilityName; + if (maxScreenWantAgentInfo_ != nullptr) { + pkgName = maxScreenWantAgentInfo_->pkgName; + abilityName = maxScreenWantAgentInfo_->abilityName; uri = ""; parameters = ""; } @@ -1943,50 +1802,7 @@ void ReminderRequest::AppendWantAgentValuesBucket(const sptr& r maxWantInfo["abilityName"] = abilityName; maxWantInfo["uri"] = uri; maxWantInfo["parameters"] = parameters; - info = maxWantInfo.dump(INDENT, ' ', false, nlohmann::json::error_handler_t::replace); - values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, info); -} - -void ReminderRequest::AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values, bool oldVersion) -{ - values.PutInt(ReminderBaseTable::REMINDER_ID, reminder->GetReminderId()); - values.PutString(ReminderBaseTable::PACKAGE_NAME, reminder->GetBundleName()); - values.PutInt(ReminderBaseTable::USER_ID, reminder->GetUserId()); - values.PutInt(ReminderBaseTable::UID, reminder->GetUid()); - values.PutString(ReminderBaseTable::SYSTEM_APP, reminder->IsSystemApp() ? "true" : "false"); - values.PutInt(ReminderBaseTable::REMINDER_TYPE, static_cast(reminder->GetReminderType())); - values.PutLong(ReminderBaseTable::REMINDER_TIME, reminder->GetReminderTimeInMilli()); - values.PutLong(ReminderBaseTable::TRIGGER_TIME, reminder->GetTriggerTimeInMilli()); - values.PutLong(ReminderBaseTable::TIME_INTERVAL, reminder->GetTimeInterval()); - values.PutInt(ReminderBaseTable::SNOOZE_TIMES, reminder->GetSnoozeTimes()); - values.PutInt(ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, reminder->GetSnoozeTimesDynamic()); - values.PutLong(ReminderBaseTable::RING_DURATION, reminder->GetRingDuration()); - values.PutString(ReminderBaseTable::IS_EXPIRED, reminder->IsExpired() ? "true" : "false"); - values.PutInt(ReminderBaseTable::STATE, reminder->GetState()); - values.PutString(ReminderBaseTable::ACTION_BUTTON_INFO, reminder->GetButtonInfo()); - values.PutString(ReminderBaseTable::CUSTOM_BUTTON_URI, reminder->GetCustomButtonUri()); - values.PutInt(ReminderBaseTable::SLOT_ID, reminder->GetSlotType()); - values.PutInt(ReminderBaseTable::SNOOZE_SLOT_ID, reminder->GetSnoozeSlotType()); - values.PutInt(ReminderBaseTable::NOTIFICATION_ID, reminder->GetNotificationId()); - values.PutString(ReminderBaseTable::TITLE, reminder->GetTitle()); - values.PutString(ReminderBaseTable::CONTENT, reminder->GetContent()); - values.PutString(ReminderBaseTable::SNOOZE_CONTENT, reminder->GetSnoozeContent()); - values.PutString(ReminderBaseTable::EXPIRED_CONTENT, reminder->GetExpiredContent()); - - if (oldVersion) { - values.PutString(ReminderBaseTable::WANT_AGENT, reminder->GetWantAgentStr()); - values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, reminder->GetMaxWantAgentStr()); - } else { - AppendWantAgentValuesBucket(reminder, values); - } - - values.PutString(ReminderBaseTable::TAP_DISMISSED, reminder->IsTapDismissed() ? "true" : "false"); - values.PutLong(ReminderBaseTable::AUTO_DELETED_TIME, reminder->GetAutoDeletedTime()); - values.PutString(ReminderBaseTable::GROUP_ID, reminder->GetGroupId()); - values.PutString(ReminderBaseTable::CUSTOM_RING_URI, reminder->GetCustomRingUri()); - values.PutString(ReminderBaseTable::CREATOR_BUNDLE_NAME, reminder->GetCreatorBundleName()); - values.PutInt(ReminderBaseTable::CREATOR_UID, reminder->GetCreatorUid()); + maxWantInfoStr = maxWantInfo.dump(INDENT, ' ', false, nlohmann::json::error_handler_t::replace); } int64_t ReminderRequest::GetNextDaysOfWeek(const time_t now, const time_t target) const @@ -2072,7 +1888,7 @@ uint64_t ReminderRequest::GetTriggerTime(const time_t now, const time_t nextTrig struct tm test; (void)localtime_r(&triggerTime, &test); ANSR_LOGI("NextTriggerTime: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, " - "min=%{public}d, sec=%{public}d, week=%{public}d, nextTriggerTime=%{public}lld", + "min=%{public}d, sec=%{public}d, week=%{public}d, nextTriggerTime=%{public}lld", GetActualTime(TimeTransferType::YEAR, test.tm_year), GetActualTime(TimeTransferType::MONTH, test.tm_mon), test.tm_mday, @@ -2095,6 +1911,9 @@ void ReminderRequest::OnLanguageChange(const std::shared_ptrGetStringByName(button.second.resource.c_str(), title); if (title.empty()) { @@ -2102,146 +1921,6 @@ void ReminderRequest::OnLanguageChange(const std::shared_ptr& resultSet) -{ - // reminderId - ReminderStore::GetInt32Val(resultSet, ReminderTable::REMINDER_ID, reminderId_); - - // userId - ReminderStore::GetInt32Val(resultSet, ReminderTable::USER_ID, userId_); - - // bundleName - ReminderStore::GetStringVal(resultSet, ReminderTable::PKG_NAME, bundleName_); - - // uid - ReminderStore::GetInt32Val(resultSet, ReminderTable::UID, uid_); - - // isSystemApp - std::string isSysApp; - ReminderStore::GetStringVal(resultSet, ReminderTable::SYS_APP, isSysApp); - isSystemApp_ = isSysApp == "true" ? true : false; - - // reminderType - int32_t reminderType; - ReminderStore::GetInt32Val(resultSet, ReminderTable::REMINDER_TYPE, reminderType); - reminderType_ = ReminderType(reminderType); - - // reminderTime - reminderTimeInMilli_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::REMINDER_TIME, - DbRecoveryType::LONG)); - - // triggerTime - triggerTimeInMilli_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::TRIGGER_TIME, - DbRecoveryType::LONG)); - - // timeInterval - uint64_t timeIntervalInSecond = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::TIME_INTERVAL, - DbRecoveryType::LONG)); - SetTimeInterval(timeIntervalInSecond); - - // snoozeTimes - snoozeTimes_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::SNOOZE_TIMES, - DbRecoveryType::INT)); - - // dynamicSnoozeTimes - snoozeTimesDynamic_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::DYNAMIC_SNOOZE_TIMES, - DbRecoveryType::INT)); - - // ringDuration - uint64_t ringDurationInSecond = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::RING_DURATION, - DbRecoveryType::LONG)); - SetRingDuration(ringDurationInSecond); - - // isExpired - std::string isExpired; - ReminderStore::GetStringVal(resultSet, ReminderTable::IS_EXPIRED, isExpired); - isExpired_ = isExpired == "true" ? true : false; - - // state - state_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::STATE, DbRecoveryType::INT)); - - // repeatDaysOfWeek_ - repeatDaysOfWeek_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::REPEAT_DAYS_OF_WEEK, - DbRecoveryType::INT)); - - // action buttons - RecoverActionButton(resultSet); - - // slotType - int32_t slotType; - ReminderStore::GetInt32Val(resultSet, ReminderTable::SLOT_ID, slotType); - slotType_ = NotificationConstant::SlotType(slotType); - - // snoozeSlotType - int32_t snoozeSlotType; - ReminderStore::GetInt32Val(resultSet, ReminderTable::SNOOZE_SLOT_ID, snoozeSlotType); - snoozeSlotType_ = NotificationConstant::SlotType(snoozeSlotType); - - // notification id - ReminderStore::GetInt32Val(resultSet, ReminderTable::NOTIFICATION_ID, notificationId_); - - // title - ReminderStore::GetStringVal(resultSet, ReminderTable::TITLE, title_); - - // content - ReminderStore::GetStringVal(resultSet, ReminderTable::CONTENT, content_); - - // snoozeContent - ReminderStore::GetStringVal(resultSet, ReminderTable::SNOOZE_CONTENT, snoozeContent_); - - // expiredContent - ReminderStore::GetStringVal(resultSet, ReminderTable::EXPIRED_CONTENT, expiredContent_); -} - -void ReminderRequest::RecoverFromOldVersion(const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - - RecoverBasicFromOldVersion(resultSet); - - // wantAgent - std::string wantAgent; - ReminderStore::GetStringVal(resultSet, ReminderTable::AGENT, wantAgent); - wantAgentStr_ = wantAgent; - - // maxScreenWantAgent - std::string maxScreenWantAgent; - ReminderStore::GetStringVal(resultSet, ReminderTable::MAX_SCREEN_AGENT, maxScreenWantAgent); - maxWantAgentStr_ = maxScreenWantAgent; - - // tapDismissed - std::string tapDismissed; - ReminderStore::GetStringVal(resultSet, ReminderTable::TAP_DISMISSED, tapDismissed); - tapDismissed_ = tapDismissed == "true" ? true : false; - - // autoDeletedTime - autoDeletedTime_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::AUTO_DELETED_TIME, - DbRecoveryType::LONG)); - - // customButtonUri - ReminderStore::GetStringVal(resultSet, ReminderTable::CUSTOM_BUTTON_URI, customButtonUri_); - - // groupId - ReminderStore::GetStringVal(resultSet, ReminderTable::GROUP_ID, groupId_); - - // customRingUri - ReminderStore::GetStringVal(resultSet, ReminderTable::CUSTOM_RING_URI, customRingUri_); - - // creatorBundleName - ReminderStore::GetStringVal(resultSet, ReminderTable::CREATOR_BUNDLE_NAME, creatorBundleName_); } } } diff --git a/frameworks/ans/src/reminder_request_alarm.cpp b/frameworks/ans/src/reminder_request_alarm.cpp index 8a08f7a5523b8629f5111748fe3d14a22f8aba11..8fd928b2b89b5221952eb2cf9e365915d289218b 100644 --- a/frameworks/ans/src/reminder_request_alarm.cpp +++ b/frameworks/ans/src/reminder_request_alarm.cpp @@ -16,9 +16,6 @@ #include "reminder_request_alarm.h" #include "ans_log_wrapper.h" -#include "reminder_table.h" -#include "reminder_table_old.h" -#include "reminder_store.h" namespace OHOS { namespace Notification { @@ -114,6 +111,16 @@ uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const return GetTriggerTime(now, nextTriggerTime); } +void ReminderRequestAlarm::SetHour(const uint8_t hour) +{ + hour_ = hour; +} + +void ReminderRequestAlarm::SetMinute(const uint8_t minute) +{ + minute_ = minute; +} + uint8_t ReminderRequestAlarm::GetHour() const { return hour_; @@ -197,49 +204,5 @@ bool ReminderRequestAlarm::ReadFromParcel(Parcel &parcel) } return false; } - -void ReminderRequestAlarm::RecoverFromOldVersion(const std::shared_ptr &resultSet) -{ - ReminderRequest::RecoverFromOldVersion(resultSet); - - // hour - hour_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::ALARM_HOUR, - DbRecoveryType::INT)); - - // minute - minute_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::ALARM_MINUTE, - DbRecoveryType::INT)); -} - -void ReminderRequestAlarm::RecoverFromDb(const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - ReminderStore::GetUInt8Val(resultSet, ReminderAlarmTable::ALARM_HOUR, hour_); - ReminderStore::GetUInt8Val(resultSet, ReminderAlarmTable::ALARM_MINUTE, minute_); - ReminderStore::GetUInt8Val(resultSet, ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek_); -} - -void ReminderRequestAlarm::AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values) -{ - uint8_t hour = 0; - uint8_t minute = 0; - uint8_t repeatDaysOfWeek = 0; - if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { - ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); - hour = alarm->GetHour(); - minute = alarm->GetMinute(); - repeatDaysOfWeek = alarm->GetRepeatDaysOfWeek(); - } - values.PutInt(ReminderAlarmTable::REMINDER_ID, reminder->GetReminderId()); - values.PutInt(ReminderAlarmTable::ALARM_HOUR, hour); - values.PutInt(ReminderAlarmTable::ALARM_MINUTE, minute); - values.PutInt(ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); -} } } \ No newline at end of file diff --git a/frameworks/ans/src/reminder_request_calendar.cpp b/frameworks/ans/src/reminder_request_calendar.cpp index 0f1ead00658f740b586428f50f8e5469d28c2e30..df26f548ccc0977ec839176fbbb85216b8152b4b 100644 --- a/frameworks/ans/src/reminder_request_calendar.cpp +++ b/frameworks/ans/src/reminder_request_calendar.cpp @@ -16,9 +16,6 @@ #include "reminder_request_calendar.h" #include "ans_log_wrapper.h" -#include "reminder_table.h" -#include "reminder_table_old.h" -#include "reminder_store.h" #include "nlohmann/json.hpp" namespace OHOS { @@ -128,6 +125,56 @@ std::shared_ptr ReminderRequestCalendar::GetRRul return rruleWantAgentInfo_; } +void ReminderRequestCalendar::SetRepeatDay(const uint32_t repeatDay) +{ + repeatDay_ = repeatDay; +} + +void ReminderRequestCalendar::SetRepeatMonth(const uint16_t repeatMonth) +{ + repeatMonth_ = repeatMonth; +} + +void ReminderRequestCalendar::SetFirstDesignateYear(const uint16_t firstDesignateYear) +{ + firstDesignateYear_ = firstDesignateYear; +} + +void ReminderRequestCalendar::SetFirstDesignageMonth(const uint16_t firstDesignateMonth) +{ + firstDesignateMonth_ = firstDesignateMonth; +} + +void ReminderRequestCalendar::SetFirstDesignateDay(const uint16_t firstDesignateDay) +{ + firstDesignateDay_ = firstDesignateDay; +} + +void ReminderRequestCalendar::SetYear(const uint16_t year) +{ + year_ = year; +} + +void ReminderRequestCalendar::SetMonth(const uint8_t month) +{ + month_ = month; +} + +void ReminderRequestCalendar::SetDay(const uint8_t day) +{ + day_ = day; +} + +void ReminderRequestCalendar::SetHour(const uint8_t hour) +{ + hour_ = hour; +} + +void ReminderRequestCalendar::SetMinute(const uint8_t minute) +{ + minute_ = minute; +} + bool ReminderRequestCalendar::InitTriggerTime() { uint64_t nextTriggerTime = INVALID_LONG_LONG_VALUE; @@ -240,6 +287,9 @@ bool ReminderRequestCalendar::OnDateTimeChange() if (IsExpired()) { return false; } + if (startDateTime_ == endDateTime_) { + return ReminderRequest::OnDateTimeChange(); + } uint64_t now = GetNowInstantMilli(); if (now == 0) { ANSR_LOGE("get now time failed"); @@ -300,7 +350,8 @@ bool ReminderRequestCalendar::IsNeedNotification() ANSR_LOGE("get now time failed"); return false; } - if (now <= endDateTime_ && now >= startDateTime_) { + if ((now <= endDateTime_ && now >= startDateTime_) || + (startDateTime_ == endDateTime_)) { return true; } uint64_t triggerTime = GetNextTriggerTime(true); @@ -567,6 +618,9 @@ bool ReminderRequestCalendar::UpdateNextReminder() ANSR_LOGI("No need to update next trigger time as it is an one-time reminder."); SetSnoozeTimesDynamic(GetSnoozeTimes()); SetTriggerTimeInMilli(INVALID_LONG_LONG_VALUE); + if (startDateTime_ == endDateTime_) { + SetExpired(true); + } return false; } uint8_t leftSnoozeTimes = GetSnoozeTimesDynamic(); @@ -579,6 +633,9 @@ bool ReminderRequestCalendar::UpdateNextReminder() if ((repeatMonth_ == 0 || repeatDay_ == 0) && (repeatDaysOfWeek_ == 0)) { ANSR_LOGI("Not a day repeat reminder, no need to update to next trigger time."); SetTriggerTimeInMilli(INVALID_LONG_LONG_VALUE); + if (startDateTime_ == endDateTime_) { + SetExpired(true); + } return false; } else { uint64_t nextTriggerTime = GetNextTriggerTime(); @@ -689,145 +746,6 @@ bool ReminderRequestCalendar::ReadFromParcel(Parcel &parcel) return false; } -void ReminderRequestCalendar::RecoverFromOldVersion(const std::shared_ptr &resultSet) -{ - ReminderRequest::RecoverFromOldVersion(resultSet); - - // repeatDay - repeatDay_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::REPEAT_DAYS, - DbRecoveryType::INT)); - - // repeatMonth - repeatMonth_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::REPEAT_MONTHS, - DbRecoveryType::INT)); - - // firstDesignateYear - firstDesignateYear_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::FIRST_DESIGNATE_YEAR, - DbRecoveryType::INT)); - - // firstDesignateMonth - firstDesignateMonth_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::FIRST_DESIGNATE_MONTH, - DbRecoveryType::INT)); - - // firstDesignateDay - firstDesignateDay_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::FIRST_DESIGNATE_DAY, - DbRecoveryType::INT)); - - // year - year_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::CALENDAR_YEAR, - DbRecoveryType::INT)); - - // month - month_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::CALENDAR_MONTH, - DbRecoveryType::INT)); - - // day - day_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::CALENDAR_DAY, - DbRecoveryType::INT)); - - // hour - hour_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::CALENDAR_HOUR, - DbRecoveryType::INT)); - - // minute - minute_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::CALENDAR_MINUTE, - DbRecoveryType::INT)); -} - -void ReminderRequestCalendar::RecoverFromDb(const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - ReminderStore::GetUInt16Val(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_YEAR, firstDesignateYear_); - ReminderStore::GetUInt8Val(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth_); - ReminderStore::GetUInt8Val(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_DAY, firstDesignateDay_); - - uint64_t dateTime; - ReminderStore::GetUInt64Val(resultSet, ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); - SetDateTime(dateTime); - - uint64_t endDateTime; - ReminderStore::GetUInt64Val(resultSet, ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); - if (endDateTime != 0 && endDateTime >= dateTime) { - SetEndDateTime(endDateTime); - } else { - SetEndDateTime(startDateTime_); - } - - uint64_t lastStartDateTime; - ReminderStore::GetUInt64Val(resultSet, ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, lastStartDateTime); - if (lastStartDateTime == 0) { - SetLastStartDateTime(dateTime); - } else { - SetLastStartDateTime(lastStartDateTime); - } - - int32_t repeatDay; - ReminderStore::GetInt32Val(resultSet, ReminderCalendarTable::REPEAT_DAYS, repeatDay); - repeatDay_ = static_cast(repeatDay); - - ReminderStore::GetUInt16Val(resultSet, ReminderCalendarTable::REPEAT_MONTHS, repeatMonth_); - ReminderStore::GetUInt8Val(resultSet, ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek_); - - std::string rruleWantAgent; - ReminderStore::GetStringVal(resultSet, ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); - DeserializationRRule(rruleWantAgent); - - std::string excludeDates; - ReminderStore::GetStringVal(resultSet, ReminderCalendarTable::EXCLUDE_DATES, excludeDates); - DeserializationExcludeDates(excludeDates); -} - -void ReminderRequestCalendar::AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values) -{ - uint16_t firstDesignateYear = 0; - uint8_t firstDesignateMonth = 0; - uint8_t firstDesignateDay = 0; - uint64_t dateTime = 0; - uint32_t repeatDay = 0; - uint16_t repeatMonth = 0; - uint8_t repeatDaysOfWeek = 0; - uint64_t endDateTime = 0; - uint64_t lastStartDateTime = 0; - std::string rruleWantAgent; - std::string excludeDates; - if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { - ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); - if (calendar != nullptr) { - repeatDay = calendar->GetRepeatDay(); - repeatMonth = calendar->GetRepeatMonth(); - firstDesignateYear = calendar->GetFirstDesignateYear(); - firstDesignateMonth = calendar->GetFirstDesignageMonth(); - firstDesignateDay = calendar->GetFirstDesignateDay(); - dateTime = calendar->GetDateTime(); - repeatDaysOfWeek = calendar->GetRepeatDaysOfWeek(); - endDateTime = calendar->GetEndDateTime(); - lastStartDateTime = calendar->GetLastStartDateTime(); - rruleWantAgent = calendar->SerializationRRule(); - excludeDates = calendar->SerializationExcludeDates(); - } - } - values.PutInt(ReminderCalendarTable::REMINDER_ID, reminder->GetReminderId()); - values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_YEAR, firstDesignateYear); - values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth); - values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_DAY, firstDesignateDay); - values.PutLong(ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); - values.PutLong(ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); - values.PutLong(ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, lastStartDateTime); - values.PutInt(ReminderCalendarTable::REPEAT_DAYS, repeatDay); - values.PutInt(ReminderCalendarTable::REPEAT_MONTHS, repeatMonth); - values.PutInt(ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); - values.PutString(ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); - values.PutString(ReminderCalendarTable::EXCLUDE_DATES, excludeDates); -} - void ReminderRequestCalendar::SetDateTime(const uint64_t time) { time_t t = static_cast(time / MILLI_SECONDS); @@ -853,12 +771,12 @@ bool ReminderRequestCalendar::SetEndDateTime(const uint64_t time) return true; } -uint64_t ReminderRequestCalendar::GetDateTime() +uint64_t ReminderRequestCalendar::GetDateTime() const { return startDateTime_; } -uint64_t ReminderRequestCalendar::GetEndDateTime() +uint64_t ReminderRequestCalendar::GetEndDateTime() const { return endDateTime_; } diff --git a/frameworks/ans/src/reminder_request_timer.cpp b/frameworks/ans/src/reminder_request_timer.cpp index 6881b6261f6bbd2b490c77ad26e0c243dcb9ff4a..867f26ae9266e07d45dfbef647b9779336bb7d17 100644 --- a/frameworks/ans/src/reminder_request_timer.cpp +++ b/frameworks/ans/src/reminder_request_timer.cpp @@ -20,8 +20,6 @@ #include "ans_log_wrapper.h" #include "time_service_client.h" -#include "reminder_table.h" -#include "reminder_store.h" namespace OHOS { namespace Notification { @@ -58,6 +56,11 @@ uint64_t ReminderRequestTimer::GetInitInfo() const return countDownTimeInSeconds_; } +void ReminderRequestTimer::SetInitInfo(const uint64_t countDownTimeInSeconds) +{ + countDownTimeInSeconds_ = countDownTimeInSeconds; +} + uint64_t ReminderRequestTimer::PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) { ANSR_LOGD("countdown time not support PreGetNextTriggerTimeIgnoreSnooze"); @@ -150,28 +153,5 @@ bool ReminderRequestTimer::ReadFromParcel(Parcel &parcel) } return false; } - -void ReminderRequestTimer::RecoverFromDb(const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - ReminderStore::GetUInt64Val(resultSet, ReminderTimerTable::TRIGGER_SECOND, countDownTimeInSeconds_); -} - -void ReminderRequestTimer::AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values) -{ - uint64_t seconds = 0; - if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { - ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); - seconds = timer->GetInitInfo(); - } - values.PutInt(ReminderTimerTable::REMINDER_ID, reminder->GetReminderId()); - values.PutLong(ReminderTimerTable::TRIGGER_SECOND, seconds); - values.PutLong(ReminderTimerTable::START_DATE_TIME, 0); - values.PutLong(ReminderTimerTable::END_DATE_TIME, 0); -} } } diff --git a/frameworks/ans/test/unittest/BUILD.gn b/frameworks/ans/test/unittest/BUILD.gn index ae68e1aefe029b4bd40d2a49a62cc73a0c29df3d..d6a5b2f1e7025f8ae7e58ba2aa1fa7b313637558 100644 --- a/frameworks/ans/test/unittest/BUILD.gn +++ b/frameworks/ans/test/unittest/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("ans_reminder_unit_test") { "${frameworks_module_ans_path}/test/unittest/notification_picture_content_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_progress_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_request_test.cpp", + "${frameworks_module_ans_path}/test/unittest/notification_slot_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_sorting_map_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_sorting_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_subscribe_info_test.cpp", @@ -73,6 +74,7 @@ ohos_unittest("ans_reminder_unit_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", "//third_party/googletest:gtest_main", ] diff --git a/frameworks/ans/test/unittest/notification_bundle_option_test.cpp b/frameworks/ans/test/unittest/notification_bundle_option_test.cpp index 2d1a0577b06e1386efcfdd1afe05d5d1d0e544cb..83089557f5247f4159f0fdfa4b4d5607bdd5a7a5 100644 --- a/frameworks/ans/test/unittest/notification_bundle_option_test.cpp +++ b/frameworks/ans/test/unittest/notification_bundle_option_test.cpp @@ -75,7 +75,7 @@ HWTEST_F(NotificationBundleOptionTest, Dump_00001, Function | SmallTest | Level1 std::string bundleName = "BundleName"; int32_t uid = 10; auto rrc = std::make_shared(bundleName, uid); - std::string ret = "NotificationBundleOption{ bundleName = BundleName, uid = 10, instanceKey = 0 }"; + std::string ret = "NotificationBundleOption{ bundleName = BundleName, uid = 10, instanceKey = 0, appIndex = -1 }"; EXPECT_EQ(rrc->Dump(), ret); } diff --git a/frameworks/ans/test/unittest/notification_helper_test.cpp b/frameworks/ans/test/unittest/notification_helper_test.cpp index 85597c7e18daf491e5903bc2fa118efd7525c44f..ad2574b85934bd8e0af3a8a0c243131758e473b5 100644 --- a/frameworks/ans/test/unittest/notification_helper_test.cpp +++ b/frameworks/ans/test/unittest/notification_helper_test.cpp @@ -262,7 +262,7 @@ HWTEST_F(NotificationHelperTest, CancelAsBundle_00001, Function | SmallTest | Le int32_t userId = 10; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.CancelAsBundle(notificationId, representativeBundle, userId); - EXPECT_EQ(ret, (int)ERROR_USER_NOT_EXIST); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -279,7 +279,7 @@ HWTEST_F(NotificationHelperTest, CancelAsBundle_00002, Function | SmallTest | Le bundleOption.SetUid(20); NotificationHelper notificationHelper; ErrCode ret = notificationHelper.CancelAsBundle(bundleOption, notificationId); - EXPECT_EQ(ret, (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -481,7 +481,7 @@ HWTEST_F(NotificationHelperTest, RemoveNotification_00001, Function | SmallTest int32_t removeReason = 2; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.RemoveNotification(key, removeReason); - EXPECT_EQ(ret, (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -539,7 +539,7 @@ HWTEST_F(NotificationHelperTest, RemoveNotifications_00001, Function | SmallTest { NotificationHelper notificationHelper; ErrCode ret = notificationHelper.RemoveNotifications(); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -583,7 +583,7 @@ HWTEST_F(NotificationHelperTest, GetAllActiveNotifications_00001, Function | Sma std::vector> notification; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.GetAllActiveNotifications(notification); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -628,7 +628,7 @@ HWTEST_F(NotificationHelperTest, SetNotificationsEnabledForAllBundles_00001, Fun bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetNotificationsEnabledForAllBundles(deviceId, enabled); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -758,7 +758,7 @@ HWTEST_F(NotificationHelperTest, DoesSupportDoNotDisturbMode_00001, Function | S bool doesSupport = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.DoesSupportDoNotDisturbMode(doesSupport); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -801,7 +801,7 @@ HWTEST_F(NotificationHelperTest, EnableDistributedByBundle_00001, Function | Sma bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.EnableDistributedByBundle(bundleOption, enabled); - EXPECT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -830,7 +830,7 @@ HWTEST_F(NotificationHelperTest, IsDistributedEnableByBundle_00001, Function | S bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.IsDistributedEnableByBundle(bundleOption, enabled); - EXPECT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -844,7 +844,7 @@ HWTEST_F(NotificationHelperTest, GetDeviceRemindType_00001, Function | SmallTest NotificationConstant::RemindType remindType = NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.GetDeviceRemindType(remindType); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -903,7 +903,7 @@ HWTEST_F(NotificationHelperTest, SetNotificationsEnabledForAllBundles_00002, Fun bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetNotificationsEnabledForAllBundles(userId, enabled); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -933,7 +933,7 @@ HWTEST_F(NotificationHelperTest, IsAllowedNotify_00004, Function | SmallTest | L bool allowed = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.IsAllowedNotify(userId, allowed); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -948,7 +948,7 @@ HWTEST_F(NotificationHelperTest, SetNotificationsEnabledForAllBundles_00003, Fun bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetNotificationsEnabledForAllBundles(userId, enabled); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -1054,7 +1054,7 @@ HWTEST_F(NotificationHelperTest, GetSyncNotificationEnabledWithoutApp_00001, Fun bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.GetSyncNotificationEnabledWithoutApp(userId, enabled); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -1121,7 +1121,7 @@ HWTEST_F(NotificationHelperTest, SetSmartReminderEnabled_0100, TestSize.Level1) std::string deviceType = "testDeviceType"; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetSmartReminderEnabled(deviceType, true); - EXPECT_EQ(ret, ERR_OK); + EXPECT_EQ(ret, ERR_ANS_PERMISSION_DENIED); } /** @@ -1134,7 +1134,7 @@ HWTEST_F(NotificationHelperTest, SetSmartReminderEnabled_0200, TestSize.Level1) std::string deviceType = ""; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetSmartReminderEnabled(deviceType, true); - EXPECT_EQ(ret, ERR_ANS_INVALID_PARAM); + EXPECT_EQ(ret, ERR_ANS_PERMISSION_DENIED); } /** @@ -1148,39 +1148,7 @@ HWTEST_F(NotificationHelperTest, IsSmartReminderEnabled_0100, TestSize.Level1) NotificationHelper notificationHelper; bool enable = true; ErrCode ret = notificationHelper.IsSmartReminderEnabled(deviceType, enable); - EXPECT_EQ(ret, ERR_OK); - EXPECT_EQ(enable, false); -} - -/** - * @tc.name: IsSmartReminderEnabled_0200 - * @tc.desc: test IsSmartReminderEnabled with parameters, expect errorCode ERR_ANS_INVALID_PARAM. - * @tc.type: FUNC - */ -HWTEST_F(NotificationHelperTest, IsSmartReminderEnabled_0200, TestSize.Level1) -{ - std::string deviceType = ""; - NotificationHelper notificationHelper; - bool enable = true; - ErrCode ret = notificationHelper.IsSmartReminderEnabled(deviceType, enable); - EXPECT_EQ(ret, ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: IsSmartReminderEnabled_0300 - * @tc.desc: test IsSmartReminderEnabled with parameters - * @tc.type: FUNC - */ -HWTEST_F(NotificationHelperTest, IsSmartReminderEnabled_0300, TestSize.Level1) -{ - std::string deviceType = "testDeviceType"; - NotificationHelper notificationHelper; - ErrCode ret = notificationHelper.SetSmartReminderEnabled(deviceType, true); - EXPECT_EQ(ret, ERR_OK); - bool enable = false; - ret = notificationHelper.IsSmartReminderEnabled(deviceType, enable); - EXPECT_EQ(ret, ERR_OK); - EXPECT_EQ(enable, true); + EXPECT_EQ(ret, ERR_ANS_PERMISSION_DENIED); } /** @@ -1227,7 +1195,7 @@ HWTEST_F(NotificationHelperTest, SetDistributedEnabledByBundle_0100, TestSize.Le std::string deviceType = "testDeviceType"; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetDistributedEnabledByBundle(bundleOption, deviceType, true); - EXPECT_EQ(ret, ERR_OK); + EXPECT_EQ(ret, ERR_ANS_PERMISSION_DENIED); } /** @@ -1259,8 +1227,7 @@ HWTEST_F(NotificationHelperTest, IsDistributedEnabledByBundle_0100, TestSize.Lev NotificationHelper notificationHelper; bool enable = true; ErrCode ret = notificationHelper.IsDistributedEnabledByBundle(bundleOption, deviceType, enable); - EXPECT_EQ(ret, ERR_OK); - EXPECT_EQ(enable, false); + EXPECT_EQ(ret, ERR_ANS_PERMISSION_DENIED); } /** @@ -1280,27 +1247,6 @@ HWTEST_F(NotificationHelperTest, IsDistributedEnabledByBundle_0200, TestSize.Lev EXPECT_EQ(ret, ERR_ANS_INVALID_PARAM); } -/** - * @tc.name: IsDistributedEnabledByBundle_0300 - * @tc.desc: test IsDistributedEnabledByBundle with parameters - * @tc.type: FUNC - */ -HWTEST_F(NotificationHelperTest, IsDistributedEnabledByBundle_0300, TestSize.Level1) -{ - NotificationBundleOption bundleOption; - std::string bundleName = "bundleName"; - bundleOption.SetBundleName(bundleName); - bundleOption.SetUid(1); - std::string deviceType = "testDeviceType"; - NotificationHelper notificationHelper; - ErrCode ret = notificationHelper.SetDistributedEnabledByBundle(bundleOption, deviceType, true); - EXPECT_EQ(ret, ERR_OK); - bool enable = false; - ret = notificationHelper.IsDistributedEnabledByBundle(bundleOption, deviceType, enable); - EXPECT_EQ(ret, ERR_OK); - EXPECT_EQ(enable, true); -} - /** * @tc.name: AddDoNotDisturbProfiles_0100 * @tc.desc: test AddDoNotDisturbProfiles when profiles is empty. @@ -1359,5 +1305,19 @@ HWTEST_F(NotificationHelperTest, RegisterSwingCallback_0100, TestSize.Level1) EXPECT_EQ(ret, ERR_OK); #endif } + +/** + * @tc.name: UpdateNotificationTimerByUid_00001 + * @tc.desc: Test UpdateNotificationTimerByUid. + * @tc.type: FUNC + */ +HWTEST_F(NotificationHelperTest, UpdateNotificationTimerByUid_00001, Function | SmallTest | Level1) +{ + int32_t uid = 20099999; + bool isPaused = true; + NotificationHelper notificationHelper; + ErrCode ret = notificationHelper.UpdateNotificationTimerByUid(uid, isPaused); + EXPECT_EQ(ret, ERR_OK); +} } } diff --git a/frameworks/ans/test/unittest/notification_slot_test.cpp b/frameworks/ans/test/unittest/notification_slot_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d7fb0565bb41cd6a034e76091191fe6637cdcc53 --- /dev/null +++ b/frameworks/ans/test/unittest/notification_slot_test.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "notification_slot.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class NotificationSlotTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() {} +}; + +/** + * @tc.name: GetSlotTypeByString_00001 + * @tc.desc: Test GetSlotTypeByString method is ok. + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(NotificationSlotTest, GetSlotTypeByString_00001, Function | SmallTest | Level1) +{ + NotificationConstant::SlotType type; + EXPECT_EQ(NotificationSlot::GetSlotTypeByString(NotificationSlot::CONTENT_INFORMATION, type), true); + EXPECT_EQ(type, NotificationConstant::SlotType::CONTENT_INFORMATION); +} + +/** + * @tc.name: GetSlotTypeByString_00002 + * @tc.desc: Test GetSlotTypeByString method is false. + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(NotificationSlotTest, GetSlotTypeByString_00002, Function | SmallTest | Level1) +{ + NotificationConstant::SlotType type; + const std::string inputStr = "others"; + EXPECT_EQ(NotificationSlot::GetSlotTypeByString(inputStr, type), false); +} +} +} \ No newline at end of file diff --git a/frameworks/ans/test/unittest/notification_sorting_test.cpp b/frameworks/ans/test/unittest/notification_sorting_test.cpp index fc295f5bdf0751cb576181a3f9e51830ce15a534..d57a2d5dce6416c0de62a3e7a3f3f3757968fec2 100644 --- a/frameworks/ans/test/unittest/notification_sorting_test.cpp +++ b/frameworks/ans/test/unittest/notification_sorting_test.cpp @@ -71,11 +71,13 @@ HWTEST_F(NotificationSortingTest, Marshalling_00002, Function | SmallTest | Leve HWTEST_F(NotificationSortingTest, Unmarshalling_001, Function | SmallTest | Level1) { NotificationSorting sorting; + sptr slot = new (std::nothrow) NotificationSlot(); + sorting.SetSlot(slot); bool unmarshalling = true; Parcel parcel; std::shared_ptr result = std::make_shared(sorting); - + result->Marshalling(parcel); if (nullptr != result) { if (nullptr == result->Unmarshalling(parcel)) { unmarshalling = false; @@ -94,7 +96,10 @@ HWTEST_F(NotificationSortingTest, ReadFromParcel_00001, Function | SmallTest | L { Parcel parcel; NotificationSorting sorting; + sptr slot = new (std::nothrow) NotificationSlot(); + sorting.SetSlot(slot); auto rrc = std::make_shared(sorting); + rrc->Marshalling(parcel); EXPECT_EQ(rrc->ReadFromParcel(parcel), true); } @@ -127,7 +132,7 @@ HWTEST_F(NotificationSortingTest, Dump_00001, Function | SmallTest | Level1) "visiblenessOverride = 30, isDisplayBadge = false, isHiddenNotification = true, " "groupKeyOverride = GroupKeyOverride, slot = NotificationSlot{ id = OTHER, name " "= OTHER, description = , type = 3, level = 1, isBypassDnd = false, visibleness = " - "3, sound = , isLightEnabled = false, lightColor = 0, isVibrate = false, vibration " + "3, sound = file://system/etc/Light.ogg, isLightEnabled = false, lightColor = 0, isVibrate = false, vibration " "= , isShowBadge = true, enabled = true, slotFlags = 0, remindMode = 0 } }"; EXPECT_EQ(rrc->Dump(), ret); } diff --git a/frameworks/ans/test/unittest/notification_subscribe_info_test.cpp b/frameworks/ans/test/unittest/notification_subscribe_info_test.cpp index 10766f6ac08969787438455296f7583d82707c73..d01af4692ae3e3ac196710b12afe264fc5ab98d5 100644 --- a/frameworks/ans/test/unittest/notification_subscribe_info_test.cpp +++ b/frameworks/ans/test/unittest/notification_subscribe_info_test.cpp @@ -167,7 +167,7 @@ HWTEST_F(NotificationSubscribeInfoTest, Dump_00001, Function | SmallTest | Level "appNames = [" + appName + ", ]" + "deviceType = " + deviceType + "userId = " + std::to_string(userId) + - " }"; + "slotTypes = []filterType = 0 }"; EXPECT_EQ(res, rrc->Dump()); } } diff --git a/frameworks/ans/test/unittest/notification_test.cpp b/frameworks/ans/test/unittest/notification_test.cpp index 60ef02bd8c059f8bfd6fa319cbc1834bcec4e731..e3186336d8c15241d54a96f757303b2f221f145c 100644 --- a/frameworks/ans/test/unittest/notification_test.cpp +++ b/frameworks/ans/test/unittest/notification_test.cpp @@ -376,7 +376,7 @@ HWTEST_F(NotificationTest, Unmarshalling_001, Function | SmallTest | Level1) unmarshalling = false; } } - EXPECT_EQ(unmarshalling, true); + EXPECT_EQ(unmarshalling, false); } /** @@ -392,7 +392,7 @@ HWTEST_F(NotificationTest, ReadFromParcel_00001, Function | SmallTest | Level1) sptr request = new NotificationRequest(); auto rrc = std::make_shared(deviceId, request); rrc->Marshalling(parcel); - EXPECT_EQ(rrc->ReadFromParcel(parcel), true); + EXPECT_EQ(rrc->ReadFromParcel(parcel), false); } /** diff --git a/frameworks/ans/test/unittest/reminder_request_alarm_test.cpp b/frameworks/ans/test/unittest/reminder_request_alarm_test.cpp index 1cdf78a7e05c131dd306a6c2202f231e59c1b872..3c748db938db2e5e7fdaf2b8338a6c719ab99078 100644 --- a/frameworks/ans/test/unittest/reminder_request_alarm_test.cpp +++ b/frameworks/ans/test/unittest/reminder_request_alarm_test.cpp @@ -350,8 +350,6 @@ HWTEST_F(ReminderRequestAlarmTest, RecoverFromDb_00100, Function | SmallTest | L uint8_t arr[] = {}; std::vector daysOfWeek (arr, arr + sizeof(arr) / sizeof(uint8_t)); auto rrc = std::make_shared(0, 0, daysOfWeek); - std::shared_ptr resultSet = nullptr; - rrc->RecoverFromDb(resultSet); uint8_t ret = rrc->GetRepeatDaysOfWeek(); EXPECT_EQ(ret, 0); } @@ -539,8 +537,6 @@ HWTEST_F(ReminderRequestAlarmTest, RecoverFromOldVersion_00001, Function | Small uint8_t arr[] = {}; std::vector daysOfWeek (arr, arr + sizeof(arr) / sizeof(uint8_t)); auto rrc = std::make_shared(0, 0, daysOfWeek); - std::shared_ptr resultSet = nullptr; - rrc->RecoverFromOldVersion(resultSet); uint8_t ret = rrc->GetRepeatDaysOfWeek(); EXPECT_EQ(ret, 0); } diff --git a/frameworks/ans/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp b/frameworks/ans/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp index 1c8599bb6bb4682153034c3e3fca7279c57a23a9..4d4e655f8b45ecee7252c06f23c7e1d4a4e656d8 100644 --- a/frameworks/ans/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp +++ b/frameworks/ans/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp @@ -295,7 +295,7 @@ HWTEST_F(ReminderRequestBranchTest, GetButtonInfo_00100, Function | SmallTest | info.wantAgent = nullptr; reminderRequest->actionButtonMap_.insert( std::pair(actionButtonType, info)); - EXPECT_NE(reminderRequest->GetButtonInfo(), ""); + EXPECT_NE(reminderRequest->SerializeButtonInfo(), ""); } /** @@ -323,7 +323,7 @@ HWTEST_F(ReminderRequestBranchTest, GetButtonInfo_00200, Function | SmallTest | info.wantAgent->abilityName = abilityName; reminderRequest->actionButtonMap_.insert( std::pair(actionButtonType, info)); - EXPECT_NE(reminderRequest->GetButtonInfo(), ""); + EXPECT_NE(reminderRequest->SerializeButtonInfo(), ""); } /** diff --git a/frameworks/ans/test/unittest/reminder_request_calendar_test.cpp b/frameworks/ans/test/unittest/reminder_request_calendar_test.cpp index 14a8a4121ba632f6a27fa664366e0c520c6c5512..bea879c3b63e0f86e93725fd5e3bf9f303e511d5 100644 --- a/frameworks/ans/test/unittest/reminder_request_calendar_test.cpp +++ b/frameworks/ans/test/unittest/reminder_request_calendar_test.cpp @@ -421,9 +421,6 @@ HWTEST_F(ReminderRequestCalendarTest, PreGetNextTriggerTimeIgnoreSnooze_03000, F struct tm nowTime; auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); EXPECT_NE(nullptr, calendar); - std::shared_ptr resultSet = - std::make_shared(); - calendar->RecoverFromDb(resultSet); EXPECT_EQ(calendar->PreGetNextTriggerTimeIgnoreSnooze(ignoreRepeat, forceToGetNext), calendar->GetNextTriggerTime()); @@ -954,11 +951,8 @@ HWTEST_F(ReminderRequestCalendarTest, RecoverFromDb_00001, Function | SmallTest auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); EXPECT_NE(nullptr, calendar); - std::shared_ptr resultSet = - std::make_shared(); - calendar->RecoverFromDb(resultSet); bool result = calendar->IsRepeatDay(1); - EXPECT_EQ(result, false); + EXPECT_EQ(result, true); } /** @@ -1102,11 +1096,8 @@ HWTEST_F(ReminderRequestCalendarTest, RecoverFromOldVersion_00001, Function | Sm auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); EXPECT_NE(nullptr, calendar); - std::shared_ptr resultSet = - std::make_shared(); - calendar->RecoverFromOldVersion(resultSet); bool result = calendar->IsRepeatDay(1); - EXPECT_EQ(result, false); + EXPECT_EQ(result, true); } /** @@ -1501,15 +1492,6 @@ HWTEST_F(ReminderRequestCalendarTest, AppendValuesBucket_00001, Function | Small std::vector daysOfWeek; sptr calendar = new ReminderRequestCalendar(nowTime, repeatMonths, repeatDays, daysOfWeek); EXPECT_NE(nullptr, calendar); - calendar->reminderId_ = 100; - - NativeRdb::ValuesBucket bucket; - NativeRdb::ValueObject object; - ReminderRequestCalendar::AppendValuesBucket(calendar, nullptr, bucket); - bucket.GetObject(ReminderCalendarTable::REMINDER_ID, object); - int32_t result {0}; - object.GetInt(result); - EXPECT_EQ(result, 100); } /** diff --git a/frameworks/ans/test/unittest/reminder_request_test.cpp b/frameworks/ans/test/unittest/reminder_request_test.cpp index b1fd3e023e48c0236466116a5a8056a00ca27c44..0489d7cbbab32cb918b7b6616775891a68d25ba1 100644 --- a/frameworks/ans/test/unittest/reminder_request_test.cpp +++ b/frameworks/ans/test/unittest/reminder_request_test.cpp @@ -784,21 +784,6 @@ HWTEST_F(ReminderRequestTest, OnTimeZoneChange_00001, Function | SmallTest | Lev } } -/** - * @tc.name: RecoverInt64FromDb_00001 - * @tc.desc: Test RecoverInt64FromDb parameters. - * @tc.type: FUNC - * @tc.require: issueI5UYHP - */ -HWTEST_F(ReminderRequestTest, RecoverInt64FromDb_00001, Function | SmallTest | Level1) -{ - std::shared_ptr resultSet = nullptr; - std::string columnName = "columnName"; - ReminderRequest::DbRecoveryType columnType = ReminderRequest::DbRecoveryType::INT; - auto rrc = std::make_shared(); - EXPECT_EQ(rrc->RecoverInt64FromDb(resultSet, columnName, columnType), 0); -} - /** * @tc.name: StringSplit_00001 * @tc.desc: Test StringSplit parameters. @@ -991,7 +976,7 @@ HWTEST_F(ReminderRequestTest, IsAlerting_00001, Function | SmallTest | Level1) HWTEST_F(ReminderRequestTest, GetButtonInfo_00001, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->GetButtonInfo(), ""); + EXPECT_EQ(rrc->SerializeButtonInfo(), ""); } /** @@ -1025,33 +1010,6 @@ HWTEST_F(ReminderRequestTest, GetShowTime_00002, Function | SmallTest | Level1) EXPECT_EQ(res.substr(4, res.size()), ret); } -/** - * @tc.name: GetUid_00001 - * @tc.desc: Test GetUid parameters. - * @tc.type: FUNC - * @tc.require: issueI5VB6V - */ -HWTEST_F(ReminderRequestTest, GetUid_00001, Function | SmallTest | Level1) -{ - int32_t userId = 1; - std::string bundleName = "bundleName"; - auto rrc = std::make_shared(); - EXPECT_EQ(rrc->GetUid(userId, bundleName), -1); -} - -/** - * @tc.name: GetUserId_00001 - * @tc.desc: Test GetUserId parameters. - * @tc.type: FUNC - * @tc.require: issueI5VB6V - */ -HWTEST_F(ReminderRequestTest, GetUserId_00001, Function | SmallTest | Level1) -{ - int32_t uid = 1; - auto rrc = std::make_shared(); - EXPECT_EQ(rrc->GetUserId(uid), 0); -} - /** * @tc.name: SetActionButton_00001 * @tc.desc: Test SetActionButton parameters. @@ -1209,49 +1167,6 @@ HWTEST_F(ReminderRequestTest, OnStart_00001, Function | SmallTest | Level1) reminderRequestChild->OnStop(); } -/** - * @tc.name: RecoverInt64FromDb_00002 - * @tc.desc: Test RecoverInt64FromDb parameters. - * @tc.type: FUNC - * @tc.require: issueI65R21 - */ -HWTEST_F(ReminderRequestTest, RecoverInt64FromDb_00002, Function | SmallTest | Level1) - -{ - auto rrc = std::make_shared(); - std::shared_ptr resultSet = - std::make_shared(); - std::string columnName = "this is columnName"; - ReminderRequest::DbRecoveryType columnType = ReminderRequest::DbRecoveryType::INT; - int64_t result = rrc->RecoverInt64FromDb(resultSet, columnName, columnType); - EXPECT_EQ(result, 0); - - ReminderRequest::DbRecoveryType columnType2 = ReminderRequest::DbRecoveryType::LONG; - int64_t result2 = rrc->RecoverInt64FromDb(resultSet, columnName, columnType2); - EXPECT_EQ(result2, 0); - rrc->RecoverFromDb(resultSet); - rrc->RecoverActionButton(resultSet); - rrc->RecoverActionButton(nullptr); -} - -/** - * @tc.name: RecoverInt64FromDb_00003 - * @tc.desc: Test RecoverInt64FromDb parameters. - * @tc.type: FUNC - * @tc.require: issueI65R21 - */ -HWTEST_F(ReminderRequestTest, RecoverInt64FromDb_00003, Function | SmallTest | Level1) -{ - auto rrc = std::make_shared(); - std::shared_ptr resultSet = - std::make_shared(); - std::string columnName = "this is columnName"; - - ReminderRequest::DbRecoveryType columnType = ReminderRequest::DbRecoveryType(3); - int64_t result2 = rrc->RecoverInt64FromDb(resultSet, columnName, columnType); - EXPECT_EQ(result2, 0); -} - /** * @tc.name: RecoverWantAgent_00002 * @tc.desc: Test RecoverWantAgent parameters. @@ -1334,20 +1249,6 @@ HWTEST_F(ReminderRequestTest, CreateWantAgent_00002, Function | SmallTest | Leve EXPECT_EQ(WantAgent, nullptr); } -/** - * @tc.name: AddColumn_00002 - * @tc.desc: Test AddColumn parameters. - * @tc.type: FUNC - * @tc.require: issueI65R21 - */ -HWTEST_F(ReminderRequestTest, AddColumn_00002, Function | SmallTest | Level1) -{ - std::string name = "this is name"; - std::string type = "this is type"; - ReminderTable::AddColumn(name, type, true); - ReminderTable::AddColumn(name, type, false); -} - /** * @tc.name: OnClose_00100 * @tc.desc: Test OnClose parameters. @@ -1467,7 +1368,7 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00003, Function | SmallTest | Lev uint8_t type = 0; std::vector ret1 = rrc->StringSplit(wantAgentInfo, ""); EXPECT_EQ(ret1.size(), 2); - rrc->RecoverWantAgent(wantAgentInfo, type); + rrc->DeserializeWantAgent(wantAgentInfo, type); } /** @@ -1483,7 +1384,7 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00004, Function | SmallTest | Lev uint8_t type = 1; std::vector ret1 = rrc->StringSplit(wantAgentInfo, ""); EXPECT_EQ(ret1.size(), 2); - rrc->RecoverWantAgent(wantAgentInfo, type); + rrc->DeserializeWantAgent(wantAgentInfo, type); } /** @@ -1499,7 +1400,7 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00005, Function | SmallTest | Lev uint8_t type = 2; std::vector ret1 = rrc->StringSplit(wantAgentInfo, ""); EXPECT_EQ(ret1.size(), 2); - rrc->RecoverWantAgent(wantAgentInfo, type); + rrc->DeserializeWantAgent(wantAgentInfo, type); } /** @@ -1515,7 +1416,7 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00006, Function | SmallTest | Lev uint8_t type = 0; std::vector ret1 = rrc->StringSplit(wantAgentInfo, ""); EXPECT_EQ(ret1.size(), 3); - rrc->RecoverWantAgent(wantAgentInfo, type); + rrc->DeserializeWantAgent(wantAgentInfo, type); } /** @@ -2017,23 +1918,23 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00007, Function | SmallTest | Lev { auto rrc = std::make_shared(); std::string jsonValue = ""; - rrc->RecoverWantAgent(jsonValue, 0); + rrc->DeserializeWantAgent(jsonValue, 0); EXPECT_EQ(rrc->GetWantAgentInfo()->abilityName, ""); jsonValue = R"({"pkgName":"com.example.myapplication","abilityName":"MainAbility","uri":"","parameters":""})"; - rrc->RecoverWantAgent(jsonValue, 1); + rrc->DeserializeWantAgent(jsonValue, 1); EXPECT_EQ(rrc->GetMaxScreenWantAgentInfo()->abilityName, "MainAbility"); jsonValue = R"(})"; - rrc->RecoverWantAgent(jsonValue, 1); + rrc->DeserializeWantAgent(jsonValue, 1); EXPECT_EQ(rrc->GetMaxScreenWantAgentInfo()->abilityName, "MainAbility"); jsonValue = R"({})"; - rrc->RecoverWantAgent(jsonValue, 1); + rrc->DeserializeWantAgent(jsonValue, 1); EXPECT_EQ(rrc->GetMaxScreenWantAgentInfo()->abilityName, "MainAbility"); jsonValue = "fawexcdvasdfwessdf"; - rrc->RecoverWantAgent(jsonValue, 1); + rrc->DeserializeWantAgent(jsonValue, 1); EXPECT_EQ(rrc->GetMaxScreenWantAgentInfo()->abilityName, "MainAbility"); } @@ -2067,59 +1968,6 @@ HWTEST_F(ReminderRequestTest, MarshallingWantParameters_00001, Function | SmallT EXPECT_EQ(params2.GetStringParam(key), value); } -/** - * @tc.name: AppendWantAgentValuesBucket_00001 - * @tc.desc: Test AppendWantAgentValuesBucket parameters. - * @tc.type: FUNC - * @tc.require: issue#I94VJT - */ -HWTEST_F(ReminderRequestTest, AppendWantAgentValuesBucket_00001, Function | SmallTest | Level1) -{ - sptr rrc = new ReminderRequestChild; - NativeRdb::ValuesBucket values; - ReminderRequest::AppendWantAgentValuesBucket(rrc, values); - - NativeRdb::ValueObject object; - values.GetObject(ReminderBaseTable::WANT_AGENT, object); - std::string result; - object.GetString(result); - EXPECT_NE(result.find("pkgName"), -1); - - values.GetObject(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, object); - object.GetString(result); - EXPECT_NE(result.find("pkgName"), -1); -} - -/** - * @tc.name: AppendWantAgentValuesBucket_00002 - * @tc.desc: Test AppendWantAgentValuesBucket parameters. - * @tc.type: FUNC - * @tc.require: issue#I94VJT - */ -HWTEST_F(ReminderRequestTest, AppendWantAgentValuesBucket_00002, Function | SmallTest | Level1) -{ - auto wantInfo = std::make_shared(); - wantInfo->pkgName = "test"; - auto maxWantInfo = std::make_shared(); - maxWantInfo->pkgName = "maxTest"; - - sptr rrc = new ReminderRequestChild; - rrc->SetWantAgentInfo(wantInfo); - rrc->SetMaxScreenWantAgentInfo(maxWantInfo); - NativeRdb::ValuesBucket values; - ReminderRequest::AppendWantAgentValuesBucket(rrc, values); - - NativeRdb::ValueObject object; - values.GetObject(ReminderBaseTable::WANT_AGENT, object); - std::string result; - object.GetString(result); - EXPECT_NE(result.find("test"), -1); - - values.GetObject(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, object); - object.GetString(result); - EXPECT_NE(result.find("maxTest"), -1); -} - /** * @tc.name: WantAgentStr_00001 * @tc.desc: Test want agent str parameters. @@ -2310,8 +2158,6 @@ HWTEST_F(ReminderRequestTest, InitCreatorUid_00001, Function | SmallTest | Level rrc->InitCreatorUid(-1); EXPECT_EQ(rrc->GetCreatorUid(), -1); - - EXPECT_EQ(ReminderRequest::GetAppIndex(20020152), 0); } } } diff --git a/frameworks/ans/test/unittest/reminder_request_timer_test.cpp b/frameworks/ans/test/unittest/reminder_request_timer_test.cpp index 66b7f588922169c27e6d49b84a79ef5d930bc391..ac6c583246e577b41d7bd79cba27de51dffdec3b 100644 --- a/frameworks/ans/test/unittest/reminder_request_timer_test.cpp +++ b/frameworks/ans/test/unittest/reminder_request_timer_test.cpp @@ -114,20 +114,5 @@ HWTEST_F(ReminderRequestTimerTest, ReadFromParcel_00100, Function | SmallTest | auto result = rrc->ReadFromParcel(parcel); EXPECT_EQ(result, false); } - -/** - * @tc.name: RecoverFromDb_00001 - * @tc.desc: Test RecoverFromDb parameters. - * @tc.type: FUNC - * @tc.require: issueI92BU9 - */ -HWTEST_F(ReminderRequestTimerTest, RecoverFromDb_00001, Function | SmallTest | Level1) -{ - auto rrc = std::make_shared(10); - std::shared_ptr resultSet = nullptr; - rrc->RecoverFromDb(resultSet); - uint64_t ret = rrc->GetInitInfo(); - EXPECT_EQ(ret, 0); -} } } \ No newline at end of file diff --git a/frameworks/ans/test/unittest/reminder_store_test.cpp b/frameworks/ans/test/unittest/reminder_store_test.cpp index 0687e8bf750430b19e384daf5a21c1e1701b1cea..53aa06669dcaf0075f692e546db1f0e432469d96 100644 --- a/frameworks/ans/test/unittest/reminder_store_test.cpp +++ b/frameworks/ans/test/unittest/reminder_store_test.cpp @@ -20,6 +20,9 @@ #include "reminder_store.h" #include "reminder_table.h" #include "reminder_table_old.h" +#include "reminder_request_alarm.h" +#include "reminder_request_calendar.h" +#include "reminder_request_timer.h" #undef private #undef protected #include "reminder_helper.h" @@ -46,6 +49,25 @@ public: ReminderHelper::CancelAllReminders(); NativeRdb::RdbHelper::DeleteRdbStore(ReminderStore::REMINDER_DB_DIR + ReminderStore::REMINDER_DB_NAME); } + + void InitStore(ReminderStore& store) + { + std::string dbConfig = ReminderStore::REMINDER_DB_DIR + "notification_test.db"; + NativeRdb::RdbStoreConfig config(dbConfig); + config.SetSecurityLevel(NativeRdb::SecurityLevel::S1); + { + ReminderStore::ReminderStoreDataCallBack rdbDataCallBack; + int32_t errCode = STATE_FAIL; + constexpr int32_t version = 7; + store.rdbStore_ = NativeRdb::RdbHelper::GetRdbStore(config, version, rdbDataCallBack, errCode); + } + } + + void ClearStore() + { + NativeRdb::RdbHelper::ClearCache(); + NativeRdb::RdbHelper::DeleteRdbStore(ReminderStore::REMINDER_DB_DIR + "notification_test.db"); + } static sptr bundleOption_; }; @@ -300,5 +322,315 @@ HWTEST_F(ReminderStoreTest, Delete_00005, Function | SmallTest | Level1) ret = reminderStore.Delete("com.example.simple", 100, -1); EXPECT_EQ(ret, -1); } + +/** + * @tc.name: ReminderStrategyTest_00001 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderTimerStrategyTest_00001, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + sptr reminder = new ReminderRequestTimer(); + reminder->reminderId_ = 999; + reminder->bundleName_ = "ReminderTimerStrategyTest_00001"; + reminder->userId_ = 998; + reminder->uid_ = 997; + reminder->isSystemApp_ = true; + reminder->reminderType_ = ReminderRequest::ReminderType::TIMER; + reminder->reminderTimeInMilli_ = 123456789; + reminder->triggerTimeInMilli_ = 987654321; + reminder->SetTimeInterval(100); + reminder->snoozeTimes_ = 10; + reminder->snoozeTimesDynamic_ = 9; + reminder->SetRingDuration(500); + reminder->isExpired_ = false; + reminder->state_ = 123; + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + timer->countDownTimeInSeconds_ = 10001; + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + EXPECT_EQ(reminder->bundleName_, each->bundleName_); + EXPECT_EQ(reminder->userId_, each->userId_); + EXPECT_EQ(reminder->uid_, each->uid_); + EXPECT_EQ(reminder->isSystemApp_, each->isSystemApp_); + EXPECT_EQ(reminder->reminderType_, each->reminderType_); + EXPECT_EQ(reminder->reminderTimeInMilli_, each->reminderTimeInMilli_); + EXPECT_EQ(reminder->triggerTimeInMilli_, each->triggerTimeInMilli_); + EXPECT_EQ(reminder->GetTimeInterval(), each->GetTimeInterval()); + EXPECT_EQ(reminder->snoozeTimes_, each->snoozeTimes_); + EXPECT_EQ(reminder->snoozeTimesDynamic_, each->snoozeTimesDynamic_); + EXPECT_EQ(reminder->GetRingDuration(), each->GetRingDuration()); + EXPECT_EQ(reminder->isExpired_, each->isExpired_); + EXPECT_EQ(reminder->state_, each->state_); + ReminderRequestTimer* timer1 = static_cast(each.GetRefPtr()); + EXPECT_EQ(timer1->countDownTimeInSeconds_, timer->countDownTimeInSeconds_); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} + +/** + * @tc.name: ReminderTimerStrategyTest_00002 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderTimerStrategyTest_00002, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + sptr reminder = new ReminderRequestTimer(); + reminder->reminderId_ = 999; + reminder->reminderType_ = ReminderRequest::ReminderType::TIMER; + reminder->slotType_ = static_cast(1); + reminder->snoozeSlotType_ = static_cast(1); + reminder->notificationId_ = 123; + reminder->title_ = "title_"; + reminder->content_ = "content_"; + reminder->snoozeContent_ = "snoozeContent_"; + reminder->expiredContent_ = "expiredContent_"; + reminder->tapDismissed_ = false; + reminder->autoDeletedTime_ = 666; + reminder->groupId_ = "groupId_"; + reminder->customRingUri_ = "customRingUri_"; + reminder->creatorBundleName_ = "creatorBundleName_"; + reminder->creatorUid_ = 101; + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + timer->countDownTimeInSeconds_ = 10001; + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + EXPECT_EQ(reminder->slotType_, each->slotType_); + EXPECT_EQ(reminder->snoozeSlotType_, each->snoozeSlotType_); + EXPECT_EQ(reminder->notificationId_, each->notificationId_); + EXPECT_EQ(reminder->title_, each->title_); + EXPECT_EQ(reminder->content_, each->content_); + EXPECT_EQ(reminder->snoozeContent_, each->snoozeContent_); + EXPECT_EQ(reminder->expiredContent_, each->expiredContent_); + EXPECT_EQ(reminder->tapDismissed_, each->tapDismissed_); + EXPECT_EQ(reminder->autoDeletedTime_, each->autoDeletedTime_); + EXPECT_EQ(reminder->groupId_, each->groupId_); + EXPECT_EQ(reminder->customRingUri_, each->customRingUri_); + EXPECT_EQ(reminder->creatorBundleName_, each->creatorBundleName_); + EXPECT_EQ(reminder->creatorUid_, each->creatorUid_); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} + +/** + * @tc.name: ReminderTimerStrategyTest_00003 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderTimerStrategyTest_00003, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + sptr reminder = new ReminderRequestTimer(); + reminder->reminderId_ = 999; + reminder->reminderType_ = ReminderRequest::ReminderType::TIMER; + reminder->customButtonUri_ = "customButtonUri_"; + if (reminder->wantAgentInfo_ == nullptr) { + reminder->InitServerObj(); + } + reminder->wantAgentInfo_->pkgName = "pkgName"; + reminder->wantAgentInfo_->abilityName = "abilityName"; + reminder->wantAgentInfo_->uri = "uri"; + reminder->maxScreenWantAgentInfo_->pkgName = "pkgName1"; + reminder->maxScreenWantAgentInfo_->abilityName = "abilityName1"; + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + timer->countDownTimeInSeconds_ = 10001; + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + EXPECT_EQ(reminder->customButtonUri_, each->customButtonUri_); + EXPECT_EQ(reminder->wantAgentInfo_->pkgName, each->wantAgentInfo_->pkgName); + EXPECT_EQ(reminder->wantAgentInfo_->abilityName, each->wantAgentInfo_->abilityName); + EXPECT_EQ(reminder->wantAgentInfo_->uri, each->wantAgentInfo_->uri); + EXPECT_EQ(reminder->maxScreenWantAgentInfo_->pkgName, each->maxScreenWantAgentInfo_->pkgName); + EXPECT_EQ(reminder->maxScreenWantAgentInfo_->abilityName, each->maxScreenWantAgentInfo_->abilityName); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} + +/** + * @tc.name: ReminderAlarmStrategyTest_00001 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderAlarmStrategyTest_00001, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + sptr reminder = new ReminderRequestAlarm(); + reminder->reminderId_ = 999; + reminder->reminderType_ = ReminderRequest::ReminderType::ALARM; + reminder->repeatDaysOfWeek_ = 55; + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + alarm->hour_ = 12; + alarm->minute_ = 30; + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + EXPECT_EQ(reminder->repeatDaysOfWeek_, each->repeatDaysOfWeek_); + ReminderRequestAlarm* alarm1 = static_cast(each.GetRefPtr()); + EXPECT_EQ(alarm->hour_, alarm1->hour_); + EXPECT_EQ(alarm->minute_, alarm1->minute_); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} + +/** + * @tc.name: ReminderCalendarStrategyTest_00001 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderCalendarStrategyTest_00001, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + time_t t; + (void)time(&t); // unit is seconds. + uint64_t ts = t * 1000; // ms + + sptr reminder = new ReminderRequestCalendar(); + reminder->reminderId_ = 999; + reminder->reminderType_ = ReminderRequest::ReminderType::CALENDAR; + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + calendar->firstDesignateYear_ = 2006; + calendar->firstDesignateMonth_ = 6; + calendar->firstDesignateDay_ = 6; + calendar->SetDateTime(ts); + calendar->SetEndDateTime(ts + 60 * 1000); + calendar->SetLastStartDateTime(ts + 10 * 1000); + calendar->repeatDay_ = 12; + calendar->repeatMonth_ = 13; + calendar->AddExcludeDate(ts); + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + ReminderRequestCalendar* calendar1 = static_cast(each.GetRefPtr()); + EXPECT_EQ(calendar1->firstDesignateYear_, calendar->firstDesignateYear_); + EXPECT_EQ(calendar1->firstDesignateMonth_, calendar->firstDesignateMonth_); + EXPECT_EQ(calendar1->firstDesignateDay_, calendar->firstDesignateDay_); + EXPECT_EQ(calendar1->repeatDay_, calendar->repeatDay_); + EXPECT_EQ(calendar1->repeatMonth_, calendar->repeatMonth_); + EXPECT_EQ(calendar1->GetDateTime(), calendar->GetDateTime()); + EXPECT_EQ(calendar1->GetEndDateTime(), calendar->GetEndDateTime()); + EXPECT_EQ(calendar1->GetLastStartDateTime(), calendar->GetLastStartDateTime()); + EXPECT_EQ(calendar1->SerializationExcludeDates(), calendar->SerializationExcludeDates()); + EXPECT_EQ(calendar1->SerializationRRule(), calendar->SerializationRRule()); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} + +/** + * @tc.name: ReminderCalendarStrategyTest_00002 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderCalendarStrategyTest_00002, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + time_t t; + (void)time(&t); // unit is seconds. + uint64_t ts = t * 1000; // ms + + sptr reminder = new ReminderRequestCalendar(); + reminder->reminderId_ = 999; + reminder->reminderType_ = ReminderRequest::ReminderType::CALENDAR; + reminder->repeatDaysOfWeek_ = 55; + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + calendar->SetDateTime(ts); + calendar->rruleWantAgentInfo_ = std::make_shared(); + calendar->rruleWantAgentInfo_->pkgName = "pkgName"; + calendar->rruleWantAgentInfo_->abilityName = "abilityName"; + calendar->rruleWantAgentInfo_->uri = "uri"; + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + EXPECT_EQ(reminder->repeatDaysOfWeek_, each->repeatDaysOfWeek_); + ReminderRequestCalendar* calendar1 = static_cast(each.GetRefPtr()); + EXPECT_EQ(calendar1->GetDateTime(), calendar->GetDateTime()); + EXPECT_EQ(calendar1->GetEndDateTime(), calendar->GetDateTime()); + EXPECT_EQ(calendar1->GetLastStartDateTime(), calendar->GetDateTime()); + EXPECT_EQ(calendar1->SerializationRRule(), calendar->SerializationRRule()); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} } } \ No newline at end of file diff --git a/frameworks/cj/ffi/include/inner_errors.h b/frameworks/cj/ffi/include/inner_errors.h index bb9b164c9b93ea4b92b330204af960942c5ccb96..c613aa83afdc4fb23669b806f6cd3f8573f74723 100644 --- a/frameworks/cj/ffi/include/inner_errors.h +++ b/frameworks/cj/ffi/include/inner_errors.h @@ -107,6 +107,7 @@ enum ErrorCode : uint32_t { ERR_ANS_EXPIRED_NOTIFICATION, ERR_ANS_PUSH_CHECK_NETWORK_UNREACHABLE, ERR_ANS_PUSH_CHECK_EXTRAINFO_INVALID, + ERR_ANS_NO_PROFILE_TEMPLATE, }; // Common error code const uint32_t ERROR_PERMISSION_DENIED = 201; // No permission to call the interface. @@ -132,6 +133,8 @@ const int32_t ERROR_DIALOG_IS_POPPING = 1600013; // A notification const int32_t ERROR_NO_RIGHT = 1600014; // No permission. const int32_t ERROR_REPEAT_SET = 1600015; // Repeat create or end. const int32_t ERROR_EXPIRED_NOTIFICATION = 1600016; // Low update version. +const int32_t ERROR_SETTING_WINDOW_EXIST = 1600018; // The notification settings window is already displayed. +const int32_t ERROR_NO_PROFILE_TEMPLATE = 1600019; // Not exit noNotDisturb profile template. const int32_t ERROR_NETWORK_UNREACHABLE = 2300007; // Network unreachable. const int32_t ERROR_BUNDLE_NOT_FOUND = 17700001; // The specified bundle name was not found. diff --git a/frameworks/core/common/include/ans_const_define.h b/frameworks/core/common/include/ans_const_define.h index 0bb0d7b785b1e0984df211d6147d70e68014cfc1..f58eea322242e3ac9772ecd337315b1ca57af860 100644 --- a/frameworks/core/common/include/ans_const_define.h +++ b/frameworks/core/common/include/ans_const_define.h @@ -27,8 +27,11 @@ namespace Notification { // Max active notification number constexpr size_t MAX_ACTIVE_NUM = 1000; constexpr uint32_t MAX_ACTIVE_NUM_PERAPP = 100; -constexpr uint32_t MAX_ACTIVE_NUM_PERSECOND = 10; -constexpr uint32_t MAX_UPDATE_NUM_PERSECOND = 20; +constexpr uint32_t MAX_CREATE_NUM_PERSECOND = 15; +constexpr uint32_t MAX_UPDATE_NUM_PERSECOND = 30; +constexpr uint32_t MAX_CREATE_NUM_PERSECOND_PERAPP = 10; +constexpr uint32_t MAX_UPDATE_NUM_PERSECOND_PERAPP = 20; +constexpr std::chrono::seconds SINGLE_APP_FLOW_CONTRL_EXPIRE_TIME = std::chrono::seconds(1); constexpr size_t MAX_SLOT_NUM = 5; constexpr uint32_t MAX_ICON_SIZE = 192 * 1024; constexpr uint32_t MAX_PICTURE_SIZE = 2 * 1024 * 1024; @@ -43,6 +46,7 @@ constexpr int32_t MAX_STATUS_VECTOR_NUM = 1000; constexpr uint32_t MAX_CANCELED_PARCELABLE_VECTOR_NUM = 200; constexpr int32_t DEFAULT_UID = 0; +constexpr int32_t INVALID_PROFILE_ID = -1; constexpr int32_t SUBSCRIBE_USER_INIT = -1; constexpr int32_t SUBSCRIBE_USER_ALL = -2; constexpr int32_t DEFAULT_USER_ID = 100; diff --git a/frameworks/core/common/include/ans_convert_enum.h b/frameworks/core/common/include/ans_convert_enum.h index 3c54fc5b1867a61dff4fcc9292e4b913d96dd449..10b906991b9b2c9e5112c5334f42419120489aaf 100644 --- a/frameworks/core/common/include/ans_convert_enum.h +++ b/frameworks/core/common/include/ans_convert_enum.h @@ -84,6 +84,7 @@ enum class RemoveReason { TRIGGER_AUTO_DELETE_REASON_DELETE = 27, PACKAGE_REMOVE_REASON_DELETE = 28, SLOT_ENABLED_REASON_DELETE = 29, + RECOVER_LIVE_VIEW_DELETE = 30, APP_CANCEL_REASON_OTHER = 100, }; @@ -196,24 +197,6 @@ public: */ static bool ReasonCToJS(const int32_t &inType, int32_t &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 void ReasonCToJSExt(const int32_t &inType, int32_t &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 void ReasonCToJSSecondExt(const int32_t &inType, int32_t &outType); - /** * @brief Converts do-not-disturb type from js to native * diff --git a/frameworks/core/common/include/ans_inner_errors.h b/frameworks/core/common/include/ans_inner_errors.h index ef824ec31485a51469dd41a07fbc043a83fe8d22..96884d8f7a57a86fec58ec9d84ee1af59b55aa42 100644 --- a/frameworks/core/common/include/ans_inner_errors.h +++ b/frameworks/core/common/include/ans_inner_errors.h @@ -90,7 +90,10 @@ enum ErrorCode : uint32_t { ERR_ANS_PUSH_CHECK_EXTRAINFO_INVALID, ERR_ANS_OVER_MAX_UPDATE_PERSECOND, ERR_ANS_DUPLICATE_MSG, - ERR_ANS_NO_AGENT_SETTING + ERR_ANS_NO_AGENT_SETTING, + ERR_ANS_ENCRYPT_FAIL, + ERR_ANS_DECRYPT_FAIL, + ERR_ANS_NO_PROFILE_TEMPLATE }; enum ReminderErrorCode : uint32_t { @@ -105,14 +108,14 @@ enum ReminderErrorCode : uint32_t { }; static std::map reminderErrCodeMsgMap = { - { ERR_REMINDER_PERMISSION_DENIED, "BussinessError 201: Permission denied." }, - { ERR_REMINDER_INVALID_PARAM, "BussinessError 401: Parameter error." }, - { ERR_REMINDER_NOTIFICATION_NOT_ENABLE, "BussinessError 1700001: Notification not enable." }, - { ERR_REMINDER_NUMBER_OVERLOAD, "BussinessError 1700002: The number of reminders exceeds the limit." }, - { ERR_REMINDER_NOT_EXIST, "BussinessError 1700003: The reminder not exist." }, - { ERR_REMINDER_PACKAGE_NOT_EXIST, "BussinessError 1700004: The package name not exist." }, - { ERR_REMINDER_CALLER_TOKEN_INVALID, "BussinessError 1700005: The caller token invalid." }, - { ERR_REMINDER_DATA_SHARE_PERMISSION_DENIED, "BussinessError 1700006: The data share permission denied." } + { ERR_REMINDER_PERMISSION_DENIED, "Permission denied." }, + { ERR_REMINDER_INVALID_PARAM, "Parameter error." }, + { ERR_REMINDER_NOTIFICATION_NOT_ENABLE, "Notification not enable." }, + { ERR_REMINDER_NUMBER_OVERLOAD, "The number of reminders exceeds the limit." }, + { ERR_REMINDER_NOT_EXIST, "The reminder not exist." }, + { ERR_REMINDER_PACKAGE_NOT_EXIST, "The package name not exist." }, + { ERR_REMINDER_CALLER_TOKEN_INVALID, "The caller token invalid." }, + { ERR_REMINDER_DATA_SHARE_PERMISSION_DENIED, "The data share permission denied." } }; // Notification error msg @@ -145,6 +148,8 @@ const int32_t ERROR_NO_RIGHT = 1600014; // No permission. const int32_t ERROR_REPEAT_SET = 1600015; // Repeat create or end. const int32_t ERROR_EXPIRED_NOTIFICATION = 1600016; // Low update version. const int32_t ERROR_NO_AGENT_SETTING = 1600017; // No corresponding agent relationship configuration. +const int32_t ERROR_SETTING_WINDOW_EXIST = 1600018; // The notification settings window is already displayed. +const int32_t ERROR_NO_PROFILE_TEMPLATE = 1600019; // Not exit noNotDisturb profile template. const int32_t ERROR_NETWORK_UNREACHABLE = 2300007; // Network unreachable. const int32_t ERROR_BUNDLE_NOT_FOUND = 17700001; // The specified bundle name was not found. } // namespace Notification diff --git a/frameworks/core/common/src/ans_convert_enum.cpp b/frameworks/core/common/src/ans_convert_enum.cpp index 594e0edee00281ee771776d211ff1b9c1b537356..a4dac36084daa484ee1778d834f9d379d262e377 100644 --- a/frameworks/core/common/src/ans_convert_enum.cpp +++ b/frameworks/core/common/src/ans_convert_enum.cpp @@ -258,16 +258,6 @@ bool AnsEnumUtil::ReasonCToJS(const int &inType, int &outType) case NotificationConstant::FLOW_CONTROL_REASON_DELETE: outType = static_cast(RemoveReason::FLOW_CONTROL_REASON_DELETE); break; - default: - ReasonCToJSExt(inType, outType); - break; - } - return true; -} - -void AnsEnumUtil::ReasonCToJSExt(const int &inType, int &outType) -{ - switch (inType) { case NotificationConstant::DISABLE_SLOT_REASON_DELETE: outType = static_cast(RemoveReason::DISABLE_SLOT_REASON_DELETE); break; @@ -301,15 +291,6 @@ void AnsEnumUtil::ReasonCToJSExt(const int &inType, int &outType) case NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE: outType = static_cast(RemoveReason::TRIGGER_FOUR_HOUR_REASON_DELETE); break; - default: - ReasonCToJSSecondExt(inType, outType); - break; - } -} - -void AnsEnumUtil::ReasonCToJSSecondExt(const int &inType, int &outType) -{ - switch (inType) { case NotificationConstant::TRIGGER_TEN_MINUTES_REASON_DELETE: outType = static_cast(RemoveReason::TRIGGER_TEN_MINUTES_REASON_DELETE); break; @@ -334,11 +315,15 @@ void AnsEnumUtil::ReasonCToJSSecondExt(const int &inType, int &outType) case NotificationConstant::APP_CANCEL_REASON_OTHER: outType = static_cast(RemoveReason::APP_CANCEL_REASON_OTHER); break; + case NotificationConstant::RECOVER_LIVE_VIEW_DELETE: + outType = static_cast(RemoveReason::RECOVER_LIVE_VIEW_DELETE); + break; default: outType = static_cast(RemoveReason::APP_CANCEL_REASON_OTHER); ANS_LOGW("Reason %{public}d is an invalid value", inType); break; } + return true; } bool AnsEnumUtil::DoNotDisturbTypeJSToC(const DoNotDisturbType &inType, NotificationConstant::DoNotDisturbType &outType) diff --git a/frameworks/core/include/ans_image_util.h b/frameworks/core/include/ans_image_util.h index d7068e608ef69ada72fda87f680c165ddb633568..5b1bbe86ab22fc304887dc685946d511ddbe15a8 100644 --- a/frameworks/core/include/ans_image_util.h +++ b/frameworks/core/include/ans_image_util.h @@ -28,6 +28,7 @@ public: static const uint8_t SHIFT_FOUR; static const uint8_t NUM_TEN; static const size_t TWO_TIMES; + static const uint32_t DEFAULT_SIZE; /** * @brief Packs an image to a string. @@ -45,7 +46,8 @@ public: * @param pixelMapStr Indicates the string of image. * @return Returns an image object. */ - static std::shared_ptr UnPackImage(const std::string &pixelMapStr); + static std::shared_ptr UnPackImage(const std::string &pixelMapStr, + const std::string &format = IMAGE_FORMAT_PNG); /** * @brief Packs an image to a file. diff --git a/frameworks/core/include/ans_manager_death_recipient.h b/frameworks/core/include/ans_manager_death_recipient.h index 44a654662c02040e1c83181f0af7b8928790339c..4d48d311da8283f584bbfbca8b3c05f3f0bf98cd 100644 --- a/frameworks/core/include/ans_manager_death_recipient.h +++ b/frameworks/core/include/ans_manager_death_recipient.h @@ -27,8 +27,6 @@ public: ~AnsManagerDeathRecipient() = default; void SubscribeSAManager(); - - bool GetIsSubscribeSAManager(); private: class SystemAbilityStatusChangeListener : public SystemAbilityStatusChangeStub { public: @@ -36,11 +34,8 @@ private: ~SystemAbilityStatusChangeListener() = default; void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; - - private: - bool isSAOffline = false; }; - + std::mutex mutex_; sptr statusChangeListener_ = nullptr; }; } // namespace Notification diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 62296e57f7ca083707db4e241eac20713a83f49b..4a00c8c45ea290ca050481d7465fc0642308028c 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -54,6 +54,17 @@ public: */ virtual ErrCode Publish(const std::string &label, const sptr ¬ification) = 0; + /** + * @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. + * + * @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. + */ + virtual ErrCode PublishNotificationForIndirectProxy(const sptr ¬ification) = 0; + /** * @brief Cancels a published notification matching the specified label and notificationId. * @@ -509,6 +520,13 @@ public: virtual ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) = 0; + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + virtual ErrCode RemoveEnableNotificationDialog() = 0; + /** * @brief Checks whether notifications are allowed for a specific bundle. * @@ -558,6 +576,14 @@ public: */ virtual ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) = 0; + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + virtual ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) = 0; + /** * @brief Cancel notifications according to group. * @@ -932,6 +958,14 @@ public: */ virtual ErrCode SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status) = 0; + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + virtual ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) = 0; #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** * @brief Register Swing Callback. @@ -941,6 +975,14 @@ public: */ virtual ErrCode RegisterSwingCallback(const sptr& swingCallback) = 0; #endif + + /** + * @brief Update Notification Timer by uid. + * + * @param uid uid. + * @return Returns Update result. + */ + virtual ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) = 0; }; } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 006c4efa23f99d95ae4834e40912f3680e2be165..fe7bfba0fe82f720030f503bb16131b5a2f91800 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -42,6 +42,17 @@ public: */ ErrCode Publish(const std::string &label, const sptr ¬ification) override; + /** + * @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. + * + * @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 PublishNotificationForIndirectProxy(const sptr ¬ification) override; + /** * @brief Cancels a published notification matching the specified label and notificationId. * @@ -497,6 +508,13 @@ public: ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog() override; + /** * @brief Checks whether notifications are allowed for a specific bundle. * @@ -546,6 +564,14 @@ public: */ ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override; + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) override; + /** * @brief Cancel notifications according to group. * @@ -920,6 +946,15 @@ public: */ ErrCode SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status) override; + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) override; + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** * @brief Register Swing Callback. @@ -930,6 +965,14 @@ public: ErrCode RegisterSwingCallback(const sptr &swingCallback) override; #endif + /** + * @brief Update Notification Timer by uid. + * + * @param uid uid. + * @return Returns Update result. + */ + ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) override; + private: ErrCode InnerTransact(NotificationInterfaceCode code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 4ac817c138d3715d8ae93ef01a20ea716df3a9cb..0444b7ec2f0e56825aa8ec0394dc94e9e20fe603 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -55,6 +55,17 @@ public: */ virtual ErrCode Publish(const std::string &label, const sptr ¬ification) override; + /** + * @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. + * + * @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. + */ + virtual ErrCode PublishNotificationForIndirectProxy(const sptr ¬ification) override; + /** * @brief Cancels a published notification matching the specified label and notificationId. * @@ -349,7 +360,7 @@ public: */ virtual ErrCode GetSlotsByBundle( const sptr &bundleOption, std::vector> &slots) override; - + /** * @brief Get the specified slot corresponding to the bundle. * @@ -448,7 +459,7 @@ public: */ virtual ErrCode Subscribe( const sptr &subscriber, const sptr &info) override; - + /** * @brief Subscribes notifications self. * @@ -496,6 +507,13 @@ public: ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog() override; + /** * @brief Checks whether notifications are allowed for a specific bundle. * @@ -546,6 +564,14 @@ public: */ virtual ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override; + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + virtual ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) override; + /** * @brief Cancel notifications according to group. * @@ -890,7 +916,7 @@ public: */ ErrCode IsDistributedEnabledByBundle( const sptr &bundleOption, const std::string &deviceType, bool &enabled) override; - + /** * @brief Get Enable smartphone to collaborate with other devices for intelligent reminders * @@ -922,6 +948,15 @@ public: */ virtual ErrCode SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status) override; + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile object. + * @return Returns ERR_OK on success, others on failure. + */ + virtual ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) override; + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** * @brief Register Swing Callback. @@ -931,9 +966,18 @@ public: */ ErrCode RegisterSwingCallback(const sptr& swingCallback) override; #endif + + /** + * @brief Update Notification Timer by uid. + * + * @param uid uid. + * @return Returns Update result. + */ + virtual ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) override; private: ErrCode HandlePublish(MessageParcel &data, MessageParcel &reply); + ErrCode HandlePublishNotificationForIndirectProxy(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancel(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelAll(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelAsBundle(MessageParcel &data, MessageParcel &reply); @@ -979,6 +1023,7 @@ private: ErrCode HandleIsAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsAllowedNotifySelf(MessageParcel &data, MessageParcel &reply); ErrCode HandleCanPopEnableNotificationDialog(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveEnableNotificationDialog(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsDistributedEnabled(MessageParcel &data, MessageParcel &reply); ErrCode HandleEnableDistributed(MessageParcel &data, MessageParcel &reply); @@ -991,6 +1036,7 @@ private: ErrCode HandleSetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply); ErrCode HandleDoesSupportDoNotDisturbMode(MessageParcel &data, MessageParcel &reply); + ErrCode HandleIsNeedSilentInDoNotDisturbMode(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetDeviceRemindType(MessageParcel &data, MessageParcel &reply); ErrCode HandlePublishContinuousTaskNotification(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelContinuousTaskNotification(MessageParcel &data, MessageParcel &reply); @@ -1031,9 +1077,11 @@ private: ErrCode HandleAddDoNotDisturbProfiles(MessageParcel &data, MessageParcel &reply); ErrCode HandleRemoveDoNotDisturbProfiles(MessageParcel &data, MessageParcel &reply); ErrCode HandleSetTargetDeviceStatus(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetDoNotDisturbProfile(MessageParcel &data, MessageParcel &reply); #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode HandleRegisterSwingCallback(MessageParcel &data, MessageParcel &reply); #endif + ErrCode HandleUpdateNotificationTimerByUid(MessageParcel &data, MessageParcel &reply); template bool WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result) { diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index 691c086421ce1e54805b25f46fd32ef862c29472..c2f88174453527586f611d1721e640a96eaefa85 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -17,10 +17,12 @@ #define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_NOTIFICATION_H #include +#include #include "ans_dialog_host_client.h" #include "ans_manager_death_recipient.h" #include "ans_manager_interface.h" +#include "ans_subscriber_listener.h" #include "notification_subscriber.h" #include "notification_local_live_view_subscriber.h" #include "want_params.h" @@ -147,6 +149,17 @@ public: */ ErrCode PublishNotification(const std::string &label, const NotificationRequest &request); + /** + * @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. + * + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns publish notification result. + */ + ErrCode PublishNotificationForIndirectProxy(const NotificationRequest &request); + /** * @brief Cancels a published notification. * @@ -168,7 +181,7 @@ public: /** * @brief Cancels all the published notifications. - * @note To cancel a specified notification, see CancelNotification(int_32). + * @note To cancel a specified notification, see CancelNotification(int32_t). * * @return Returns cancel all notifications result. */ @@ -299,6 +312,13 @@ public: ErrCode CanPopEnableNotificationDialog(sptr &hostClient, bool &canPop, std::string &bundleName); + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog(); + /** * @brief Allows the current application to publish notifications on a specified device. * @@ -336,26 +356,57 @@ public: * notification. To subscribe to notifications published only by specified sources, for example, notifications from * certain applications, call the {SubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} * method. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotification(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns subscribe notification result. */ ErrCode SubscribeNotification(const NotificationSubscriber &subscriber); + /** + * @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. + * After the notification is published, subscribers that meet the filter criteria can receive the + * notification. To subscribe to notifications published only by specified sources, for example, notifications from + * certain applications, call the {SubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} + * method. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns subscribe notification result. + */ + ErrCode SubscribeNotification(const std::shared_ptr &subscriber); + /** * @brief Subscribes to notifications from the appliaction self. * @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. * After the notification is published, subscribers that meet the filter criteria can receive the * notification. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotificationSelf(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns subscribe notification result. */ ErrCode SubscribeNotificationSelf(const NotificationSubscriber &subscriber); + /** + * @brief Subscribes to notifications from the appliaction self. + * @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. + * After the notification is published, subscribers that meet the filter criteria can receive the + * notification. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns subscribe notification result. + */ + ErrCode SubscribeNotificationSelf(const std::shared_ptr &subscriber); + /** * @brief Subscribes liveView notification. This method can be called only by applications * with required system permissions. @@ -379,7 +430,9 @@ public: * After the notification is published, subscribers that meet the filter criteria can receive the * notification. To subscribe to and receive all notifications, call the * {SubscribeNotification(NotificationSubscriber)} method. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotification(const std::shared_ptr &subscriber, + * const std::shared_ptr &subscribeInfo)'. * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. * For details, see {NotificationSubscriber}. * @param subscribeInfo Indicates the filters for specified notification sources, including application name, @@ -388,6 +441,26 @@ public: */ ErrCode SubscribeNotification( const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo); + + /** + * @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}. + * 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. + * After the notification is published, subscribers that meet the filter criteria can receive the + * notification. To subscribe to and receive all notifications, call the + * {SubscribeNotification(NotificationSubscriber)} method. + * + * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. + * For details, see {NotificationSubscriber}. + * @param subscribeInfo Indicates the filters for specified notification sources, including application name, + * user ID, or device name. This parameter is optional. + * @return Returns subscribe notification result. + */ + ErrCode SubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo); /** * @brief Unsubscribes from all notifications. This method can be called only by applications with required @@ -399,18 +472,39 @@ public: * To unsubscribe from notifications published only by specified sources, for example, * notifications from certain applications, call the * {UnSubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. - * + * @deprecated This function is deprecated, + * use 'UnSubscribeNotification(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns unsubscribe notification result. */ ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber); + /** + * @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 + * to receive a notification any longer, unsubscribe from that notification using this method. + * You can unsubscribe from only those notifications that your application has subscribed to. + * To unsubscribe from notifications published only by specified sources, for example, + * notifications from certain applications, call the + * {UnSubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + ErrCode UnSubscribeNotification(const std::shared_ptr &subscriber); + /** * @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. * + * @deprecated This function is deprecated, + * use 'UnSubscribeNotification(const std::shared_ptr &subscriber, + * const std::shared_ptr &subscribeInfo)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @param subscribeInfo Indicates the filters for , including application name, @@ -419,6 +513,20 @@ public: */ ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo); + /** + * @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. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @param subscribeInfo Indicates the filters for , including application name, + * user ID, or device name. This parameter is optional. + * @return Returns unsubscribe notification result. + */ + ErrCode UnSubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo); + /** * @brief Trigger the local live view after the button has been clicked. * @note Your application must have platform signature to use this method. @@ -685,6 +793,14 @@ public: */ ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType); + /** * @brief Checks if the device supports distributed notification. * @@ -1079,6 +1195,27 @@ public: ErrCode RegisterSwingCallback(const std::function swingCbFunc); #endif + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile); + + /** + * @brief Ans service died, OnRemoteDied called. + */ + void OnServiceDied(); + + /** + * @brief Update Notification Timer by uid + * + * @param uid uid. + * @return Returns Update result. + */ + ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused); private: /** * @brief Gets Ans Manager proxy. @@ -1121,10 +1258,12 @@ private: bool IsValidTemplate(const NotificationRequest &request) const; bool IsValidDelayTime(const NotificationRequest &request) const; + void CreateSubscribeListener(const std::shared_ptr &subscriber, + sptr &listener); private: - std::mutex mutex_; - sptr ansManagerProxy_; + std::mutex subscriberMutex_; + std::map, sptr> subscribers_; #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED sptr swingCallBackStub_; #endif diff --git a/frameworks/core/include/ans_subscriber_listener.h b/frameworks/core/include/ans_subscriber_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..2ecd8bf32bde10a0f1d2287c9ee416692fd7bba7 --- /dev/null +++ b/frameworks/core/include/ans_subscriber_listener.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_CORE_NOTIFICATION_SUBSCRIBER_LISTENER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_CORE_NOTIFICATION_SUBSCRIBER_LISTENER_H + +#include "ans_manager_interface.h" +#include "ans_subscriber_stub.h" +#include "notification_request.h" +#include "notification_sorting.h" +#include "notification_sorting_map.h" +#include "notification_subscriber.h" + +namespace OHOS { +namespace Notification { +class SubscriberListener final : public AnsSubscriberStub { +public: + SubscriberListener(const std::shared_ptr &subscriber); + ~SubscriberListener(); + + void OnConnected() override; + + void OnDisconnected() override; + + void OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) override; + + void OnConsumedList(const std::vector> ¬ifications, + const sptr ¬ificationMap) override; + + void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, + int32_t deleteReason) override; + + void OnCanceledList(const std::vector> ¬ifications, + const sptr ¬ificationMap, int32_t deleteReason) override; + + void OnBatchCanceled(const std::vector> ¬ifications, + const sptr ¬ificationMap, int32_t deleteReason); + + void OnUpdated(const sptr ¬ificationMap) override; + + void OnDoNotDisturbDateChange(const sptr &date) override; + + void OnEnabledNotificationChanged(const sptr &callbackData) override; + + void OnBadgeChanged(const sptr &badgeData) override; + + void OnBadgeEnabledChanged(const sptr &callbackData) override; + +public: + std::weak_ptr subscriber_; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_CORE_NOTIFICATION_SUBSCRIBER_LISTENER_H \ No newline at end of file diff --git a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h index aa2df9e2be97fdba0135d0ac3128620d81b7a933..fc620668a10c95012a4736cd5e04e30abc1e5db4 100644 --- a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h +++ b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h @@ -25,6 +25,7 @@ namespace Notification { // ans_manager_interface PUBLISH_NOTIFICATION = FIRST_CALL_TRANSACTION, PUBLISH_NOTIFICATION_TO_DEVICE, // Obsolete + PUBLISH_NOTIFICATION_INDIRECTPROXY, CANCEL_NOTIFICATION, CANCEL_ALL_NOTIFICATIONS, CANCEL_AS_BUNDLE_OPTION, @@ -76,10 +77,12 @@ namespace Notification { IS_ALLOWED_NOTIFY, IS_ALLOWED_NOTIFY_SELF, CAN_POP_ENABLE_NOTIFICATION_DIALOG, + REMOVE_ENABLE_NOTIFICATION_DIALOG, IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, SET_DO_NOT_DISTURB_DATE, GET_DO_NOT_DISTURB_DATE, DOES_SUPPORT_DO_NOT_DISTURB_MODE, + IS_NEED_SILENT_IN_DO_NOT_DISTURB_MODE, CANCEL_GROUP, REMOVE_GROUP_BY_BUNDLE, IS_DISTRIBUTED_ENABLED, @@ -147,6 +150,8 @@ namespace Notification { ADD_EXCLUDE_DATE_REMINDER, DEL_EXCLUDE_DATES_REMINDER, GET_EXCLUDE_DATES_REMINDER, + GET_DONOTDISTURB_PROFILE, + UPDATE_NOTIFICATION_TIMER, }; } } diff --git a/frameworks/core/src/ans_image_util.cpp b/frameworks/core/src/ans_image_util.cpp index f2fe05f4efb493d939fec33732aa4b8568ac4309..e3929d1dd55dec5463888db06b0af422e31b1c1e 100644 --- a/frameworks/core/src/ans_image_util.cpp +++ b/frameworks/core/src/ans_image_util.cpp @@ -24,6 +24,7 @@ const uint8_t AnsImageUtil::IMAGE_QUALITY {100}; const uint8_t AnsImageUtil::SHIFT_FOUR {4}; const uint8_t AnsImageUtil::NUM_TEN {10}; const size_t AnsImageUtil::TWO_TIMES {2}; +const uint32_t AnsImageUtil::DEFAULT_SIZE {25 * 1024 * 1024}; std::string AnsImageUtil::PackImage(const std::shared_ptr &pixelMap, const std::string &format) { @@ -47,6 +48,9 @@ std::string AnsImageUtil::PackImage(const std::shared_ptr &pixe auto size = static_cast(pixelMap->GetByteCount()); ANS_LOGD("size of pixelMap : %{public}u", size); + if (size < DEFAULT_SIZE) { + size = DEFAULT_SIZE; + } auto pbuf = new (std::nothrow) uint8_t [size]; if (pbuf == nullptr) { ANS_LOGE("create buffer failed"); @@ -66,7 +70,7 @@ std::string AnsImageUtil::PackImage(const std::shared_ptr &pixe return BinToHex(pixelMapStr); } -std::shared_ptr AnsImageUtil::UnPackImage(const std::string &pixelMapStr) +std::shared_ptr AnsImageUtil::UnPackImage(const std::string &pixelMapStr, const std::string &format) { if (pixelMapStr.empty()) { return {}; @@ -76,6 +80,7 @@ std::shared_ptr AnsImageUtil::UnPackImage(const std::string &pi uint32_t errorCode {0}; Media::SourceOptions opts; + opts.formatHint = format; auto imageSource = Media::ImageSource::CreateImageSource( reinterpret_cast(binStr.data()), static_cast(binStr.length()), diff --git a/frameworks/core/src/ans_manager_death_recipient.cpp b/frameworks/core/src/ans_manager_death_recipient.cpp index fab6f2f06147795d67192b5c347ae5551ed101d6..9048f8a587923328dc37815acd3aa4ef613ab50a 100644 --- a/frameworks/core/src/ans_manager_death_recipient.cpp +++ b/frameworks/core/src/ans_manager_death_recipient.cpp @@ -24,6 +24,10 @@ namespace OHOS { namespace Notification { void AnsManagerDeathRecipient::SubscribeSAManager() { + std::lock_guard lock(mutex_); + if (statusChangeListener_ != nullptr) { + return; + } auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); statusChangeListener_ = new (std::nothrow) AnsManagerDeathRecipient::SystemAbilityStatusChangeListener(); if (samgrProxy == nullptr || statusChangeListener_ == nullptr) { @@ -37,29 +41,14 @@ void AnsManagerDeathRecipient::SubscribeSAManager() statusChangeListener_ = nullptr; } } - -bool AnsManagerDeathRecipient::GetIsSubscribeSAManager() -{ - return statusChangeListener_ != nullptr; -} - void AnsManagerDeathRecipient::SystemAbilityStatusChangeListener::OnAddSystemAbility( - int32_t systemAbilityId, const std::string& deviceId) -{ - if (!isSAOffline) { - return; - } - ANS_LOGI("Ans manager service restore, try to reconnect"); - DelayedSingleton::GetInstance()->Reconnect(); - isSAOffline = false; -} + int32_t systemAbilityId, const std::string& deviceId) {} void AnsManagerDeathRecipient::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( int32_t systemAbilityId, const std::string& deviceId) { ANS_LOGI("Ans manager service died"); - DelayedSingleton::GetInstance()->ResetAnsManagerProxy(); - isSAOffline = true; + DelayedSingleton::GetInstance()->OnServiceDied(); } } // namespace Notification -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/core/src/ans_manager_proxy.cpp b/frameworks/core/src/ans_manager_proxy.cpp index 1d185722d77c074b807c96744429c528da6560c9..cb020271355d18db3f405f50ede037c97abe0935 100644 --- a/frameworks/core/src/ans_manager_proxy.cpp +++ b/frameworks/core/src/ans_manager_proxy.cpp @@ -78,6 +78,45 @@ ErrCode AnsManagerProxy::Publish(const std::string &label, const sptr ¬ification) +{ + if (notification == nullptr) { + ANS_LOGE("[PublishNotificationForIndirectProxy] fail: notification is null ptr."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (notification->IsCommonLiveView()) { + if (!data.SetMaxCapacity(NotificationConstant::NOTIFICATION_MAX_LIVE_VIEW_SIZE)) { + return ERR_ANS_PARCELABLE_FAILED; + } + } + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[PublishNotificationForIndirectProxy] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(notification)) { + ANS_LOGE("[PublishNotificationForIndirectProxy] fail: write notification parcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::PUBLISH_NOTIFICATION_INDIRECTPROXY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[PublishNotificationForIndirectProxy] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[PublishNotificationForIndirectProxy] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + ErrCode AnsManagerProxy::Cancel(int32_t notificationId, const std::string &label, int32_t instanceKey) { MessageParcel data; @@ -328,6 +367,10 @@ ErrCode AnsManagerProxy::GetAllActiveNotifications(std::vector &bundleOption, bool &allowed) { if (bundleOption == nullptr) { @@ -2197,5 +2262,34 @@ ErrCode AnsManagerProxy::RegisterSwingCallback(const sptr &swingC return result; } #endif + +ErrCode AnsManagerProxy::UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(uid)) { + ANS_LOGE("write uid failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(isPaused)) { + ANS_LOGE("write isPaused failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = { MessageOption::TF_ASYNC }; + ErrCode result = InnerTransact(NotificationInterfaceCode::UPDATE_NOTIFICATION_TIMER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + return result; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/ans_manager_proxy_disturb.cpp b/frameworks/core/src/ans_manager_proxy_disturb.cpp index 16e141ade908590f3e5bf08c1fe5df1cffd8d790..b13921e81fefeea453917bc34aa3b05390984665 100644 --- a/frameworks/core/src/ans_manager_proxy_disturb.cpp +++ b/frameworks/core/src/ans_manager_proxy_disturb.cpp @@ -426,5 +426,80 @@ ErrCode AnsManagerProxy::IsSmartReminderEnabled(const std::string &deviceType, b return result; } + +ErrCode AnsManagerProxy::IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[IsNeedSilentInDoNotDisturbMode] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(phoneNumber)) { + ANS_LOGE("[IsNeedSilentInDoNotDisturbMode] fail: write phoneNumber failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(callerType)) { + ANS_LOGE("[IsNeedSilentInDoNotDisturbMode] fail: write callerType failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_NEED_SILENT_IN_DO_NOT_DISTURB_MODE, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[IsNeedSilentInDoNotDisturbMode] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[IsNeedSilentInDoNotDisturbMode] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetDoNotDisturbProfile(int32_t id, sptr &profile) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("GetDoNotDisturbProfile write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(id)) { + ANS_LOGE("GetDoNotDisturbProfile write id failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_DONOTDISTURB_PROFILE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("GetDoNotDisturbProfile transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("GetDoNotDisturbProfile read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (result != ERR_OK) { + ANS_LOGE("GetDoNotDisturbProfile result failed %{public}d.", result); + return result; + } + + profile = reply.ReadParcelable(); + if (profile == nullptr) { + ANS_LOGE("GetDoNotDisturbProfile read data failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index b27515659d4314a88b781331a3cf41155c5093c9..f71bb65ea8a5e60bcf78112dcea99e72c7d30eae 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -47,6 +47,10 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandlePublish(data, reply); break; } + case static_cast(NotificationInterfaceCode::PUBLISH_NOTIFICATION_INDIRECTPROXY): { + result = HandlePublishNotificationForIndirectProxy(data, reply); + break; + } case static_cast(NotificationInterfaceCode::CANCEL_NOTIFICATION): { result = HandleCancel(data, reply); break; @@ -223,6 +227,10 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleCanPopEnableNotificationDialog(data, reply); break; } + case static_cast(NotificationInterfaceCode::REMOVE_ENABLE_NOTIFICATION_DIALOG): { + result = HandleRemoveEnableNotificationDialog(data, reply); + break; + } case static_cast(NotificationInterfaceCode::IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY): { result = HandleIsSpecialBundleAllowedNotify(data, reply); break; @@ -239,6 +247,10 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleDoesSupportDoNotDisturbMode(data, reply); break; } + case static_cast(NotificationInterfaceCode::IS_NEED_SILENT_IN_DO_NOT_DISTURB_MODE): { + result = HandleIsNeedSilentInDoNotDisturbMode(data, reply); + break; + } case static_cast(NotificationInterfaceCode::CANCEL_GROUP): { result = HandleCancelGroup(data, reply); break; @@ -441,6 +453,14 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleGetExcludeDates(data, reply); break; } + case static_cast(NotificationInterfaceCode::GET_DONOTDISTURB_PROFILE): { + result = HandleGetDoNotDisturbProfile(data, reply); + break; + } + case static_cast(NotificationInterfaceCode::UPDATE_NOTIFICATION_TIMER): { + result = HandleUpdateNotificationTimerByUid(data, reply); + break; + } default: { ANS_LOGE("[OnRemoteRequest] fail: unknown code!"); return IPCObjectStub::OnRemoteRequest(code, data, reply, flags); @@ -476,6 +496,22 @@ ErrCode AnsManagerStub::HandlePublish(MessageParcel &data, MessageParcel &reply) return ERR_OK; } +ErrCode AnsManagerStub::HandlePublishNotificationForIndirectProxy(MessageParcel &data, MessageParcel &reply) +{ + sptr notification = data.ReadParcelable(); + if (!notification) { + ANS_LOGE("[HandlePublishNotificationForIndirectProxy] fail: notification ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = PublishNotificationForIndirectProxy(notification); + if (!reply.WriteInt32(result)) { + ANS_LOGE("[HandlePublishNotificationForIndirectProxy] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleCancel(MessageParcel &data, MessageParcel &reply) { int32_t notificationId = 0; @@ -776,6 +812,10 @@ ErrCode AnsManagerStub::HandleGetAllActiveNotifications(MessageParcel &data, Mes { std::vector> notifications; ErrCode result = GetAllActiveNotifications(notifications); + + if (!reply.SetMaxCapacity(NotificationConstant::NOTIFICATION_MAX_LIVE_VIEW_SIZE)) { + return ERR_ANS_PARCELABLE_FAILED; + } if (!WriteParcelableVector(notifications, reply, result)) { ANS_LOGE("[HandleGetAllActiveNotifications] fail: write notifications failed"); return ERR_ANS_PARCELABLE_FAILED; @@ -1005,6 +1045,28 @@ ErrCode AnsManagerStub::HandleDoesSupportDoNotDisturbMode(MessageParcel &data, M return ERR_OK; } +ErrCode AnsManagerStub::HandleIsNeedSilentInDoNotDisturbMode(MessageParcel &data, MessageParcel &reply) +{ + std::string phoneNumber; + if (!data.ReadString(phoneNumber)) { + ANS_LOGE("[HandleIsNeedSilentInDoNotDisturbMode] fail: read phoneNumber failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + int32_t callerType = 0; + if (!data.ReadInt32(callerType)) { + ANS_LOGE("[HandleIsNeedSilentInDoNotDisturbMode] fail: read callerType failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + if (!reply.WriteInt32(result)) { + ANS_LOGE("[HandleIsNeedSilentInDoNotDisturbMode] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandlePublishContinuousTaskNotification(MessageParcel &data, MessageParcel &reply) { sptr request = data.ReadParcelable(); @@ -1618,6 +1680,16 @@ ErrCode AnsManagerStub::HandleCanPopEnableNotificationDialog(MessageParcel &data return ERR_OK; } +ErrCode AnsManagerStub::HandleRemoveEnableNotificationDialog(MessageParcel &data, MessageParcel &reply) +{ + ErrCode result = RemoveEnableNotificationDialog(); + if (!reply.WriteInt32(result)) { + ANS_LOGE("[HandleRemoveEnableNotificationDialog] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply) { sptr bundleOption = data.ReadParcelable(); @@ -2482,13 +2554,13 @@ ErrCode AnsManagerStub::HandleSetAdditionConfig(MessageParcel &data, MessageParc ANS_LOGE("Failed to read key."); return ERR_ANS_PARCELABLE_FAILED; } - + std::string value; if (!data.ReadString(value)) { ANS_LOGE("Failed to read value."); return ERR_ANS_PARCELABLE_FAILED; } - + ErrCode result = SetAdditionConfig(key, value); if (!reply.WriteInt32(result)) { ANS_LOGE("Failed to write result, ErrCode=%{public}d", result); @@ -2550,14 +2622,14 @@ ErrCode AnsManagerStub::HandleIsSmartReminderEnabled(MessageParcel &data, Messag ANS_LOGE("[HandleIsSmartReminderEnabled] fail: read deviceId failed."); return ERR_ANS_PARCELABLE_FAILED; } - + bool enabled = false; ErrCode result = IsSmartReminderEnabled(deviceType, enabled); if (!reply.WriteInt32(result)) { ANS_LOGE("[HandleIsSmartReminderEnabled] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; } - + if (!reply.WriteBool(enabled)) { ANS_LOGE("[HandleIsSmartReminderEnabled] fail: write enabled failed."); return ERR_ANS_PARCELABLE_FAILED; @@ -2587,6 +2659,25 @@ ErrCode AnsManagerStub::HandleSetTargetDeviceStatus(MessageParcel &data, Message return ERR_OK; } +ErrCode AnsManagerStub::HandleGetDoNotDisturbProfile(MessageParcel &data, MessageParcel &reply) +{ + int32_t profileId = data.ReadInt32(); + sptr profile = nullptr; + ErrCode result = GetDoNotDisturbProfile(profileId, profile); + if (!reply.WriteInt32(result)) { + ANS_LOGE("HandleGetDoNotDisturbProfile write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (result == ERR_OK) { + if (!reply.WriteParcelable(profile)) { + ANS_LOGE("HandleGetDoNotDisturbProfile write slot failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + } + return ERR_OK; +} + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode AnsManagerStub::HandleRegisterSwingCallback(MessageParcel &data, MessageParcel &reply) { @@ -2604,5 +2695,17 @@ ErrCode AnsManagerStub::HandleRegisterSwingCallback(MessageParcel &data, Message return result; } #endif + +ErrCode AnsManagerStub::HandleUpdateNotificationTimerByUid(MessageParcel &data, MessageParcel &reply) +{ + int32_t uid = data.ReadInt32(); + bool isPaused = data.ReadBool(); + ErrCode result = UpdateNotificationTimerByUid(uid, isPaused); + if (!reply.WriteInt32(result)) { + ANS_LOGE("[HandleUpdateNotificationTimerByUid] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/ans_manager_stub_invalid.cpp b/frameworks/core/src/ans_manager_stub_invalid.cpp index d659f076c3e03e4cbae55d3db2e74672c2d24a87..c42c7ac85bc47b38c0f608b49308cd19aa147a4d 100644 --- a/frameworks/core/src/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/ans_manager_stub_invalid.cpp @@ -32,6 +32,12 @@ ErrCode AnsManagerStub::Publish(const std::string &label, const sptr ¬ification) +{ + ANS_LOGE("AnsManagerStub::PublishNotificationForIndirectProxy called!"); + return ERR_INVALID_OPERATION; +} + ErrCode AnsManagerStub::Cancel(int notificationId, const std::string &label, int32_t instanceKey) { ANS_LOGE("AnsManagerStub::Cancel called!"); @@ -351,6 +357,12 @@ ErrCode AnsManagerStub::CanPopEnableNotificationDialog(const sptr &bundleOption, bool &allowed) { ANS_LOGE("AnsManagerStub::IsSpecialBundleAllowedNotify called!"); @@ -400,6 +412,12 @@ ErrCode AnsManagerStub::DoesSupportDoNotDisturbMode(bool &doesSupport) return ERR_INVALID_OPERATION; } +ErrCode AnsManagerStub::IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) +{ + ANS_LOGE("AnsManagerStub::IsNeedSilentInDoNotDisturbMode called!"); + return ERR_INVALID_OPERATION; +} + ErrCode AnsManagerStub::IsDistributedEnabled(bool &enabled) { ANS_LOGE("AnsManagerStub::IsDistributedEnabled called!"); @@ -640,6 +658,12 @@ ErrCode AnsManagerStub::SetTargetDeviceStatus(const std::string &deviceType, con return ERR_INVALID_OPERATION; } +ErrCode AnsManagerStub::GetDoNotDisturbProfile(int32_t id, sptr &profile) +{ + ANS_LOGE("GetDoNotDisturbProfile called!"); + return ERR_INVALID_OPERATION; +} + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode AnsManagerStub::RegisterSwingCallback(const sptr& swingCallback) { @@ -647,5 +671,11 @@ ErrCode AnsManagerStub::RegisterSwingCallback(const sptr& swingCa return ERR_INVALID_OPERATION; } #endif + +ErrCode AnsManagerStub::UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) +{ + ANS_LOGE("UpdateNotificationTimerByUid called!"); + return ERR_INVALID_OPERATION; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index 87cc6c5365cec6c461ec7336d1df4b7db88edeaa..6553934480e27011f6843bac921546654752ff64 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -17,6 +17,7 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "ans_manager_death_recipient.h" #include "ans_manager_proxy.h" #include "hitrace_meter_adapter.h" #include "ipc_skeleton.h" @@ -27,6 +28,10 @@ #include "reminder_request_calendar.h" #include "reminder_request_timer.h" #include "system_ability_definition.h" +#include "unique_fd.h" + +#include +#include namespace OHOS { namespace Notification { @@ -83,6 +88,7 @@ ErrCode AnsNotification::AddNotificationSlots(const std::vector proxy = GetAnsManagerProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); @@ -233,6 +239,58 @@ ErrCode AnsNotification::PublishNotification(const std::string &label, const Not return proxy->Publish(label, reqPtr); } +ErrCode AnsNotification::PublishNotificationForIndirectProxy(const NotificationRequest &request) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + ANS_LOGD("enter"); + + if (request.GetContent() == nullptr || request.GetNotificationType() == NotificationContent::Type::NONE) { + ANS_LOGE("Refuse to publish the notification without valid content"); + return ERR_ANS_INVALID_PARAM; + } + + if (!IsValidTemplate(request) || !IsValidDelayTime(request)) { + return ERR_ANS_INVALID_PARAM; + } + + if (!CanPublishMediaContent(request)) { + ANS_LOGE("Refuse to publish the notification because the series numbers actions not match those assigned to " + "added action buttons."); + return ERR_ANS_INVALID_PARAM; + } + + if (!CanPublishLiveViewContent(request)) { + ANS_LOGE("Refuse to publish the notification without valid live view content."); + return ERR_ANS_INVALID_PARAM; + } + + ErrCode checkErr = CheckImageSize(request); + if (checkErr != ERR_OK) { + ANS_LOGE("The size of one picture exceeds the limit"); + return checkErr; + } + + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("Failed to GetAnsManagerProxy."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr reqPtr = new (std::nothrow) NotificationRequest(request); + if (reqPtr == nullptr) { + ANS_LOGE("Create notificationRequest ptr fail."); + return ERR_ANS_NO_MEMORY; + } + + if (IsNonDistributedNotificationType(reqPtr->GetNotificationType())) { + reqPtr->SetDistributed(false); + } + int32_t instanceKey = DEFAULT_INSTANCE_KEY; + reqPtr->SetCreatorInstanceKey(instanceKey); + + return proxy->PublishNotificationForIndirectProxy(reqPtr); +} + ErrCode AnsNotification::CancelNotification(int32_t notificationId) { return CancelNotification("", notificationId); @@ -240,6 +298,7 @@ ErrCode AnsNotification::CancelNotification(int32_t notificationId) ErrCode AnsNotification::CancelNotification(const std::string &label, int32_t notificationId) { + ANS_LOGI("enter CancelNotification,notificationId:%{public}d", notificationId); HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); sptr proxy = GetAnsManagerProxy(); if (!proxy) { @@ -266,6 +325,7 @@ ErrCode AnsNotification::CancelAllNotifications() ErrCode AnsNotification::CancelAsBundle( int32_t notificationId, const std::string &representativeBundle, int32_t userId) { + ANS_LOGI("enter CancelAsBundle,notificationId:%{public}d", notificationId); sptr proxy = GetAnsManagerProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); @@ -277,6 +337,7 @@ ErrCode AnsNotification::CancelAsBundle( ErrCode AnsNotification::CancelAsBundle( const NotificationBundleOption &bundleOption, int32_t notificationId) { + ANS_LOGI("enter CancelAsBundle,notificationId:%{public}d", notificationId); sptr proxy = GetAnsManagerProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); @@ -443,6 +504,17 @@ ErrCode AnsNotification::CanPopEnableNotificationDialog(sptrCanPopEnableNotificationDialog(hostClient, canPop, bundleName); } +ErrCode AnsNotification::RemoveEnableNotificationDialog() +{ + ANS_LOGD("enter"); + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->RemoveEnableNotificationDialog(); +} + ErrCode AnsNotification::RequestEnableNotification(std::string &deviceId, sptr &hostClient, sptr &callerToken) @@ -601,6 +673,98 @@ ErrCode AnsNotification::UnSubscribeNotification( return proxy->Unsubscribe(subscriberSptr, sptrInfo); } +ErrCode AnsNotification::SubscribeNotification(const std::shared_ptr &subscriber) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + return SubscribeNotification(subscriber, nullptr); +} + +ErrCode AnsNotification::SubscribeNotificationSelf(const std::shared_ptr &subscriber) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + if (subscriber == nullptr) { + ANS_LOGE("Subscriber is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr listener = nullptr; + CreateSubscribeListener(subscriber, listener); + if (listener == nullptr) { + ANS_LOGE("Failed to subscribe due to create subscriber listener failed."); + return ERR_ANS_NO_MEMORY; + } + DelayedSingleton::GetInstance()->SubscribeSAManager(); + return proxy->SubscribeSelf(listener); +} + +ErrCode AnsNotification::SubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + if (subscriber == nullptr) { + ANS_LOGE("Subscriber is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("Failed to GetAnsManagerProxy."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr listener = nullptr; + CreateSubscribeListener(subscriber, listener); + if (listener == nullptr) { + ANS_LOGE("Failed to subscribe due to create subscriber listener failed."); + return ERR_ANS_NO_MEMORY; + } + if (subscribeInfo != nullptr) { + subscriber->SetDeviceType(subscribeInfo->GetDeviceType()); + } + DelayedSingleton::GetInstance()->SubscribeSAManager(); + return proxy->Subscribe(listener, subscribeInfo); +} + +ErrCode AnsNotification::UnSubscribeNotification(const std::shared_ptr &subscriber) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + return UnSubscribeNotification(subscriber, nullptr); +} + +ErrCode AnsNotification::UnSubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + if (subscriber == nullptr) { + ANS_LOGE("Subscriber is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + std::lock_guard lock(subscriberMutex_); + auto item = subscribers_.find(subscriber); + if (item != subscribers_.end()) { + sptr listener = item->second; + int32_t ret = proxy->Unsubscribe(listener, subscribeInfo); + if (ret == ERR_OK) { + subscribers_.erase(item); + } + return ret; + } + ANS_LOGE("Failed to unsubscribe due to subscriber not found."); + return ERR_ANS_INVALID_PARAM; +} + ErrCode AnsNotification::TriggerLocalLiveView(const NotificationBundleOption &bundleOption, const int32_t notificationId, const NotificationButtonOption &buttonOption) { @@ -624,6 +788,8 @@ ErrCode AnsNotification::TriggerLocalLiveView(const NotificationBundleOption &bu ErrCode AnsNotification::RemoveNotification(const std::string &key, int32_t removeReason) { + ANS_LOGI("enter RemoveNotification,key:%{public}s,removeReason:%{public}d", + key.c_str(), removeReason); HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); if (key.empty()) { ANS_LOGW("Input key is empty."); @@ -641,6 +807,8 @@ ErrCode AnsNotification::RemoveNotification(const std::string &key, int32_t remo ErrCode AnsNotification::RemoveNotification(const NotificationBundleOption &bundleOption, const int32_t notificationId, const std::string &label, int32_t removeReason) { + ANS_LOGI("enter RemoveNotification,bundle:%{public}s,Id:%{public}d,reason:%{public}d", + bundleOption.GetBundleName().c_str(), notificationId, removeReason); HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); if (bundleOption.GetBundleName().empty()) { ANS_LOGE("Invalid bundle name."); @@ -659,6 +827,7 @@ ErrCode AnsNotification::RemoveNotification(const NotificationBundleOption &bund ErrCode AnsNotification::RemoveAllNotifications(const NotificationBundleOption &bundleOption) { + ANS_LOGI("enter RemoveAllNotifications,bundleName:%{public}s", bundleOption.GetBundleName().c_str()); if (bundleOption.GetBundleName().empty()) { ANS_LOGE("Invalid bundle name."); return ERR_ANS_INVALID_PARAM; @@ -676,6 +845,7 @@ ErrCode AnsNotification::RemoveAllNotifications(const NotificationBundleOption & ErrCode AnsNotification::RemoveNotifications(const std::vector hashcodes, int32_t removeReason) { + ANS_LOGI("enter RemoveNotifications,removeReason:%{public}d", removeReason); if (hashcodes.empty()) { ANS_LOGE("Hashcodes is empty"); return ERR_ANS_INVALID_PARAM; @@ -692,6 +862,7 @@ ErrCode AnsNotification::RemoveNotifications(const std::vector hash ErrCode AnsNotification::RemoveNotificationsByBundle(const NotificationBundleOption &bundleOption) { + ANS_LOGI("enter RemoveNotificationsByBundle,bundleName:%{public}s", bundleOption.GetBundleName().c_str()); if (bundleOption.GetBundleName().empty()) { ANS_LOGE("Invalid bundle name."); return ERR_ANS_INVALID_PARAM; @@ -919,6 +1090,7 @@ ErrCode AnsNotification::GetShowBadgeEnabled(bool &enabled) ErrCode AnsNotification::CancelGroup(const std::string &groupName) { + ANS_LOGI("enter CancelGroup,groupName:%{public}s", groupName.c_str()); if (groupName.empty()) { ANS_LOGE("Invalid group name."); return ERR_ANS_INVALID_PARAM; @@ -936,6 +1108,7 @@ ErrCode AnsNotification::CancelGroup(const std::string &groupName) ErrCode AnsNotification::RemoveGroupByBundle( const NotificationBundleOption &bundleOption, const std::string &groupName) { + ANS_LOGI("enter RemoveGroupByBundle,bundleName:%{public}s", bundleOption.GetBundleName().c_str()); if (bundleOption.GetBundleName().empty() || groupName.empty()) { ANS_LOGE("Invalid parameter."); return ERR_ANS_INVALID_PARAM; @@ -1032,6 +1205,17 @@ ErrCode AnsNotification::DoesSupportDoNotDisturbMode(bool &doesSupport) return proxy->DoesSupportDoNotDisturbMode(doesSupport); } +ErrCode AnsNotification::IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) +{ + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); +} + ErrCode AnsNotification::PublishContinuousTaskNotification(const NotificationRequest &request) { if (request.GetContent() == nullptr || request.GetNotificationType() == NotificationContent::Type::NONE) { @@ -1077,6 +1261,7 @@ ErrCode AnsNotification::PublishContinuousTaskNotification(const NotificationReq ErrCode AnsNotification::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) { + ANS_LOGI("enter CancelContinuousTaskNotification,notificationId:%{public}d", notificationId); sptr proxy = GetAnsManagerProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); @@ -1155,11 +1340,7 @@ ErrCode AnsNotification::GetDeviceRemindType(NotificationConstant::RemindType &r } void AnsNotification::ResetAnsManagerProxy() -{ - ANS_LOGD("enter"); - std::lock_guard lock(mutex_); - ansManagerProxy_ = nullptr; -} +{} void AnsNotification::Reconnect() { @@ -1167,13 +1348,12 @@ void AnsNotification::Reconnect() for (int32_t i = 0; i < MAX_RETRY_TIME; i++) { // try to connect ans sptr proxy = GetAnsManagerProxy(); - if (!proxy) { + if (!proxy) { // Sleep 1000 milliseconds before reconnect. std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); ANS_LOGE("get ans proxy fail, try again."); continue; } - ANS_LOGD("get ans proxy success."); return; } @@ -1365,12 +1545,6 @@ ErrCode AnsNotification::CheckImageSize(const NotificationRequest &request) return ERR_ANS_ICON_OVER_SIZE; } - auto bigIcon = request.GetBigIcon(); - if (NotificationRequest::CheckImageOverSizeForPixelMap(bigIcon, MAX_ICON_SIZE)) { - ANS_LOGE("The size of big icon exceeds limit"); - return ERR_ANS_ICON_OVER_SIZE; - } - auto overlayIcon = request.GetOverlayIcon(); if (overlayIcon && NotificationRequest::CheckImageOverSizeForPixelMap(overlayIcon, MAX_ICON_SIZE)) { ANS_LOGE("The size of overlay icon exceeds limit"); @@ -1406,6 +1580,12 @@ ErrCode AnsNotification::CheckImageSize(const NotificationRequest &request) } } + auto bigIcon = request.GetBigIcon(); + if (NotificationRequest::CheckImageOverSizeForPixelMap(bigIcon, MAX_ICON_SIZE)) { + request.ResetBigIcon(); + ANS_LOGI("The size of big icon exceeds limit"); + } + return ERR_OK; } @@ -1751,6 +1931,8 @@ ErrCode AnsNotification::SetSmartReminderEnabled(const std::string &deviceType, ErrCode AnsNotification::CancelAsBundleWithAgent(const NotificationBundleOption &bundleOption, const int32_t id) { + ANS_LOGI("enter CancelAsBundleWithAgent,bundleName:%{public}s,id:%{public}d", + bundleOption.GetBundleName().c_str(), id); sptr proxy = GetAnsManagerProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); @@ -1809,6 +1991,41 @@ bool AnsNotification::IsValidDelayTime(const NotificationRequest &request) cons return request.GetPublishDelayTime() <= MAX_PUBLISH_DELAY_TIME; } +ErrCode AnsNotification::GetDoNotDisturbProfile(int32_t id, sptr &profile) +{ + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("Fail to GetAnsManagerProxy."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->GetDoNotDisturbProfile(id, profile); +} + +void AnsNotification::CreateSubscribeListener(const std::shared_ptr &subscriber, + sptr &listener) +{ + std::lock_guard lock(subscriberMutex_); + auto item = subscribers_.find(subscriber); + if (item != subscribers_.end()) { + listener = item->second; + ANS_LOGD("subscriber has listener"); + return; + } + listener = new (std::nothrow) SubscriberListener(subscriber); + if (listener != nullptr) { + subscribers_[subscriber] = listener; + ANS_LOGD("CreateSubscribeListener success"); + } +} + +void AnsNotification::OnServiceDied() +{ + std::lock_guard lock(subscriberMutex_); + for (auto item : subscribers_) { + item.first->OnDied(); + } +} + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode AnsNotification::RegisterSwingCallback(const std::function swingCbFunc) { @@ -1826,5 +2043,15 @@ ErrCode AnsNotification::RegisterSwingCallback(const std::functionRegisterSwingCallback(swingCallBackStub_->AsObject()); } #endif + +ErrCode AnsNotification::UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) +{ + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("UpdateNotificationTimerByUid fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->UpdateNotificationTimerByUid(uid, isPaused); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/ans_subscriber_listener.cpp b/frameworks/core/src/ans_subscriber_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4c2af00be098ab2e8a5fca858303a0df81eec39 --- /dev/null +++ b/frameworks/core/src/ans_subscriber_listener.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ans_subscriber_listener.h" +#include "notification_constant.h" +#include "hitrace_meter_adapter.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { +SubscriberListener::SubscriberListener(const std::shared_ptr &subscriber) + : subscriber_(subscriber) +{}; + +SubscriberListener::~SubscriberListener() +{} + +void SubscriberListener::OnConnected() +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnConnected(); +} + +void SubscriberListener::OnDisconnected() +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnDisconnected(); +} + +void SubscriberListener::OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + + std::shared_ptr sharedNotification = std::make_shared(*notification); +#ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED + if (!subscriber->ProcessSyncDecision(subscriber->GetDeviceType(), sharedNotification)) { + return; + } +#endif + + subscriber->OnConsumed( + sharedNotification, std::make_shared(*notificationMap)); +} + +void SubscriberListener::OnConsumedList(const std::vector> ¬ifications, + const sptr ¬ificationMap) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + for (auto notification : notifications) { + OnConsumed(notification, notificationMap); + } +} + +void SubscriberListener::OnCanceled( + const sptr ¬ification, const sptr ¬ificationMap, int32_t deleteReason) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + if (notificationMap == nullptr) { + subscriber->OnCanceled(std::make_shared(*notification), + std::make_shared(), deleteReason); + } else { + subscriber->OnCanceled(std::make_shared(*notification), + std::make_shared(*notificationMap), deleteReason); + } +} + +void SubscriberListener::OnBatchCanceled(const std::vector> ¬ifications, + const sptr ¬ificationMap, int32_t deleteReason) +{ + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + std::vector> notificationList; + for (auto notification : notifications) { + notificationList.emplace_back(std::make_shared(*notification)); + } + if (notificationMap == nullptr) { + subscriber->OnBatchCanceled(notificationList, + std::make_shared(), deleteReason); + } else { + subscriber->OnBatchCanceled(notificationList, + std::make_shared(*notificationMap), deleteReason); + } +} + +void SubscriberListener::OnCanceledList(const std::vector> ¬ifications, + const sptr ¬ificationMap, int32_t deleteReason) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + if (subscriber->HasOnBatchCancelCallback()) { + OnBatchCanceled(notifications, notificationMap, deleteReason); + return; + } + for (auto notification : notifications) { + OnCanceled(notification, notificationMap, deleteReason); + } +} + +void SubscriberListener::OnUpdated(const sptr ¬ificationMap) +{ + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnUpdate(std::make_shared(*notificationMap)); +} + +void SubscriberListener::OnDoNotDisturbDateChange(const sptr &date) +{ + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnDoNotDisturbDateChange(std::make_shared(*date)); +} + +void SubscriberListener::OnEnabledNotificationChanged( + const sptr &callbackData) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnEnabledNotificationChanged(std::make_shared(*callbackData)); +} + +void SubscriberListener::OnBadgeChanged(const sptr &badgeData) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnBadgeChanged(std::make_shared(*badgeData)); +} + +void SubscriberListener::OnBadgeEnabledChanged( + const sptr &callbackData) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnBadgeEnabledChanged(callbackData); +} +} // namespace Notification +} // namespace OHOS diff --git a/frameworks/core/src/ans_subscriber_proxy.cpp b/frameworks/core/src/ans_subscriber_proxy.cpp index 53e283ab9e7838b75515bf843fe14806d81bf3bf..bb63fde4452c43c27d760ceb86b5c188a8e08844 100644 --- a/frameworks/core/src/ans_subscriber_proxy.cpp +++ b/frameworks/core/src/ans_subscriber_proxy.cpp @@ -143,6 +143,9 @@ void AnsSubscriberProxy::OnConsumedList(const std::vector> &n } MessageParcel data; + if (!data.SetMaxCapacity(NotificationConstant::NOTIFICATION_MAX_LIVE_VIEW_SIZE)) { + ANS_LOGE("[OnConsumedList] fail: set max capacity failed."); + } if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { ANS_LOGE("Write interface token failed."); return; @@ -241,8 +244,9 @@ void AnsSubscriberProxy::OnCanceledList(const std::vector> &n for (size_t i = 0; i < notifications.size(); i ++) { sptr notification = notifications[i]; - notification->GetNotificationRequest().SetBigIcon(nullptr); - notification->GetNotificationRequest().SetLittleIcon(nullptr); + notification->GetNotificationRequestPoint()->SetBigIcon(nullptr); + notification->GetNotificationRequestPoint()->SetLittleIcon(nullptr); + notification->GetNotificationRequestPoint()->SetOverlayIcon(nullptr); } if (!WriteParcelableVector(notifications, data)) { ANS_LOGE("Write notifications failed"); diff --git a/frameworks/core/src/manager/ans_manager_proxy_bundle.cpp b/frameworks/core/src/manager/ans_manager_proxy_bundle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4aae443abd326b74a11f44841184eda46a8d10a7 --- /dev/null +++ b/frameworks/core/src/manager/ans_manager_proxy_bundle.cpp @@ -0,0 +1,797 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "ans_subscriber_local_live_view_interface.h" +#include "distributed_notification_service_ipc_interface_code.h" +#include "message_option.h" +#include "message_parcel.h" +#include "parcel.h" +#include "ans_manager_proxy.h" + +namespace OHOS { +namespace Notification { +ErrCode AnsManagerProxy::SetNotificationBadgeNum(int32_t num) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetNotificationBadgeNum] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(num)) { + ANS_LOGE("[SetNotificationBadgeNum] fail: write num failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_NOTIFICATION_BADGE_NUM, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetNotificationBadgeNum] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetNotificationBadgeNum] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetBundleImportance(int32_t &importance) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[GetBundleImportance] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_BUNDLE_IMPORTANCE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[GetBundleImportance] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[GetBundleImportance] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadInt32(importance)) { + ANS_LOGE("[GetBundleImportance] fail: read importance failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::HasNotificationPolicyAccessPermission(bool &granted) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[HasNotificationPolicyAccessPermission] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_NOTIFICATION_POLICY_ACCESS_GRANTED, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[HasNotificationPolicyAccessPermission] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[HasNotificationPolicyAccessPermission] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(granted)) { + ANS_LOGE("[HasNotificationPolicyAccessPermission] fail: read granted failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::RequestEnableNotification(const std::string &deviceId, + const sptr &callback, + const sptr &callerToken) +{ + ANS_LOGD("enter"); + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[RequestEnableNotification] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGE("[RequestEnableNotification] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (callback == nullptr || !data.WriteRemoteObject(callback->AsObject())) { + ANS_LOGE("[RequestEnableNotification] fail: write callback failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(callerToken != nullptr)) { + ANS_LOGE("fail: write callerToken failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + if (callerToken != nullptr) { + if (!data.WriteRemoteObject(callerToken)) { + ANS_LOGE("fail: write callerToken failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::REQUEST_ENABLE_NOTIFICATION, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[RequestEnableNotification] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[RequestEnableNotification] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetNotificationsEnabledForBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGE("[SetNotificationsEnabledForBundle] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetNotificationsEnabledForBundle] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_NOTIFICATION_ENABLED_FOR_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetNotificationsEnabledForBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetNotificationsEnabledForBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetNotificationsEnabledForAllBundles] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGE("[SetNotificationsEnabledForAllBundles] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetNotificationsEnabledForAllBundles] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_NOTIFICATION_ENABLED_FOR_ALL_BUNDLE, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetNotificationsEnabledForAllBundles] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetNotificationsEnabledForAllBundles] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledForSpecialBundle( + const std::string &deviceId, const sptr &bundleOption, bool enabled) +{ + if (bundleOption == nullptr) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: bundleOption is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: write bundleOption failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_NOTIFICATION_ENABLED_FOR_SPECIAL_BUNDLE, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetShowBadgeEnabledForBundle(const sptr &bundleOption, bool enabled) +{ + if (bundleOption == nullptr) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail:: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_SHOW_BADGE_ENABLED_FOR_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetShowBadgeEnabledForBundle(const sptr &bundleOption, bool &enabled) +{ + if (bundleOption == nullptr) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_SHOW_BADGE_ENABLED_FOR_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(enabled)) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetShowBadgeEnabled(bool &enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[GetShowBadgeEnabled] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_SHOW_BADGE_ENABLED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[GetShowBadgeEnabled] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[GetShowBadgeEnabled] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(enabled)) { + ANS_LOGE("[GetShowBadgeEnabled] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::IsAllowedNotify(bool &allowed) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[IsAllowedNotify] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_ALLOWED_NOTIFY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[IsAllowedNotify] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[IsAllowedNotify] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGE("[IsAllowedNotify] fail: read allowed failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::IsAllowedNotifySelf(bool &allowed) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[IsAllowedNotifySelf] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_ALLOWED_NOTIFY_SELF, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[IsAllowedNotifySelf] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[IsAllowedNotifySelf] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGE("[IsAllowedNotifySelf] fail: read allowed failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::CanPopEnableNotificationDialog(const sptr &callback, + bool &canPop, std::string &bundleName) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (callback == nullptr || !data.WriteRemoteObject(callback->AsObject())) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: write callback failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::CAN_POP_ENABLE_NOTIFICATION_DIALOG, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(canPop)) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: read canPop failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!reply.ReadString(bundleName)) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: read bundleName failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::RemoveEnableNotificationDialog() +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::REMOVE_ENABLE_NOTIFICATION_DIALOG, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[RemoveEnableNotificationDialog] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + if (!reply.ReadInt32(result)) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} + +ErrCode AnsManagerProxy::IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) +{ + if (bundleOption == nullptr) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: read allowed error."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[IsSpecialUserAllowedNotify] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGE("[IsSpecialUserAllowedNotify] fail: write userId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_SPECIAL_USER_ALLOWED_NOTIFY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: read allowed failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledByUser(const int32_t &userId, bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetNotificationsEnabledByUser] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGE("[SetNotificationsEnabledByUser] fail: write userId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetNotificationsEnabledByUser] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_NOTIFICATION_ENABLED_BY_USER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetNotificationsEnabledByUser] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetNotificationsEnabledByUser] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetSyncNotificationEnabledWithoutApp(const int32_t userId, const bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetSyncNotificationEnabledWithoutApp] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGE("[SetSyncNotificationEnabledWithoutApp] fail:: write userId failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetSyncNotificationEnabledWithoutApp] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_SYNC_NOTIFICATION_ENABLED_WITHOUT_APP, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetSyncNotificationEnabledWithoutApp] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetSyncNotificationEnabledWithoutApp] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetSyncNotificationEnabledWithoutApp(const int32_t userId, bool &enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[GetSyncNotificationEnabledWithoutApp] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGE("[GetSyncNotificationEnabledWithoutApp] fail:: write userId failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_SYNC_NOTIFICATION_ENABLED_WITHOUT_APP, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[GetSyncNotificationEnabledWithoutApp] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[GetSyncNotificationEnabledWithoutApp] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(enabled)) { + ANS_LOGE("[GetSyncNotificationEnabledWithoutApp] fail: read enable failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetBadgeNumber(int32_t badgeNumber, int32_t instanceKey) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetBadgeNumber] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(badgeNumber)) { + ANS_LOGE("[SetBadgeNumber] fail:: write badgeNumber failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(instanceKey)) { + ANS_LOGE("[SetBadgeNumber] fail:: write instancekey failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_BADGE_NUMBER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetBadgeNumber] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetBadgeNumber] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetBadgeNumberByBundle(const sptr &bundleOption, int32_t badgeNumber) +{ + if (bundleOption == nullptr) { + ANS_LOGE("Bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("Write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGE("Write bundle option failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!data.WriteInt32(badgeNumber)) { + ANS_LOGE("Write badge number failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = { MessageOption::TF_SYNC }; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_BADGE_NUMBER_BY_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("Transact error code is: %{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + if (!reply.ReadInt32(result)) { + ANS_LOGE("Read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} + +ErrCode AnsManagerProxy::GetAllNotificationEnabledBundles(std::vector &bundleOption) +{ + ANS_LOGD("Called."); + MessageParcel data; + int32_t vectorSize = 0; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("Write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = { MessageOption::TF_SYNC }; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_ALL_NOTIFICATION_ENABLE_STATUS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("Fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("Fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadInt32(vectorSize)) { + ANS_LOGE("Fail: read vectorSize failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (vectorSize > MAX_STATUS_VECTOR_NUM) { + ANS_LOGE("Bundle status vector is over size"); + return ERR_ANS_PARCELABLE_FAILED; + } + + for (auto i = 0; i < vectorSize; i++) { + sptr obj = reply.ReadParcelable(); + if (obj == nullptr) { + ANS_LOGE("The obj of Bundle status vector is nullptr."); + return ERR_ANS_PARCELABLE_FAILED; + } + bundleOption.emplace_back(*obj); + } + + return result; +} +} // namespace Notification +} // namespace OHOS diff --git a/frameworks/core/test/unittest/BUILD.gn b/frameworks/core/test/unittest/BUILD.gn index 22ef009cc3d8f7e622274df50529aa48fcc8762b..94550b16b1ea7d224a75fedd9bb0f60601e076fe 100644 --- a/frameworks/core/test/unittest/BUILD.gn +++ b/frameworks/core/test/unittest/BUILD.gn @@ -17,7 +17,6 @@ group("unittest") { deps += [ "ans_image_util_test:unittest", - "ans_manager_death_recipient_test:unittest", "ans_manager_proxy_test:unittest", "ans_manager_stub_test:unittest", "ans_notification_annex_test:unittest", diff --git a/frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp b/frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp deleted file mode 100644 index de513a16e2addc6727b980618dff4ecaffdac5ae..0000000000000000000000000000000000000000 --- a/frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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 - -#define private public -#define protected public -#include "ans_manager_death_recipient.h" -#include "ans_notification.h" -#undef private -#undef protected - -#include "singleton.h" - -using namespace testing::ext; -using namespace OHOS; -using namespace OHOS::Notification; - -class AnsManagerDeathRecipientUnitTest : public testing::Test { -public: - AnsManagerDeathRecipientUnitTest() {} - - virtual ~AnsManagerDeathRecipientUnitTest() {} - - static void SetUpTestCase(); - - static void TearDownTestCase(); - - void SetUp(); - - void TearDown(); -}; - -void AnsManagerDeathRecipientUnitTest::SetUpTestCase() {} - -void AnsManagerDeathRecipientUnitTest::TearDownTestCase() {} - -void AnsManagerDeathRecipientUnitTest::SetUp() {} - -void AnsManagerDeathRecipientUnitTest::TearDown() {} - -/* - * @tc.name: SubscribeSAManagerTest_0100 - * @tc.desc: test if AnsManagerDeathRecipient's SubscribeSAManager function executed as expected in normal case. - * @tc.type: FUNC - * @tc.require: #I5SJ62 - */ -HWTEST_F(AnsManagerDeathRecipientUnitTest, SubscribeSAManagerTest_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) - << "AnsManagerDeathRecipientUnitTest, SubscribeSAManagerTest_0100, TestSize.Level1"; - auto ansManagerDeathRecipient = OHOS::DelayedSingleton::GetInstance(); - ansManagerDeathRecipient->SubscribeSAManager(); - EXPECT_EQ(true, ansManagerDeathRecipient->GetIsSubscribeSAManager()); -} - -/* - * @tc.name: OnRemoveSystemAbilityTest_0100 - * @tc.desc: test if AnsManagerDeathRecipient's OnRemoveSystemAbility function executed as expected in normal case. - * @tc.type: FUNC - * @tc.require: #I5SJ62 - */ -HWTEST_F(AnsManagerDeathRecipientUnitTest, OnRemoveSystemAbilityTest_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) - << "AnsManagerDeathRecipientUnitTest, OnRemoveSystemAbilityTest_0100, TestSize.Level1"; - auto ansManagerDeathRecipient = OHOS::DelayedSingleton::GetInstance(); - ansManagerDeathRecipient->SubscribeSAManager(); - ansManagerDeathRecipient->statusChangeListener_->OnRemoveSystemAbility(0, ""); - auto ansNotification = OHOS::DelayedSingleton::GetInstance(); - EXPECT_TRUE(ansNotification->ansManagerProxy_ == nullptr); -} - -/* - * @tc.name: OnAddSystemAbilityTest_0100 - * @tc.desc: test if AnsManagerDeathRecipient's OnAddSystemAbility function executed as expected in normal case. - * @tc.type: FUNC - * @tc.require: #I5SJ62 - */ -HWTEST_F(AnsManagerDeathRecipientUnitTest, OnAddSystemAbilityTest_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) - << "AnsManagerDeathRecipientUnitTest, OnAddSystemAbilityTest_0100, TestSize.Level1"; - auto ansManagerDeathRecipient = OHOS::DelayedSingleton::GetInstance(); - ansManagerDeathRecipient->SubscribeSAManager(); - ansManagerDeathRecipient->statusChangeListener_->OnRemoveSystemAbility(0, ""); - ansManagerDeathRecipient->statusChangeListener_->OnAddSystemAbility(0, ""); - auto ansNotification = OHOS::DelayedSingleton::GetInstance(); - EXPECT_TRUE(ansNotification->ansManagerProxy_ != nullptr); -} diff --git a/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp b/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp index 326f4505289f248b9eb135c53399d169bb73ea40..2a609a0559b85a26f139391a6134c7e69a2c8b45 100644 --- a/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp @@ -2024,8 +2024,8 @@ HWTEST_F(AnsManagerProxyUnitTest, GetActiveNotificationsTest_0200, Function | Me ASSERT_NE(nullptr, proxy); std::vector> notifications; int32_t result = proxy->GetActiveNotifications(notifications, 0); - EXPECT_EQ(ERR_OK, result); - EXPECT_EQ(1, notifications.size()); + EXPECT_EQ(ERR_ANS_PARCELABLE_FAILED, result); + EXPECT_EQ(0, notifications.size()); } /* * @tc.name: GetActiveNotificationsTest_0300 @@ -8080,5 +8080,135 @@ HWTEST_F(AnsManagerProxyUnitTest, RemoveDoNotDisturbProfiles_0300, TestSize.Leve EXPECT_NE(ERR_OK, res); EXPECT_NE(ERR_ANS_PARCELABLE_FAILED, res); } + +/* + * @tc.name: IsNeedSilentInDoNotDisturbModeTest_0100 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0100, TestSize.Level1"; + MockWriteInterfaceToken(false); + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ERR_ANS_PARCELABLE_FAILED, result); +} + +/* + * @tc.name: IsNeedSilentInDoNotDisturbModeTest_0200 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0200, TestSize.Level1"; + MockWriteInterfaceToken(true); + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + EXPECT_CALL(*iremoteObject, SendRequest(_, _, _, _)) + .WillRepeatedly(DoAll(Invoke(std::bind(SendRequestReplace, _1, _2, _3, _4, + ERR_OK, true, true, true)), Return(NO_ERROR))); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ERR_OK, result); +} + +/* + * @tc.name: IsNeedSilentInDoNotDisturbModeTest_0300 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0300, TestSize.Level1"; + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + EXPECT_CALL(*iremoteObject, SendRequest(_, _, _, _)).Times(1) + .WillRepeatedly(DoAll(Return(DEAD_OBJECT))); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ERR_ANS_TRANSACT_FAILED, result); +} + +/* + * @tc.name: IsNeedSilentInDoNotDisturbModeTest_0400 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0400, TestSize.Level1"; + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + EXPECT_CALL(*iremoteObject, SendRequest(_, _, _, _)).Times(1) + .WillRepeatedly(DoAll(Invoke(std::bind(SendRequestReplace, _1, _2, _3, _4, + ERR_OK, false, false, false)), Return(NO_ERROR))); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ERR_ANS_PARCELABLE_FAILED, result); +} + +/* + * @tc.name: IsNeedSilentInDoNotDisturbModeTest_0500 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0500, TestSize.Level1"; + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + EXPECT_CALL(*iremoteObject, SendRequest(_, _, _, _)).Times(1) + .WillRepeatedly(DoAll(Invoke(std::bind(SendRequestReplace, _1, _2, _3, _4, + ERR_OK, true, true, false)), Return(NO_ERROR))); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ERR_OK, result); +} + +/* + * @tc.name: UpdateNotificationTimerByUid_0100 + * @tc.desc: test UpdateNotificationTimerByUid function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, UpdateNotificationTimerByUid_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, UpdateNotificationTimerByUid_0100, TestSize.Level1"; + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + EXPECT_CALL(*iremoteObject, SendRequest(_, _, _, _)).Times(1) + .WillRepeatedly(DoAll(Invoke(std::bind(SendRequestReplace, _1, _2, _3, _4, + ERR_OK, true, false, false)), Return(NO_ERROR))); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + int32_t uid = 20099999; + bool isPaused = true; + int32_t result = proxy->UpdateNotificationTimerByUid(uid, isPaused); + EXPECT_EQ(ERR_OK, result); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp b/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp index 0190cf750955254684444cc7b2e3267dc927ea2c..96bb54b6305e628c05f0b4e699cb17bcbad2fdb2 100644 --- a/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp @@ -103,6 +103,11 @@ HWTEST_F(AnsManagerStubTest, HandlePublish01, Function | SmallTest | Level1) std::string label = "this is a notification label"; sptr notification = new NotificationRequest(); + notification->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + notification->SetContent(content2); data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); data.WriteString(label); data.WriteParcelable(notification); @@ -1007,7 +1012,11 @@ HWTEST_F(AnsManagerStubTest, HandlePublishAsBundle01, Function | SmallTest | Lev MessageOption option = {MessageOption::TF_SYNC}; sptr notification = new NotificationRequest(); - + notification->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + notification->SetContent(content2); std::string representativeBundle = "this is a representativeBundle"; data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); @@ -1215,7 +1224,11 @@ HWTEST_F(AnsManagerStubTest, HandlePublishContinuousTaskNotification01, Function MessageOption option = {MessageOption::TF_SYNC}; sptr request = new NotificationRequest(); - + request->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + request->SetContent(content2); data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); data.WriteParcelable(request); @@ -5428,5 +5441,50 @@ HWTEST_F(AnsManagerStubTest, RegisterSwingCallback_0200, TestSize.Level1) EXPECT_EQ(res, ERR_ANS_PARCELABLE_FAILED); } #endif + +/** + * @tc.name: HandleIsNeedSilentInDoNotDisturbMode01 + * @tc.desc: Test HandleIsNeedSilentInDoNotDisturbMode01 succeeds. + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerStubTest, HandleIsNeedSilentInDoNotDisturbMode01, Function | SmallTest | Level1) +{ + uint32_t code = static_cast(NotificationInterfaceCode::IS_NEED_SILENT_IN_DO_NOT_DISTURB_MODE); + MessageParcel data; + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + + data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); + + ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); + EXPECT_EQ(ret, (int)ERR_ANS_PARCELABLE_FAILED); +} + +/** + * @tc.name: IsNeedSilentInDoNotDisturbMode01 + * @tc.desc: Test IsNeedSilentInDoNotDisturbMode return. + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerStubTest, IsNeedSilentInDoNotDisturbMode01, Function | SmallTest | Level1) +{ + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + + ErrCode result = ansManagerStub_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); +} + +/** + * @tc.name: UpdateNotificationTimerByUid_01 + * @tc.desc: Test UpdateNotificationTimerByUid return. + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerStubTest, UpdateNotificationTimerByUid_01, Function | SmallTest | Level1) +{ + int32_t uid = 20099999; + bool isPaused = true; + ErrCode result = ansManagerStub_->UpdateNotificationTimerByUid(uid, isPaused); + EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); +} } } diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn b/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn index 95540f750d16eecdf1711c7d798e9e2b8b6318f4..c96bda5b6cc5d531d445638e4c39224a275f9313 100755 --- a/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn +++ b/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn @@ -25,8 +25,8 @@ ohos_unittest("ans_notification_branch_test") { ] sources = [ + "../mock/mock_ans_manager_proxy.cpp", "ans_notification_branch_test.cpp", - "mock_ans_notification.cpp", ] deps = [ diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index fa2edbc73a2839a983255f06e34f49251645ab2a..b03eb1d7fdb18b808baa97af1ee35d7ca40d53fe 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -31,7 +31,7 @@ #include "singleton.h" #include "notification_subscriber.h" -extern void MockGetAnsManagerProxy(bool mockRet); +extern void MockGetAnsManagerProxy(OHOS::sptr mockRet); using namespace testing; using namespace testing::ext; @@ -55,6 +55,11 @@ public: return ERR_ANS_INVALID_PARAM; } + ErrCode PublishNotificationForIndirectProxy(const sptr ¬ification) override + { + return ERR_ANS_INVALID_PARAM; + } + ErrCode Cancel(int notificationId, const std::string &label, int32_t instanceKey) override { return ERR_ANS_INVALID_PARAM; @@ -307,6 +312,11 @@ public: return ERR_ANS_INVALID_PARAM; } + ErrCode RemoveEnableNotificationDialog() override + { + return ERR_ANS_INVALID_PARAM; + } + ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override { return ERR_ANS_INVALID_PARAM; @@ -337,6 +347,11 @@ public: return ERR_ANS_INVALID_PARAM; } + ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) override + { + return ERR_ANS_INVALID_PARAM; + } + ErrCode CancelGroup(const std::string &groupName, int32_t instanceKey) override { return ERR_ANS_INVALID_PARAM; @@ -567,12 +582,22 @@ public: return ERR_ANS_INVALID_PARAM; } + ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) + { + return ERR_ANS_INVALID_PARAM; + } + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode RegisterSwingCallback(const sptr &swingCallback) override { return ERR_ANS_INVALID_PARAM; } #endif + + ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) override + { + return ERR_ANS_INVALID_PARAM; + } }; class AnsNotificationBranchTest : public testing::Test { @@ -588,7 +613,10 @@ public: void SetUp(); }; -void AnsNotificationBranchTest::SetUpTestCase() {} +void AnsNotificationBranchTest::SetUpTestCase() +{ + MockGetAnsManagerProxy(nullptr); +} void AnsNotificationBranchTest::TearDownTestCase() {} @@ -625,7 +653,6 @@ HWTEST_F(AnsNotificationBranchTest, RemoveNotifications_0200, Function | MediumT std::vector hashcodes; hashcodes.emplace_back(hashcode); int32_t removeReason = 1; - MockGetAnsManagerProxy(false); ErrCode ret = ansNotification->RemoveNotifications(hashcodes, removeReason); EXPECT_EQ(ret, ERR_ANS_SERVICE_NOT_CONNECTED); } @@ -645,8 +672,6 @@ HWTEST_F(AnsNotificationBranchTest, RemoveNotifications_0300, Function | MediumT std::vector hashcodes; hashcodes.emplace_back(hashcode); int32_t removeReason = 1; - MockGetAnsManagerProxy(true); - ansNotification->ansManagerProxy_ = new (std::nothrow) MockAnsManagerInterface(); ansNotification->RemoveNotifications(hashcodes, removeReason); } @@ -662,7 +687,6 @@ HWTEST_F(AnsNotificationBranchTest, RegisterPushCallback_0100, Function | Medium auto ansNotification = std::make_shared(); EXPECT_NE(ansNotification, nullptr); sptr pushCallback = nullptr; - MockGetAnsManagerProxy(false); sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); ErrCode ret = ansNotification->RegisterPushCallback(pushCallback, checkRequest); EXPECT_EQ(ret, ERR_ANS_SERVICE_NOT_CONNECTED); @@ -680,8 +704,6 @@ HWTEST_F(AnsNotificationBranchTest, RegisterPushCallback_0200, Function | Medium auto ansNotification = std::make_shared(); EXPECT_NE(ansNotification, nullptr); sptr pushCallback = nullptr; - MockGetAnsManagerProxy(true); - ansNotification->ansManagerProxy_ = new (std::nothrow) MockAnsManagerInterface(); sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); ansNotification->RegisterPushCallback(pushCallback, checkRequest); } @@ -697,7 +719,6 @@ HWTEST_F(AnsNotificationBranchTest, UnregisterPushCallback_0100, Function | Medi { auto ansNotification = std::make_shared(); EXPECT_NE(ansNotification, nullptr); - MockGetAnsManagerProxy(false); ErrCode ret = ansNotification->UnregisterPushCallback(); EXPECT_EQ(ret, ERR_ANS_SERVICE_NOT_CONNECTED); } @@ -713,8 +734,6 @@ HWTEST_F(AnsNotificationBranchTest, UnregisterPushCallback_0200, Function | Medi { auto ansNotification = std::make_shared(); EXPECT_NE(ansNotification, nullptr); - MockGetAnsManagerProxy(true); - ansNotification->ansManagerProxy_ = new (std::nothrow) MockAnsManagerInterface(); ansNotification->UnregisterPushCallback(); } @@ -841,7 +860,7 @@ HWTEST_F(AnsNotificationBranchTest, SetNotificationSlotFlagsAsBundle_0001, Funct ret = notification->GetNotificationSlotFlagsAsBundle(bundle, slotFlags); EXPECT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); } - + /* * @tc.name: PublishNotification_0001 * @tc.desc: PublishNotification @@ -851,7 +870,7 @@ HWTEST_F(AnsNotificationBranchTest, SetNotificationSlotFlagsAsBundle_0001, Funct HWTEST_F(AnsNotificationBranchTest, PublishNotification_0001, Function | MediumTest | Level1) { auto notification = std::make_shared(); - notification->ansManagerProxy_ = new (std::nothrow) MockAnsManagerInterface(); + MockGetAnsManagerProxy(new (std::nothrow) MockAnsManagerInterface()); NotificationRequest req; std::shared_ptr mediaContent = std::make_shared(); auto content = std::make_shared(mediaContent); diff --git a/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp b/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp index 2b59696a15f14d98c1037f02affc1e5aefe73898..0fa39133447ab400f99aa7201561ea7237d9384c 100644 --- a/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp @@ -1509,5 +1509,24 @@ HWTEST_F(AnsNotificationUnitTest, RegisterSwingCallback_0100, TestSize.Level1) EXPECT_EQ(res, ERR_ANS_SERVICE_NOT_CONNECTED); } #endif + +/* + * @tc.name: IsNeedSilentInDoNotDisturbMode_0100 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode. + * @tc.type: FUNC + */ +HWTEST_F(AnsNotificationUnitTest, IsNeedSilentInDoNotDisturbMode_0100, Function | MediumTest | Level1) +{ + MockWriteInterfaceToken(false); + sptr iremoteObjects = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObjects); + std::shared_ptr proxy = std::make_shared(iremoteObjects); + ASSERT_NE(nullptr, proxy); + ans_->GetAnsManagerProxy(); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ErrCode ret = ans_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ret, ERR_ANS_SERVICE_NOT_CONNECTED); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/mock_ans_notification.cpp b/frameworks/core/test/unittest/mock/mock_ans_manager_proxy.cpp old mode 100755 new mode 100644 similarity index 77% rename from frameworks/core/test/unittest/ans_notification_branch_test/mock_ans_notification.cpp rename to frameworks/core/test/unittest/mock/mock_ans_manager_proxy.cpp index fc40be3fe3b63b86a21ee16525fc5330a39ea41f..ebf00dd068892d445b8b53115fe612ce2ba06986 --- a/frameworks/core/test/unittest/ans_notification_branch_test/mock_ans_notification.cpp +++ b/frameworks/core/test/unittest/mock/mock_ans_manager_proxy.cpp @@ -1,37 +1,34 @@ -/* - * Copyright (c) 2023 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 "ans_notification.h" - -namespace { - bool g_mockGetAnsManagerProxy = true; -} - -void MockGetAnsManagerProxy(bool mockRet) -{ - g_mockGetAnsManagerProxy = mockRet; -} - -namespace OHOS { -namespace Notification { -sptr AnsNotification::GetAnsManagerProxy() -{ - if (g_mockGetAnsManagerProxy) { - return ansManagerProxy_; - } - return nullptr; -} -} // namespace Notification -} // namespace OHOS +/* + * Copyright (c) 2023 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 "ans_notification.h" + +namespace { + OHOS::sptr g_mockGetAnsManagerProxy = nullptr; +} + +void MockGetAnsManagerProxy(OHOS::sptr mockRet) +{ + g_mockGetAnsManagerProxy = mockRet; +} + +namespace OHOS { +namespace Notification { +sptr AnsNotification::GetAnsManagerProxy() +{ + return g_mockGetAnsManagerProxy; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/include/common.h b/frameworks/js/napi/include/common.h index dd34671452443715b1735c95e1ca8a9dfff46c3c..4ee85a84ccfb8bfba4e7fd9cd2cd705438bf11f4 100644 --- a/frameworks/js/napi/include/common.h +++ b/frameworks/js/napi/include/common.h @@ -29,10 +29,12 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -constexpr int32_t STR_MAX_SIZE = 200; -constexpr int32_t LONG_STR_MAX_SIZE = 1024; +constexpr int32_t STR_MAX_SIZE = 204; +constexpr int32_t LONG_STR_MAX_SIZE = 1028; constexpr uint8_t OPERATION_MAX_TYPE = 3; constexpr int32_t LONG_LONG_STR_MAX_SIZE = 25600; +constexpr int32_t COMMON_TEXT_SIZE = 3074; +constexpr int32_t SHORT_TEXT_SIZE = 1026; constexpr int8_t NO_ERROR = 0; constexpr int8_t ERROR = -1; constexpr uint8_t PARAM0 = 0; @@ -335,7 +337,7 @@ public: * @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); + const napi_env &env, NotificationSorting &sorting, napi_value &result); /** * @brief Sets a js object by specified NotificationSlot object @@ -1700,7 +1702,7 @@ public: * @return Returns a napi value with specified error object for callback */ static napi_value CreateErrorValue(napi_env env, int32_t errCode, std::string &msg); - + /** * @brief Sets a js object by specified BadgeNumberCallbackData object * @@ -1722,6 +1724,19 @@ public: */ static napi_value GetNotificationBundleOption( const napi_env &env, const napi_value &value, NotificationRequest &request); + /** + * @brief Sets a js object by specified NotificationDoNotDisturbProfile object + * + * @param env Indicates the environment that the API is invoked under + * @param date Indicates a NotificationDoNotDisturbProfile 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 SetDoNotDisturbProfile( + const napi_env &env, const NotificationDoNotDisturbProfile &data, napi_value &result); + + static napi_value SetBundleOption( + const napi_env &env, const NotificationBundleOption &bundleInfo, napi_value &result); static bool IsValidRemoveReason(int32_t reasonType); static void NapiThrow(napi_env env, int32_t errCode); static void NapiThrow(napi_env env, int32_t errCode, std::string &msg); diff --git a/frameworks/js/napi/include/disturb_mode.h b/frameworks/js/napi/include/disturb_mode.h index 31b784e560b592848b430701fbab25973ca68ea9..fd9d5b6620472009e151d7e09673d510804c4858 100644 --- a/frameworks/js/napi/include/disturb_mode.h +++ b/frameworks/js/napi/include/disturb_mode.h @@ -21,6 +21,11 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; +struct GetDoNotDisturbProfileParams { + int32_t profileId = INVALID_PROFILE_ID; + napi_ref callback = nullptr; +}; + struct SetDoNotDisturbDateParams { NotificationDoNotDisturbDate date; bool hasUserId = false; @@ -64,15 +69,24 @@ struct AsyncCallbackInfoSupportDoNotDisturb { CallbackPromiseInfo info; }; +struct AsyncCallbackInfoGetDoNotDisturbProfile { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + GetDoNotDisturbProfileParams params; + sptr data; + CallbackPromiseInfo info; +}; + napi_value SetDoNotDisturbDate(napi_env env, napi_callback_info info); napi_value GetDoNotDisturbDate(napi_env env, napi_callback_info info); napi_value SupportDoNotDisturbMode(napi_env env, napi_callback_info info); napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, SetDoNotDisturbDateParams ¶ms); napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetDoNotDisturbDateParams ¶ms); +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetDoNotDisturbProfileParams ¶ms); bool ParseProfilesParameters( const napi_env &env, const napi_callback_info &info, std::vector> &profiles); bool AnalyseTrustlist(const napi_env &env, const napi_value &value, sptr &profile); } // namespace NotificationNapi } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_INCLUDE_DISTURB_MODE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_INCLUDE_DISTURB_MODE_H diff --git a/frameworks/js/napi/include/manager/napi_disturb_mode.h b/frameworks/js/napi/include/manager/napi_disturb_mode.h index 4bf0af5b21e2008513bbb044c527f6dd11f8f7c4..716cfd74501cc65ca6e228d289558f5a0289046d 100644 --- a/frameworks/js/napi/include/manager/napi_disturb_mode.h +++ b/frameworks/js/napi/include/manager/napi_disturb_mode.h @@ -26,6 +26,7 @@ napi_value NapiGetDoNotDisturbDate(napi_env env, napi_callback_info info); napi_value NapiSupportDoNotDisturbMode(napi_env env, napi_callback_info info); napi_value NapiAddDoNotDisturbProfiles(napi_env env, napi_callback_info info); napi_value NapiRemoveDoNotDisturbProfiles(napi_env env, napi_callback_info info); +napi_value NapiGetDoNotDisturbProfile(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_DISTURB_MODE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_DISTURB_MODE_H diff --git a/frameworks/js/napi/include/manager/napi_enable_notification.h b/frameworks/js/napi/include/manager/napi_enable_notification.h index 294190d454dd86dd2a0dc71a2b228a8e94cd8292..65ee9f4dabc48c62c0784f1a655680e32a5a2fb1 100644 --- a/frameworks/js/napi/include/manager/napi_enable_notification.h +++ b/frameworks/js/napi/include/manager/napi_enable_notification.h @@ -33,7 +33,7 @@ napi_value NapiGetAllNotificationEnabledBundles(napi_env env, napi_callback_info napi_value ParseRequestEnableParameters(const napi_env &env, const napi_callback_info &info, IsEnableParams ¶ms); napi_value NapiIsNotificationEnabledSync(napi_env env, napi_callback_info info); bool CreateUIExtension(std::shared_ptr context, std::string &bundleName); -void SendDialogEvent(std::string &bundleName, int32_t code); +void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object); class ModalExtensionCallback { public: diff --git a/frameworks/js/napi/include/manager/napi_open_settings.h b/frameworks/js/napi/include/manager/napi_open_settings.h new file mode 100644 index 0000000000000000000000000000000000000000..925e03954837f55cf72ad4e70a4eee3388fd9a64 --- /dev/null +++ b/frameworks/js/napi/include/manager/napi_open_settings.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_OPEN_SETTINGS_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_OPEN_SETTINGS_H + +#include "common.h" +#include +#include "ui_content.h" +#include "ability.h" +#include "ability_context.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; +using JsAnsCallbackComplete = void(napi_env, void*); + +struct OpenSettingsParams { + std::shared_ptr context; +}; + +struct AsyncCallbackInfoOpenSettings { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + OpenSettingsParams params; + CallbackPromiseInfo info; +}; + +void NapiAsyncCompleteCallbackOpenSettings(napi_env env, void *data); +napi_value NapiOpenNotificationSettings(napi_env env, napi_callback_info info); +napi_value ParseOpenSettingsParameters(const napi_env &env, const napi_callback_info &info, OpenSettingsParams ¶ms); +bool CreateSettingsUIExtension(std::shared_ptr context, std::string &bundleName); +bool Init(napi_env env, AsyncCallbackInfoOpenSettings* callbackInfo, JsAnsCallbackComplete complete); +void ProcessStatusChanged(int32_t code); + +class SettingsModalExtensionCallback { +public: + SettingsModalExtensionCallback(); + ~SettingsModalExtensionCallback(); + void OnRelease(int32_t releaseCode); + void OnResult(int32_t resultCode, const OHOS::AAFwk::Want& result); + void OnReceive(const OHOS::AAFwk::WantParams& request); + void OnError(int32_t code, const std::string& name, const std::string &message); + void OnRemoteReady(const std::shared_ptr &uiProxy); + void OnDestroy(); + void SetSessionId(int32_t sessionId); + void SetBundleName(std::string bundleName); + void SetAbilityContext(std::shared_ptr abilityContext); + void ReleaseOrErrorHandle(int32_t code); + +private: + int32_t sessionId_ = 0; + std::string bundleName_; + std::shared_ptr abilityContext_; +}; +} // namespace NotificationNapi +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_OPEN_SETTINGS_H \ No newline at end of file diff --git a/frameworks/js/napi/include/subscribe.h b/frameworks/js/napi/include/subscribe.h index 17a1c917ff90d31befe3230a31e457a429551cc0..1f1a2771350352926561017196fafd1d68721bed 100644 --- a/frameworks/js/napi/include/subscribe.h +++ b/frameworks/js/napi/include/subscribe.h @@ -131,79 +131,47 @@ public: * @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 callback information by type. + * @brief Sets threadsafe_function. * - * @param type Indicates the type of callback. - * @param env Indicates the environment that the API is invoked under. - * @param ref Indicates the napi_ref of callback. * @param tsfn Indicates the napi_threadsafe_function of callback. */ - void SetCallbackInfo(const std::string &type, const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn); + void SetThreadSafeFunction(const napi_threadsafe_function &tsfn); private: void SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetDieCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetDieCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetDisturbDateCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetDisturbDateCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetDisturbChangedCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetDisturbChangedCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetEnabledNotificationCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetEnabledNotificationCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn); - void SetBadgeCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetBadgeCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetBadgeEnabledCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetBadgeEnabledCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetBatchCancelCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetBatchCancelCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - private: struct CallbackInfo { napi_env env = nullptr; napi_ref ref = nullptr; - napi_threadsafe_function tsfn = nullptr; }; - + napi_threadsafe_function tsfn_ = nullptr; CallbackInfo canceCallbackInfo_; CallbackInfo consumeCallbackInfo_; CallbackInfo updateCallbackInfo_; @@ -221,13 +189,13 @@ private: struct SubscriberInstancesInfo { napi_ref ref = nullptr; - SubscriberInstance *subscriber = nullptr; + std::shared_ptr subscriber = nullptr; }; struct AsyncCallbackInfoSubscribe { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; NotificationSubscribeInfo subscriberInfo; CallbackPromiseInfo info; }; @@ -236,19 +204,19 @@ static std::mutex mutex_; static thread_local std::vector subscriberInstances_; static std::mutex delMutex_; -static std::vector DeletingSubscriber; +static std::vector> DeletingSubscriber; bool HasNotificationSubscriber(const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo); bool AddSubscriberInstancesInfo(const napi_env &env, const SubscriberInstancesInfo &subscriberInfo); -bool DelSubscriberInstancesInfo(const napi_env &env, const SubscriberInstance *subscriber); +bool DelSubscriberInstancesInfo(const napi_env &env, const std::shared_ptr subscriber); -bool AddDeletingSubscriber(SubscriberInstance *subscriber); -void DelDeletingSubscriber(SubscriberInstance *subscriber); +bool AddDeletingSubscriber(std::shared_ptr subscriber); +void DelDeletingSubscriber(std::shared_ptr subscriber); napi_value Subscribe(napi_env env, napi_callback_info info); napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, - NotificationSubscribeInfo &subscriberInfo, SubscriberInstance *&subscriber, napi_ref &callback); + NotificationSubscribeInfo &subscriberInfo, std::shared_ptr &subscriber, napi_ref &callback); } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_INCLUDE_SUBSCRIBE_H diff --git a/frameworks/js/napi/include/unsubscribe.h b/frameworks/js/napi/include/unsubscribe.h index d3db0dfba5023ac5f95c28c79518e020cdd90bfe..6e9680ccda39c077c98b7f1367bded01a6978d79 100644 --- a/frameworks/js/napi/include/unsubscribe.h +++ b/frameworks/js/napi/include/unsubscribe.h @@ -25,12 +25,12 @@ using namespace OHOS::Notification; struct AsyncCallbackInfoUnsubscribe { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; CallbackPromiseInfo info; }; struct ParametersInfoUnsubscribe { - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; napi_ref callback = nullptr; }; diff --git a/frameworks/js/napi/src/common.cpp b/frameworks/js/napi/src/common.cpp index 5d7fbde1e93386b2aa6f929bb32180ad0a741a8e..d206f9fb091575785e9253095273704204584524 100644 --- a/frameworks/js/napi/src/common.cpp +++ b/frameworks/js/napi/src/common.cpp @@ -85,7 +85,7 @@ napi_value Common::SetNotificationSortingMap( return NapiGetBoolean(env, true); } -napi_value Common::SetNotificationSorting(const napi_env &env, const NotificationSorting &sorting, napi_value &result) +napi_value Common::SetNotificationSorting(const napi_env &env, NotificationSorting &sorting, napi_value &result) { ANS_LOGD("enter"); @@ -93,7 +93,7 @@ napi_value Common::SetNotificationSorting(const napi_env &env, const Notificatio napi_value slotResult = nullptr; napi_value value = nullptr; napi_create_object(env, &slotResult); - if (!SetNotificationSlot(env, sorting.GetSlot(), slotResult)) { + if (!sorting.GetSlot() || !SetNotificationSlot(env, *sorting.GetSlot(), slotResult)) { ANS_LOGE("SetNotificationSlot call failed"); return NapiGetBoolean(env, false); } @@ -1412,5 +1412,50 @@ napi_value Common::SetNotificationUnifiedGroupInfo( return NapiGetBoolean(env, true); } + +napi_value Common::SetBundleOption(const napi_env &env, const NotificationBundleOption &bundleInfo, + napi_value &result) +{ + napi_value value = nullptr; + // bundle: string + napi_create_string_utf8(env, bundleInfo.GetBundleName().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "bundle", value); + + // uid: uid_t + napi_create_int32(env, bundleInfo.GetUid(), &value); + napi_set_named_property(env, result, "uid", value); + return NapiGetBoolean(env, true); +} + +napi_value Common::SetDoNotDisturbProfile(const napi_env &env, const NotificationDoNotDisturbProfile &data, + napi_value &result) +{ + ANS_LOGD("enter"); + napi_value value = nullptr; + // id: number + napi_create_int32(env, data.GetProfileId(), &value); + napi_set_named_property(env, result, "id", value); + + // name: string + napi_create_string_utf8(env, data.GetProfileName().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "name", value); + + size_t count = 0; + napi_create_array(env, &value); + // trustList?: std::vector + for (auto bundleInfo : data.GetProfileTrustList()) { + napi_value bundleValue = nullptr; + napi_create_object(env, &bundleValue); + if (!Common::SetBundleOption(env, bundleInfo, bundleValue)) { + continue; + } + napi_set_element(env, value, count, bundleValue); + count++; + } + if (count > 0) { + napi_set_named_property(env, result, "trustlist", value); + } + return NapiGetBoolean(env, true); +} } // namespace NotificationNapi } // namespace OHOS diff --git a/frameworks/js/napi/src/common_convert_content.cpp b/frameworks/js/napi/src/common_convert_content.cpp index d6dcc0436602dd5e7f51decdb515dceae3f443f6..43edd2bf4a5415852ce5fbb0b3041e7966117851 100644 --- a/frameworks/js/napi/src/common_convert_content.cpp +++ b/frameworks/js/napi/src/common_convert_content.cpp @@ -544,7 +544,8 @@ napi_value Common::GetNotificationBasicContentDetailed( ANS_LOGD("enter"); bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; + char commonStr[COMMON_TEXT_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; // title: string @@ -553,13 +554,13 @@ napi_value Common::GetNotificationBasicContentDetailed( ANS_LOGE("Failed to get title from js."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, value, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property title is empty"); return nullptr; } - basicContent->SetTitle(str); - ANS_LOGD("normal::title = %{public}s", str); + basicContent->SetTitle(shortStr); + ANS_LOGD("normal::title = %{public}s", shortStr); // text: string value = AppExecFwk::GetPropertyValueByPropertyName(env, contentResult, "text", napi_string); @@ -567,13 +568,13 @@ napi_value Common::GetNotificationBasicContentDetailed( ANS_LOGE("Failed to get text from js."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, value, commonStr, COMMON_TEXT_SIZE - 1, &strLen)); + if (std::strlen(commonStr) == 0) { ANS_LOGE("Property text is empty"); return nullptr; } - basicContent->SetText(str); - ANS_LOGD("normal::text = %{public}s", str); + basicContent->SetText(commonStr); + ANS_LOGD("normal::text = %{public}s", commonStr); // additionalText?: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); @@ -583,9 +584,9 @@ napi_value Common::GetNotificationBasicContentDetailed( ANS_LOGE("Failed to get additionalText from js."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); - basicContent->SetAdditionalText(str); - ANS_LOGD("normal::additionalText = %{public}s", str); + NAPI_CALL(env, napi_get_value_string_utf8(env, value, commonStr, COMMON_TEXT_SIZE - 1, &strLen)); + basicContent->SetAdditionalText(commonStr); + ANS_LOGD("normal::additionalText = %{public}s", commonStr); } // lockScreenPicture?: pixelMap @@ -639,8 +640,8 @@ napi_value Common::GetNotificationLongTextContentDetailed( napi_valuetype valuetype = napi_undefined; napi_value longContentResult = nullptr; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; - char long_str[LONG_STR_MAX_SIZE + 1] = {0}; + char commonStr[COMMON_TEXT_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; if (GetNotificationBasicContentDetailed(env, contentResult, longContent) == nullptr) { @@ -659,13 +660,13 @@ napi_value Common::GetNotificationLongTextContentDetailed( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, long_str, LONG_STR_MAX_SIZE, &strLen)); - if (std::strlen(long_str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, commonStr, COMMON_TEXT_SIZE-1, &strLen)); + if (std::strlen(commonStr) == 0) { ANS_LOGE("Property longText is empty"); return nullptr; } - longContent->SetLongText(long_str); - ANS_LOGD("longText::longText = %{public}s", long_str); + longContent->SetLongText(commonStr); + ANS_LOGD("longText::longText = %{public}s", commonStr); // briefText: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); @@ -679,13 +680,13 @@ napi_value Common::GetNotificationLongTextContentDetailed( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property briefText is empty"); return nullptr; } - longContent->SetBriefText(str); - ANS_LOGD("longText::briefText = %{public}s", str); + longContent->SetBriefText(shortStr); + ANS_LOGD("longText::briefText = %{public}s", shortStr); // expandedTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); @@ -699,13 +700,13 @@ napi_value Common::GetNotificationLongTextContentDetailed( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property expandedTitle is empty"); return nullptr; } - longContent->SetExpandedTitle(str); - ANS_LOGD("longText::expandedTitle = %{public}s", str); + longContent->SetExpandedTitle(shortStr); + ANS_LOGD("longText::expandedTitle = %{public}s", shortStr); return NapiGetNull(env); } @@ -754,7 +755,7 @@ napi_value Common::GetNotificationPictureContentDetailed(const napi_env &env, napi_valuetype valuetype = napi_undefined; napi_value pictureContentResult = nullptr; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; if (GetNotificationBasicContentDetailed(env, contentResult, pictureContent) == nullptr) { @@ -773,12 +774,12 @@ napi_value Common::GetNotificationPictureContentDetailed(const napi_env &env, ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property briefText is empty"); return nullptr; } - pictureContent->SetBriefText(str); + pictureContent->SetBriefText(shortStr); // expandedTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); @@ -792,12 +793,12 @@ napi_value Common::GetNotificationPictureContentDetailed(const napi_env &env, ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property expandedTitle is empty"); return nullptr; } - pictureContent->SetExpandedTitle(str); + pictureContent->SetExpandedTitle(shortStr); // picture: image.PixelMap NAPI_CALL(env, napi_has_named_property(env, contentResult, "picture", &hasProperty)); @@ -1065,7 +1066,7 @@ napi_value Common::GetNotificationConversationalContentTitle( napi_valuetype valuetype = napi_undefined; napi_value conversationalContentResult = nullptr; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; // conversationTitle: string @@ -1080,9 +1081,10 @@ napi_value Common::GetNotificationConversationalContentTitle( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, conversationalContentResult, str, STR_MAX_SIZE - 1, &strLen)); - conversationalContent->SetConversationTitle(str); - ANS_LOGD("conversationTitle = %{public}s", str); + NAPI_CALL(env, napi_get_value_string_utf8( + env, conversationalContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + conversationalContent->SetConversationTitle(shortStr); + ANS_LOGD("conversationTitle = %{public}s", shortStr); return NapiGetNull(env); } @@ -1183,7 +1185,7 @@ napi_value Common::GetConversationalMessageBasicInfo(const napi_env &env, const napi_valuetype valuetype = napi_undefined; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; + char commonStr[COMMON_TEXT_SIZE] = {0}; size_t strLen = 0; std::string text; int64_t timestamp = 0; @@ -1202,9 +1204,9 @@ napi_value Common::GetConversationalMessageBasicInfo(const napi_env &env, const ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, textResult, str, STR_MAX_SIZE - 1, &strLen)); - text = str; - ANS_LOGI("conversationalMessage::text = %{public}s", str); + NAPI_CALL(env, napi_get_value_string_utf8(env, textResult, commonStr, COMMON_TEXT_SIZE - 1, &strLen)); + text = commonStr; + ANS_LOGI("conversationalMessage::text = %{public}s", commonStr); // timestamp: number NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "timestamp", &hasProperty)); @@ -1306,7 +1308,7 @@ napi_value Common::GetNotificationMultiLineContent( napi_value contentResult = nullptr; napi_value multiLineContentResult = nullptr; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; NAPI_CALL(env, napi_has_named_property(env, result, "multiLine", &hasProperty)); @@ -1344,13 +1346,13 @@ napi_value Common::GetNotificationMultiLineContent( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property briefText is empty"); return nullptr; } - multiLineContent->SetBriefText(str); - ANS_LOGD("multiLine: briefText = %{public}s", str); + multiLineContent->SetBriefText(shortStr); + ANS_LOGD("multiLine: briefText = %{public}s", shortStr); // longTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "longTitle", &hasProperty)); @@ -1364,13 +1366,13 @@ napi_value Common::GetNotificationMultiLineContent( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property longTitle is empty"); return nullptr; } - multiLineContent->SetExpandedTitle(str); - ANS_LOGD("multiLine: longTitle = %{public}s", str); + multiLineContent->SetExpandedTitle(shortStr); + ANS_LOGD("multiLine: longTitle = %{public}s", shortStr); // lines: Array NAPI_CALL(env, napi_has_named_property(env, contentResult, "lines", &hasProperty)); @@ -1396,7 +1398,7 @@ napi_value Common::GetNotificationMultiLineContentLines(const napi_env &env, con bool isArray = false; napi_valuetype valuetype = napi_undefined; napi_value multilines = nullptr; - char str[STR_MAX_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; uint32_t length = 0; @@ -1420,9 +1422,9 @@ napi_value Common::GetNotificationMultiLineContentLines(const napi_env &env, con ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, line, str, STR_MAX_SIZE - 1, &strLen)); - multiLineContent->AddSingleLine(str); - ANS_LOGI("multiLine: lines : addSingleLine = %{public}s", str); + NAPI_CALL(env, napi_get_value_string_utf8(env, line, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + multiLineContent->AddSingleLine(shortStr); + ANS_LOGI("multiLine: lines : addSingleLine = %{public}s", shortStr); } return NapiGetNull(env); diff --git a/frameworks/js/napi/src/common_convert_notification.cpp b/frameworks/js/napi/src/common_convert_notification.cpp index a847c411dc14bc1561a7f9d8fc0f803f8a1f5ee8..18dcdd45eae93f38b553551056aea094a7fef115 100644 --- a/frameworks/js/napi/src/common_convert_notification.cpp +++ b/frameworks/js/napi/src/common_convert_notification.cpp @@ -111,33 +111,18 @@ napi_value Common::SetNotification( napi_get_boolean(env, notification->IsFloatingIcon(), &value); napi_set_named_property(env, result, "isFloatingIcon", 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->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 creatorBundleName?: string + napi_create_string_utf8( + env, notification->GetBundleName().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->GetUserId(), &value); - napi_set_named_property(env, result, "creatorUserId", value); - } + // readonly creatorUserId?: number + napi_create_int32(env, notification->GetRecvUserId(), &value); + napi_set_named_property(env, result, "creatorUserId", value); // readonly creatorInstanceKey?: number napi_create_int32(env, notification->GetInstanceKey(), &value); @@ -171,6 +156,10 @@ napi_value Common::SetNotification( napi_create_string_utf8(env, notification->GetDeviceId().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "deviceId", value); + // notificationControlFlags?: number + napi_create_int32(env, notification->GetNotificationRequest().GetNotificationControlFlags(), &value); + napi_set_named_property(env, result, "notificationControlFlags", value); + return NapiGetBoolean(env, true); } diff --git a/frameworks/js/napi/src/common_utils.cpp b/frameworks/js/napi/src/common_utils.cpp index 74568771c0caf52930f7d2ccefb22e8129465c48..425dbc3642c7223b17598d82cf8f4a7999acb7be 100644 --- a/frameworks/js/napi/src/common_utils.cpp +++ b/frameworks/js/napi/src/common_utils.cpp @@ -49,6 +49,13 @@ static const std::unordered_map ERROR_CODE_MESSAGE { {ERROR_NO_MEMORY, "No memory space"}, {ERROR_BUNDLE_NOT_FOUND, "The specified bundle name was not found"}, {ERROR_NO_AGENT_SETTING, "There is no corresponding agent relationship configuration"}, + {ERROR_DIALOG_IS_POPPING, "Dialog is popping"}, + {ERROR_SETTING_WINDOW_EXIST, "The notification settings window is already displayed"}, + {ERROR_NO_PROFILE_TEMPLATE, "Not exit noNotDisturb profile template"}, + {ERROR_REPEAT_SET, "Repeat create or end"}, + {ERROR_NO_RIGHT, "No permission"}, + {ERROR_EXPIRED_NOTIFICATION, "Low update version"}, + {ERROR_NETWORK_UNREACHABLE, "Network unreachable"}, }; } @@ -313,7 +320,9 @@ int32_t Common::ErrorToExternal(uint32_t errCode) {ERR_ANS_PUSH_CHECK_FAILED, ERROR_NO_RIGHT}, {ERR_ANS_PUSH_CHECK_UNREGISTERED, ERROR_NO_RIGHT}, {ERR_ANS_PUSH_CHECK_NETWORK_UNREACHABLE, ERROR_NETWORK_UNREACHABLE}, - {ERR_ANS_NO_AGENT_SETTING, ERROR_NO_AGENT_SETTING} + {ERR_ANS_NO_AGENT_SETTING, ERROR_NO_AGENT_SETTING}, + {ERR_ANS_DIALOG_IS_POPPING, ERROR_DIALOG_IS_POPPING}, + {ERR_ANS_NO_PROFILE_TEMPLATE, ERROR_NO_PROFILE_TEMPLATE} }; int32_t ExternalCode = ERROR_INTERNAL_ERROR; diff --git a/frameworks/js/napi/src/disturb_mode.cpp b/frameworks/js/napi/src/disturb_mode.cpp index a16396568daf364af93f5bf1a41b373c81966e58..cc749d0ee24d3fa0b455515764db23e23487d4d6 100644 --- a/frameworks/js/napi/src/disturb_mode.cpp +++ b/frameworks/js/napi/src/disturb_mode.cpp @@ -550,5 +550,28 @@ napi_value SupportDoNotDisturbMode(napi_env env, napi_callback_info info) return promise; } } + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetDoNotDisturbProfileParams ¶ms) +{ + ANS_LOGD("ParseParameters"); + + size_t argc = DISTURB_PROFILES_PARA; + napi_value argv[DISTURB_PROFILES_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + // argv[0]: profileId + napi_valuetype valuetype = napi_undefined; + if (argc >= DISTURB_PROFILES_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if (valuetype != napi_number) { + ANS_LOGW("Wrong argument type Excute promise."); + return Common::NapiGetNull(env); + } + NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM0], ¶ms.profileId)); + } + + return Common::NapiGetNull(env); +} } // namespace NotificationNapi } // namespace OHOS diff --git a/frameworks/js/napi/src/manager/BUILD.gn b/frameworks/js/napi/src/manager/BUILD.gn index 1c80f6904a652d16bb34909f03e0f8f5bd693e99..3cfda893b7af5a4cc5b1f1ba6c9cca4be73aace7 100644 --- a/frameworks/js/napi/src/manager/BUILD.gn +++ b/frameworks/js/napi/src/manager/BUILD.gn @@ -84,6 +84,7 @@ ohos_shared_library("notificationmanager") { "napi_enable_notification.cpp", "napi_get_active.cpp", "napi_local_live_view.cpp", + "napi_open_settings.cpp", "napi_publish.cpp", "napi_push.cpp", "napi_push_callback.cpp", diff --git a/frameworks/js/napi/src/manager/init_module.cpp b/frameworks/js/napi/src/manager/init_module.cpp index 5f6860ccdae00c0e45c5a84b3bae203841628e91..0468d5b6995c9c0b4278cbe6e57caab803c2a510 100644 --- a/frameworks/js/napi/src/manager/init_module.cpp +++ b/frameworks/js/napi/src/manager/init_module.cpp @@ -34,6 +34,7 @@ #include "napi_local_live_view.h" #include "napi_distributed_enable.h" #include "napi_sync_config.h" +#include "napi_open_settings.h" namespace OHOS { namespace NotificationNapi { @@ -120,6 +121,8 @@ napi_value NotificationManagerInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getSlotByBundle", NapiGetSlotByBundle), DECLARE_NAPI_FUNCTION("setAdditionalConfig", NapiSetAdditionConfig), DECLARE_NAPI_FUNCTION("isNotificationEnabledSync", NapiIsNotificationEnabledSync), + DECLARE_NAPI_FUNCTION("openNotificationSettings", NapiOpenNotificationSettings), + DECLARE_NAPI_FUNCTION("getDoNotDisturbProfile", NapiGetDoNotDisturbProfile), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/frameworks/js/napi/src/manager/napi_cancel.cpp b/frameworks/js/napi/src/manager/napi_cancel.cpp index 87e969de08a2715ce1fde7644dff93f7f6ca0fde..198307c68eb1e20e3f65f530f884207f2d5a8f3a 100644 --- a/frameworks/js/napi/src/manager/napi_cancel.cpp +++ b/frameworks/js/napi/src/manager/napi_cancel.cpp @@ -38,6 +38,7 @@ napi_value NapiCancel(napi_env env, napi_callback_info info) .hasOption = paras.hasOption }; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, paras.callback); } napi_value promise = nullptr; @@ -103,6 +104,7 @@ napi_value NapiCancelAll(napi_env env, napi_callback_info info) auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoCancel {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -162,6 +164,7 @@ napi_value NapiCancelGroup(napi_env env, napi_callback_info info) AsyncCallbackInfoCancelGroup *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoCancelGroup {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -230,6 +233,7 @@ napi_value NapiCancelAsBundle(napi_env env, napi_callback_info info) .hasOption = paras.hasOption }; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, paras.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_display_badge.cpp b/frameworks/js/napi/src/manager/napi_display_badge.cpp index a48f94a3a41ceb16c189314eaf63441a79d42ec2..17e4c0bd8cffb62981f69fa12d889f8a63ef5313 100644 --- a/frameworks/js/napi/src/manager/napi_display_badge.cpp +++ b/frameworks/js/napi/src/manager/napi_display_badge.cpp @@ -36,6 +36,7 @@ napi_value NapiDisplayBadge(napi_env env, napi_callback_info info) AsyncCallbackInfoEnableBadge *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoEnableBadge {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -123,6 +124,7 @@ napi_value NapiIsBadgeDisplayed(napi_env env, napi_callback_info info) AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoIsDisplayBadge {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -197,7 +199,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); if (valuetype != napi_number) { ANS_LOGE("Wrong argument type. Number expected."); - std::string msg = "Incorrect parameter types.The type of param must be number."; + std::string msg = "Incorrect parameter types.The type of badgeNumber must be number."; Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } @@ -207,7 +209,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // case2: setBadgeNumber(badgeNumber) if (valuetype != napi_number) { ANS_LOGW("Wrong argument type. Number expected."); - std::string msg = "Incorrect parameter types.The type of param must be object."; + std::string msg = "Incorrect parameter types.The type of badgeNumber must be number."; Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } @@ -319,7 +321,7 @@ napi_value NapiSetBadgeNumberByBundle(napi_env env, napi_callback_info info) ANS_LOGD("Napi set badge number by bundle work execute."); AsyncCallbackSetBadgeNumber *asyncCallbackInfo = static_cast(data); if (asyncCallbackInfo) { - ANS_LOGD("Option.bundle = %{public}s, option.uid = %{public}d, badge number = %{public}d.", + ANS_LOGI("Option.bundle = %{public}s, option.uid = %{public}d, badge number = %{public}d.", asyncCallbackInfo->params.option.GetBundleName().c_str(), asyncCallbackInfo->params.option.GetUid(), asyncCallbackInfo->params.badgeNumber); diff --git a/frameworks/js/napi/src/manager/napi_distributed.cpp b/frameworks/js/napi/src/manager/napi_distributed.cpp index 83eb203745282822b890f229df95451d4ab293c1..0b9b3092e24938e327421659eebdf064d0f21dc5 100644 --- a/frameworks/js/napi/src/manager/napi_distributed.cpp +++ b/frameworks/js/napi/src/manager/napi_distributed.cpp @@ -111,6 +111,7 @@ napi_value NapiEnableDistributed(napi_env env, napi_callback_info info) new (std::nothrow) AsyncCallbackInfoEnabled {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { ANS_LOGD("Create asyncCallbackinfo fail."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -327,6 +328,7 @@ napi_value NapiIsDistributedEnableByBundle(napi_env env, napi_callback_info info AsyncCallbackInfoIsEnabledByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoIsEnabledByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -413,6 +415,7 @@ napi_value NapiGetDeviceRemindType(napi_env env, napi_callback_info info) auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetRemindType {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -461,6 +464,7 @@ napi_value NapiSetSyncNotificationEnabledWithoutApp(napi_env env, napi_callback_ AsyncCallbackInfoEnabledWithoutApp *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoEnabledWithoutApp {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -526,6 +530,7 @@ napi_value NapiGetSyncNotificationEnabledWithoutApp(napi_env env, napi_callback_ new (std::nothrow) AsyncCallbackInfoGetEnabledWithoutApp { .env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_distributed_enable.cpp b/frameworks/js/napi/src/manager/napi_distributed_enable.cpp index 51201d61cb92de613278119a268c1f5f307a76fd..05d9b172be7f8bb4897f0b60136dc141c6f5bd7d 100644 --- a/frameworks/js/napi/src/manager/napi_distributed_enable.cpp +++ b/frameworks/js/napi/src/manager/napi_distributed_enable.cpp @@ -44,7 +44,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); if (valuetype != napi_object) { ANS_LOGW("Parameter type error. Object expected."); - std::string msg = "Incorrect parameter types.The type of param must be object."; + std::string msg = "Incorrect parameter types.The type of bundleOption must be object."; Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } @@ -58,8 +58,8 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[1]: deviceType NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); if (valuetype != napi_string) { - ANS_LOGW("Wrong argument type. Bool expected."); - std::string msg = "Incorrect parameter types.The type of param must be boolean."; + ANS_LOGW("Wrong argument type.String expected."); + std::string msg = "Incorrect parameter types.The type of deviceType must be string."; Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } @@ -120,6 +120,7 @@ napi_value NapiSetDistributedEnabledByBundle(napi_env env, napi_callback_info in AsyncCallbackDistributedEnable *asynccallbackinfo = new (std::nothrow) AsyncCallbackDistributedEnable {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, nullptr); } napi_value promise = nullptr; @@ -230,6 +231,7 @@ napi_value NapiSetSmartReminderEnabled(napi_env env, napi_callback_info info) AsyncCallbackSmartReminderEnabled *asynccallbackinfo = new (std::nothrow) AsyncCallbackSmartReminderEnabled {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, nullptr); } napi_value promise = nullptr; @@ -298,6 +300,7 @@ napi_value NapiIsSmartReminderEnabled(napi_env env, napi_callback_info info) AsyncCallbackSmartReminderEnabled *asynccallbackinfo = new (std::nothrow) AsyncCallbackSmartReminderEnabled {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, nullptr); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_disturb_mode.cpp b/frameworks/js/napi/src/manager/napi_disturb_mode.cpp index b37508f04e430af7ac0ad2a8b938b50d4273ed75..15252415db2b0586309a4fc4512dc4f90726c8c7 100644 --- a/frameworks/js/napi/src/manager/napi_disturb_mode.cpp +++ b/frameworks/js/napi/src/manager/napi_disturb_mode.cpp @@ -32,6 +32,7 @@ napi_value NapiSetDoNotDisturbDate(napi_env env, napi_callback_info info) AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoSetDoNotDisturb {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -96,6 +97,7 @@ napi_value NapiAddDoNotDisturbProfiles(napi_env env, napi_callback_info info) AsyncCallbackInfoDoNotDisturbProfile *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoDoNotDisturbProfile{.env = env, .asyncWork = nullptr, .profiles = profiles}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, nullptr); } napi_value promise = nullptr; @@ -141,6 +143,7 @@ napi_value NapiRemoveDoNotDisturbProfiles(napi_env env, napi_callback_info info) AsyncCallbackInfoDoNotDisturbProfile *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoDoNotDisturbProfile{.env = env, .asyncWork = nullptr, .profiles = profiles}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, nullptr); } napi_value promise = nullptr; @@ -214,6 +217,7 @@ napi_value NapiGetDoNotDisturbDate(napi_env env, napi_callback_info info) AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetDoNotDisturb {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -273,6 +277,7 @@ napi_value NapiSupportDoNotDisturbMode(napi_env env, napi_callback_info info) .env = env, .asyncWork = nullptr, .callback = callback}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -326,5 +331,86 @@ napi_value NapiSupportDoNotDisturbMode(napi_env env, napi_callback_info info) return promise; } } + +void AsyncCompleteCallbackNapiGetDoNotDisturbProfile(napi_env env, napi_status status, void *data) +{ + ANS_LOGD("GetDoNotDisturbProfile complete enter"); + if (!data) { + ANS_LOGE("Invalid async callback data."); + return; + } + napi_value result = nullptr; + auto asynccallbackinfo = reinterpret_cast(data); + if (asynccallbackinfo == nullptr) { + return; + } + + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + if (asynccallbackinfo->data != nullptr) { + napi_create_object(env, &result); + if (!Common::SetDoNotDisturbProfile(env, *asynccallbackinfo->data, result)) { + asynccallbackinfo->info.errorCode = ERROR; + result = Common::NapiGetNull(env); + } + } + } + Common::CreateReturnValue(env, asynccallbackinfo->info, result); + if (asynccallbackinfo->info.callback != nullptr) { + ANS_LOGD("Delete getDoNotDisturbProfile callback reference."); + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; +} + +napi_value NapiGetDoNotDisturbProfile(napi_env env, napi_callback_info info) +{ + ANS_LOGD("NapiGetDoNotDisturbProfile enter"); + GetDoNotDisturbProfileParams params {}; + if (ParseParameters(env, info, params) == nullptr) { + Common::NapiThrow(env, ERROR_PARAM_INVALID); + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoGetDoNotDisturbProfile *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetDoNotDisturbProfile {.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); + 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, "getDoNotDisturbProfile", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGD("NapiGetDoNotDisturbProfile work excute."); + auto asynccallbackinfo = reinterpret_cast(data); + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = NotificationHelper::GetDoNotDisturbProfile( + asynccallbackinfo->params.profileId, asynccallbackinfo->data); + } + }, + AsyncCompleteCallbackNapiGetDoNotDisturbProfile, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + bool isCallback = asynccallbackinfo->info.isCallback; + napi_queue_async_work_with_qos(env, asynccallbackinfo->asyncWork, napi_qos_user_initiated); + + if (isCallback) { + ANS_LOGD("NapiGetDoNotDisturbProfile callback is nullptr."); + return Common::NapiGetNull(env); + } else { + return promise; + } +} } // namespace NotificationNapi } // namespace OHOS diff --git a/frameworks/js/napi/src/manager/napi_enable_notification.cpp b/frameworks/js/napi/src/manager/napi_enable_notification.cpp index 7b7f7ac7fdcacc6273509696186616cedbc7c676..dbc5533e42f35ae5e2322a15f026e22558ecffc7 100644 --- a/frameworks/js/napi/src/manager/napi_enable_notification.cpp +++ b/frameworks/js/napi/src/manager/napi_enable_notification.cpp @@ -23,9 +23,6 @@ #include "js_ans_dialog_callback.h" #include "common_event_manager.h" -constexpr int32_t CRASH_CODE = 2; -constexpr int32_t REMOVE_CODE = 3; - namespace OHOS { namespace NotificationNapi { const int IS_NOTIFICATION_ENABLE_MAX_PARA = 2; @@ -61,6 +58,7 @@ napi_value NapiEnableNotification(napi_env env, napi_callback_info info) AsyncCallbackInfoEnable *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoEnable {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -132,6 +130,7 @@ __attribute__((no_sanitize("cfi"))) napi_value NapiIsNotificationEnabled(napi_en new (std::nothrow) AsyncCallbackInfoIsEnable {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { ANS_LOGD("Asynccallbackinfo is nullptr."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -253,7 +252,7 @@ void NapiAsyncCompleteCallbackRequestEnableNotification(napi_env env, void *data napi_value NapiRequestEnableNotification(napi_env env, napi_callback_info info) { - ANS_LOGI("enter"); + ANS_LOGI("NapiRequestEnableNotification enter"); IsEnableParams params {}; if (ParseRequestEnableParameters(env, info, params) == nullptr) { Common::NapiThrow(env, ERROR_PARAM_INVALID); @@ -263,6 +262,7 @@ napi_value NapiRequestEnableNotification(napi_env env, napi_callback_info info) AsyncCallbackInfoIsEnable *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoIsEnable { .env = env, .params = params, .newInterface = true}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -300,7 +300,7 @@ napi_value NapiRequestEnableNotification(napi_env env, napi_callback_info info) asynccallbackinfo->info.errorCode = ERR_ANS_DIALOG_POP_SUCCEEDED; } else { asynccallbackinfo->info.errorCode = ERROR_INTERNAL_ERROR; - SendDialogEvent(bundleName, REMOVE_CODE); + NotificationHelper::RemoveEnableNotificationDialog(); } } else { ANS_LOGD("un stage mode"); @@ -382,11 +382,7 @@ napi_value ParseRequestEnableParameters(const napi_env &env, const napi_callback bool stageMode = false; napi_status status = OHOS::AbilityRuntime::IsStageContext(env, argv[PARAM0], stageMode); if (status == napi_ok && stageMode) { - auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]); - sptr callerToken = context->GetToken(); - params.context = context; - params.callerToken = callerToken; - params.hasCallerToken = true; + SetEnableParam(params, env, argv[PARAM0]); } else { ANS_LOGE("Only support stage mode"); std::string msg = "Incorrect parameter types.Only support stage mode."; @@ -454,6 +450,7 @@ napi_value NapiGetAllNotificationEnabledBundles(napi_env env, napi_callback_info new (std::nothrow) AsyncCallbackInfoEnableStatus{ .env = env, .asyncWork = nullptr }; if (asynccallbackinfo == nullptr) { ANS_LOGE("asynccallbackinfo is nullptr"); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::NapiGetUndefined(env); } napi_value promise = nullptr; @@ -566,26 +563,16 @@ bool CreateUIExtension(std::shared_ptr context, s return true; } -void SendDialogEvent(std::string &bundleName, int32_t code) +void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object) { - ANS_LOGD("SendDialogEvent start"); - if (bundleName.empty()) { - ANS_LOGE("SendDialogEvent bundleName is nullptr"); - return; - } - std::string action = "OnNotificationServiceDialogClicked"; - - EventFwk::Want want; - want.SetAction(action); - - EventFwk::CommonEventData commonData; - commonData.SetWant(want); - commonData.SetCode(code); - commonData.SetData(bundleName); - if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) { - ANS_LOGE("PublishCommonEvent failed"); - } - ANS_LOGD("SendDialogEvent end"); + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, object); + sptr callerToken = nullptr; + if (context != nullptr) { + callerToken = context->GetToken(); + } + params.context = context; + params.callerToken = callerToken; + params.hasCallerToken = true; } ModalExtensionCallback::ModalExtensionCallback() @@ -617,7 +604,7 @@ void ModalExtensionCallback::OnReceive(const AAFwk::WantParams& receive) */ void ModalExtensionCallback::OnRelease(int32_t releaseCode) { - ANS_LOGD("OnRelease"); + ANS_LOGI("OnRelease"); ReleaseOrErrorHandle(releaseCode); } @@ -628,7 +615,7 @@ void ModalExtensionCallback::OnError(int32_t code, const std::string& name, cons { ANS_LOGE("OnError, name = %{public}s, message = %{public}s", name.c_str(), message.c_str()); ReleaseOrErrorHandle(code); - SendDialogEvent(this->bundleName_, CRASH_CODE); + NotificationHelper::RemoveEnableNotificationDialog(); } /* diff --git a/frameworks/js/napi/src/manager/napi_get_active.cpp b/frameworks/js/napi/src/manager/napi_get_active.cpp index 7d73cf03b7b818dfdf21fc677a1072ca2476f268..4fc167a534832ab4f46a6d07f1d2b994664d816e 100644 --- a/frameworks/js/napi/src/manager/napi_get_active.cpp +++ b/frameworks/js/napi/src/manager/napi_get_active.cpp @@ -86,6 +86,7 @@ napi_value NapiGetAllActiveNotifications(napi_env env, napi_callback_info info) auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoActive {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { ANS_LOGD("Asynccallbackinfo is nullptr."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -183,6 +184,7 @@ napi_value NapiGetActiveNotifications(napi_env env, napi_callback_info info) auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoActive {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { ANS_LOGD("Create asynccallbackinfo failed."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_local_live_view.cpp b/frameworks/js/napi/src/manager/napi_local_live_view.cpp index 174b3da0f7b7771cc5585f8ddba914c325d4032d..4ba18a5e6b3b18b8787fe5d8e3e0bee69fa830af 100644 --- a/frameworks/js/napi/src/manager/napi_local_live_view.cpp +++ b/frameworks/js/napi/src/manager/napi_local_live_view.cpp @@ -165,11 +165,13 @@ napi_value NapiTriggerLocalLiveView(napi_env env, napi_callback_info info) .env = env, .asyncWork = nullptr, }; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } if (ParseTriggerParameters(env, info, asynccallbackinfo, callback) == nullptr) { Common::NapiThrow(env, ERROR_PARAM_INVALID); + delete asynccallbackinfo; return Common::NapiGetUndefined(env); } diff --git a/frameworks/js/napi/src/manager/napi_open_settings.cpp b/frameworks/js/napi/src/manager/napi_open_settings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cda74b8d73e60f3c68f87770cce5a7a86c1daa8a --- /dev/null +++ b/frameworks/js/napi/src/manager/napi_open_settings.cpp @@ -0,0 +1,403 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_open_settings.h" +#include +#include "napi_base_context.h" +#include "ans_inner_errors.h" + +namespace OHOS { +namespace NotificationNapi { +const int OPEN_NOTIFICATION_SETTINGS_MAX_PARA = 1; +static napi_env env_ = nullptr; +static AsyncCallbackInfoOpenSettings* callbackInfo_ = nullptr; +static JsAnsCallbackComplete* complete_ = nullptr; +static std::atomic isExist = false; + +void NapiAsyncCompleteCallbackOpenSettings(napi_env env, void *data) +{ + ANS_LOGD("enter NapiAsyncCompleteCallbackOpenSettings"); + if (data == nullptr) { + ANS_LOGE("Invalid async callback data."); + return; + } + auto* asynccallbackinfo = static_cast(data); + napi_value result = nullptr; + napi_get_undefined(env, &result); + int32_t errorCode = ERR_OK; + if (asynccallbackinfo->info.errorCode == ERROR_SETTING_WINDOW_EXIST) { + errorCode = ERROR_SETTING_WINDOW_EXIST; + } else { + errorCode = asynccallbackinfo->info.errorCode == + ERR_OK ? ERR_OK : Common::ErrorToExternal(asynccallbackinfo->info.errorCode); + } + if (asynccallbackinfo->info.isCallback) { + Common::SetCallback(env, asynccallbackinfo->info.callback, errorCode, result, true); + } else { + Common::SetPromise(env, asynccallbackinfo->info.deferred, errorCode, result, true); + } + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; +} + +napi_value NapiOpenNotificationSettings(napi_env env, napi_callback_info info) +{ + ANS_LOGD("NapiOpenNotificationSettings start"); + OpenSettingsParams params {}; + if (ParseOpenSettingsParameters(env, info, params) == nullptr) { + Common::NapiThrow(env, ERROR_PARAM_INVALID); + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoOpenSettings *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoOpenSettings { + .env = env, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, nullptr); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, nullptr, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "openNotificationSettings", NAPI_AUTO_LENGTH, &resourceName); + + auto createExtension = [](napi_env env, void* data) { + ANS_LOGD("enter"); + if (data == nullptr) { + ANS_LOGE("data is invalid"); + return; + } + auto* asynccallbackinfo = static_cast(data); + + if (asynccallbackinfo->params.context != nullptr) { + ANS_LOGD("stage mode"); + std::string bundleName {""}; + if (isExist.exchange(true)) { + ANS_LOGE("SettingsUIExtension existed"); + asynccallbackinfo->info.errorCode = ERROR_SETTING_WINDOW_EXIST; + return; + } + bool success = CreateSettingsUIExtension(asynccallbackinfo->params.context, bundleName); + if (success) { + asynccallbackinfo->info.errorCode = ERR_ANS_DIALOG_POP_SUCCEEDED; + } else { + asynccallbackinfo->info.errorCode = ERROR_INTERNAL_ERROR; + } + } else { + ANS_LOGD("un stage mode"); + } + ANS_LOGI("done, code is %{public}d.", asynccallbackinfo->info.errorCode); + }; + auto jsCb = [](napi_env env, napi_status status, void* data) { + ANS_LOGD("enter jsCb"); + auto* asynccallbackinfo = static_cast(data); + ErrCode errCode = asynccallbackinfo->info.errorCode; + if (errCode != ERR_ANS_DIALOG_POP_SUCCEEDED) { + ANS_LOGE("error, code is %{public}d.", errCode); + NapiAsyncCompleteCallbackOpenSettings(env, static_cast(asynccallbackinfo)); + isExist.store(false); + return; + } + if (!Init(env, asynccallbackinfo, NapiAsyncCompleteCallbackOpenSettings)) { + ANS_LOGE("error"); + asynccallbackinfo->info.errorCode = ERROR_INTERNAL_ERROR; + NapiAsyncCompleteCallbackOpenSettings(env, static_cast(asynccallbackinfo)); + return; + } + ANS_LOGD("jsCb end"); + }; + + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + createExtension, + jsCb, + static_cast(asynccallbackinfo), + &asynccallbackinfo->asyncWork); + + napi_queue_async_work_with_qos(env, asynccallbackinfo->asyncWork, napi_qos_user_initiated); + ANS_LOGD("NapiOpenNotificationSettings end"); + return promise; +} + +napi_value ParseOpenSettingsParameters(const napi_env &env, const napi_callback_info &info, OpenSettingsParams ¶ms) +{ + ANS_LOGD("enter"); + + size_t argc = OPEN_NOTIFICATION_SETTINGS_MAX_PARA; + napi_value argv[OPEN_NOTIFICATION_SETTINGS_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + if (argc == 0) { + return Common::NapiGetNull(env); + } + + // argv[0]: context + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if ((valuetype != napi_object) && (valuetype != napi_function)) { + ANS_LOGW("Wrong argument type. Function or object expected. Excute promise."); + return Common::NapiGetNull(env); + } + if (valuetype == napi_object) { + bool stageMode = false; + napi_status status = OHOS::AbilityRuntime::IsStageContext(env, argv[PARAM0], stageMode); + if (status == napi_ok && stageMode) { + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]); + sptr callerToken = context->GetToken(); + params.context = context; + } else { + ANS_LOGE("Only support stage mode"); + std::string msg = "Incorrect parameter types.Only support stage mode."; + Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); + return nullptr; + } + } + return Common::NapiGetNull(env); +} + +bool CreateSettingsUIExtension(std::shared_ptr context, std::string &bundleName) +{ + if (context == nullptr) { + ANS_LOGE("Get context failed"); + return false; + } + + std::shared_ptr abilityContext = + OHOS::AbilityRuntime::Context::ConvertTo(context); + if (abilityContext == nullptr) { + ANS_LOGE("abilityContext is null"); + return false; + } + auto uiContent = abilityContext->GetUIContent(); + if (uiContent == nullptr) { + ANS_LOGE("uiContent is null"); + return false; + } + + AAFwk::Want want; + std::string targetBundleName = "com.ohos.sceneboard"; + std::string targetAbilityName = "NotificationManangerUIExtensionAbility"; + want.SetElementName(targetBundleName, targetAbilityName); + + std::string typeKey = "ability.want.params.uiExtensionType"; + std::string typeValue = "sys/commonUI"; + want.SetParam(typeKey, typeValue); + + auto uiExtCallback = std::make_shared(); + uiExtCallback->SetAbilityContext(abilityContext); + uiExtCallback->SetBundleName(bundleName); + Ace::ModalUIExtensionCallbacks uiExtensionCallbacks = { + .onRelease = + std::bind(&SettingsModalExtensionCallback::OnRelease, uiExtCallback, std::placeholders::_1), + .onResult = std::bind(&SettingsModalExtensionCallback::OnResult, uiExtCallback, + std::placeholders::_1, std::placeholders::_2), + .onReceive = + std::bind(&SettingsModalExtensionCallback::OnReceive, uiExtCallback, std::placeholders::_1), + .onError = std::bind(&SettingsModalExtensionCallback::OnError, uiExtCallback, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), + .onRemoteReady = + std::bind(&SettingsModalExtensionCallback::OnRemoteReady, uiExtCallback, std::placeholders::_1), + .onDestroy = std::bind(&SettingsModalExtensionCallback::OnDestroy, uiExtCallback), + }; + + Ace::ModalUIExtensionConfig config; + config.isProhibitBack = true; + + int32_t sessionId = uiContent->CreateModalUIExtension(want, uiExtensionCallbacks, config); + ANS_LOGI("Create end, sessionId: %{public}d", sessionId); + if (sessionId == 0) { + ANS_LOGE("Create component failed, sessionId is 0"); + return false; + } + uiExtCallback->SetSessionId(sessionId); + return true; +} + +bool Init(napi_env env, AsyncCallbackInfoOpenSettings* callbackInfo, + JsAnsCallbackComplete complete) +{ + ANS_LOGD("enter JsAnsCallback::Init"); + if (env == nullptr || callbackInfo == nullptr || complete == nullptr) { + ANS_LOGE("invalid data"); + return false; + } + env_ = env; + callbackInfo_ = callbackInfo; + complete_ = complete; + return true; +} + +void ProcessStatusChanged(int32_t code) +{ + ANS_LOGD("enter"); + std::unique_ptr callbackInfo(callbackInfo_); + if (env_ == nullptr || callbackInfo == nullptr || complete_ == nullptr) { + ANS_LOGE("invalid data"); + return; + } + + callbackInfo->info.errorCode = code; + + uv_loop_s* loop = nullptr; + napi_get_uv_event_loop(env_, &loop); + if (loop == nullptr) { + ANS_LOGE("loop is nullptr"); + return; + } + + auto work = std::make_unique(); + struct WorkData { + decltype(env_) env = nullptr; + decltype(callbackInfo_) callbackInfo = nullptr; + decltype(complete_) complete = nullptr; + }; + auto workData = std::make_unique(); + workData->env = env_; + workData->callbackInfo = callbackInfo_; + workData->complete = complete_; + + work->data = static_cast(workData.get()); + auto jsCb = [](uv_work_t* work, int status) { + ANS_LOGD("enter ProcessStatusChanged jsCb"); + std::unique_ptr workSP(work); + if (work == nullptr || work->data == nullptr) { + ANS_LOGE("invalid data"); + return; + } + auto* data = static_cast(work->data); + std::unique_ptr dataSP(data); + std::unique_ptr callbackInfoSP(data->callbackInfo); + if (data->env == nullptr || + data->callbackInfo == nullptr || + data->complete == nullptr) { + return; + } + auto* callbackInfoPtr = callbackInfoSP.release(); + data->complete(data->env, static_cast(callbackInfoPtr)); + }; + + int ret = uv_queue_work_with_qos(loop, + work.get(), + [](uv_work_t *work) {}, + jsCb, + uv_qos_user_initiated); + if (ret != 0) { + ANS_LOGE("uv_queue_work failed"); + return; + } + callbackInfo.release(); + workData.release(); + work.release(); +} + +SettingsModalExtensionCallback::SettingsModalExtensionCallback() +{} + +SettingsModalExtensionCallback::~SettingsModalExtensionCallback() +{} + + +/* + * when UIExtensionAbility use terminateSelfWithResult + */ +void SettingsModalExtensionCallback::OnResult(int32_t resultCode, const AAFwk::Want& result) +{ + ANS_LOGD("OnResult"); +} + +/* + * when UIExtensionAbility send message to UIExtensionComponent + */ +void SettingsModalExtensionCallback::OnReceive(const AAFwk::WantParams& receive) +{ + ANS_LOGD("OnReceive"); +} + +/* + * when UIExtensionAbility disconnect or use terminate or process die + * releaseCode is 0 when process normal exit + */ +void SettingsModalExtensionCallback::OnRelease(int32_t releaseCode) +{ + ANS_LOGD("OnRelease"); + ReleaseOrErrorHandle(releaseCode); +} + +/* + * when UIExtensionComponent init or turn to background or destroy UIExtensionAbility occur error + */ +void SettingsModalExtensionCallback::OnError(int32_t code, const std::string& name, const std::string& message) +{ + ANS_LOGE("OnError, code = %{public}d,name = %{public}s, message = %{public}s", code, name.c_str(), message.c_str()); + ReleaseOrErrorHandle(code); + ProcessStatusChanged(code); +} + +/* + * when UIExtensionComponent connect to UIExtensionAbility, ModalUIExtensionProxy will init, + * UIExtensionComponent can send message to UIExtensionAbility by ModalUIExtensionProxy + */ +void SettingsModalExtensionCallback::OnRemoteReady(const std::shared_ptr& uiProxy) +{ + ANS_LOGI("OnRemoteReady"); + ProcessStatusChanged(0); +} + +/* + * when UIExtensionComponent destructed + */ +void SettingsModalExtensionCallback::OnDestroy() +{ + ANS_LOGI("OnDestroy"); + isExist.store(false); +} + + +void SettingsModalExtensionCallback::SetSessionId(int32_t sessionId) +{ + this->sessionId_ = sessionId; +} + +void SettingsModalExtensionCallback::SetBundleName(std::string bundleName) +{ + this->bundleName_ = bundleName; +} + +void SettingsModalExtensionCallback::SetAbilityContext( + std::shared_ptr abilityContext) +{ + this->abilityContext_ = abilityContext; +} + +void SettingsModalExtensionCallback::ReleaseOrErrorHandle(int32_t code) +{ + ANS_LOGD("ReleaseOrErrorHandle start"); + Ace::UIContent* uiContent = this->abilityContext_->GetUIContent(); + if (uiContent == nullptr) { + ANS_LOGE("uiContent is null"); + return; + } + uiContent->CloseModalUIExtension(this->sessionId_); + ANS_LOGD("ReleaseOrErrorHandle end"); + return; +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/manager/napi_publish.cpp b/frameworks/js/napi/src/manager/napi_publish.cpp index e65be6f77a557e3242fb4bb3e99bf07b4026a8fe..8d139fd4b6860994f3823488cde5ce4ec7f62f49 100644 --- a/frameworks/js/napi/src/manager/napi_publish.cpp +++ b/frameworks/js/napi/src/manager/napi_publish.cpp @@ -34,6 +34,7 @@ napi_value NapiPublish(napi_env env, napi_callback_info info) auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoPublish {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { ANS_LOGD("asynccallbackinfo is nullptr."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } asynccallbackinfo->request = params.request; @@ -157,6 +158,7 @@ napi_value NapiPublishAsBundle(napi_env env, napi_callback_info info) napi_value promise = nullptr; auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoPublish {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } diff --git a/frameworks/js/napi/src/manager/napi_push.cpp b/frameworks/js/napi/src/manager/napi_push.cpp index 5d6a27796d68ecdc59fc36fa34ed3da3f99a1953..e216dc2cf3c39af46fdf91fe02335bded6ffab49 100644 --- a/frameworks/js/napi/src/manager/napi_push.cpp +++ b/frameworks/js/napi/src/manager/napi_push.cpp @@ -43,13 +43,21 @@ void NapiPush::Finalizer(napi_env env, void *data, void *hint) napi_value NapiPush::RegisterPushCallback(napi_env env, napi_callback_info info) { NapiPush *me = CheckParamsAndGetThis(env, info); - return (me != nullptr) ? me->OnRegisterPushCallback(env, info) : nullptr; + if (me == nullptr) { + Common::NapiThrow(env, ERROR_PARAM_INVALID); + return nullptr; + } + return me->OnRegisterPushCallback(env, info); } napi_value NapiPush::UnregisterPushCallback(napi_env env, napi_callback_info info) { NapiPush *me = CheckParamsAndGetThis(env, info); - return (me != nullptr) ? me->OnUnregisterPushCallback(env, info) : nullptr; + if (me == nullptr) { + Common::NapiThrow(env, ERROR_PARAM_INVALID); + return nullptr; + } + return me->OnUnregisterPushCallback(env, info); } napi_value NapiPush::OnRegisterPushCallback(napi_env env, const napi_callback_info info) @@ -161,8 +169,6 @@ napi_value NapiPush::OnUnregisterPushCallback(napi_env env, const napi_callback_ } NotificationHelper::UnregisterPushCallback(); - delete jsPushCallBack_; - jsPushCallBack_ = nullptr; return undefined; } diff --git a/frameworks/js/napi/src/manager/napi_push_callback.cpp b/frameworks/js/napi/src/manager/napi_push_callback.cpp index 193784dce693c8bf8e7ad74e9fcde55e707305f1..066c6796ad7d2ff3cbe1892a57159da24128b226 100644 --- a/frameworks/js/napi/src/manager/napi_push_callback.cpp +++ b/frameworks/js/napi/src/manager/napi_push_callback.cpp @@ -133,7 +133,7 @@ int32_t JSPushCallBack::OnCheckNotification( AbilityRuntime::HandleEscape handleEscape(env_); std::string pkgName; - auto checkInfo = new (std::nothrow) NotificationCheckInfo {}; + auto checkInfo = std::make_shared(); checkInfo->ConvertJsonStringToValue(notificationData); NotificationConstant::SlotType outSlotType = static_cast(checkInfo->GetSlotType()); diff --git a/frameworks/js/napi/src/manager/napi_remove_group.cpp b/frameworks/js/napi/src/manager/napi_remove_group.cpp index 07845ea4727f5611d41a72f95900815089934c53..cf504b265c30560c8f57dd78e1583861f5771ba4 100644 --- a/frameworks/js/napi/src/manager/napi_remove_group.cpp +++ b/frameworks/js/napi/src/manager/napi_remove_group.cpp @@ -121,6 +121,7 @@ napi_value NapiRemoveGroupByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoRemoveGroupByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoRemoveGroupByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_slot.cpp b/frameworks/js/napi/src/manager/napi_slot.cpp index afdd235257ab97154ccde8cf58d665599255c3f4..df9d4aa0d48c7f9ac7d8aed65cb277644f64eb88 100644 --- a/frameworks/js/napi/src/manager/napi_slot.cpp +++ b/frameworks/js/napi/src/manager/napi_slot.cpp @@ -103,6 +103,7 @@ napi_value NapiAddSlots(napi_env env, napi_callback_info info) new (std::nothrow) AsyncCallbackInfoAddSlots {.env = env, .asyncWork = nullptr, .slots = paras.slots}; if (!asynccallbackinfo) { ANS_LOGD("Asynccallbackinfo is nullptr."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, paras.callback); } napi_value promise = nullptr; @@ -300,6 +301,7 @@ napi_value NapiGetSlotNumByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoGetSlotNumByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetSlotNumByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -502,6 +504,7 @@ napi_value NapiGetSlotsByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoGetSlotsByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetSlotsByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -580,6 +583,7 @@ napi_value NapiGetSlotByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoGetSlotByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetSlotByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -745,6 +749,7 @@ napi_value NapiEnableNotificationSlot(napi_env env, napi_callback_info info) AsyncCallbackInfoInfoEnableSlot *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoInfoEnableSlot {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -808,6 +813,7 @@ napi_value NapiIsEnableNotificationSlot(napi_env env, napi_callback_info info) AsyncCallbackInfoInfoIsEnableSlot *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoInfoIsEnableSlot {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -870,6 +876,7 @@ napi_value NapiSetSlotFlagsByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoSetSlotFlagsByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoSetSlotFlagsByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -930,6 +937,7 @@ napi_value NapiGetSlotFlagsByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoGetSlotFlagsByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetSlotFlagsByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_sync_config.cpp b/frameworks/js/napi/src/manager/napi_sync_config.cpp index 45860a3aeccca878781e732ee793bd3c96b4cc2b..c904849089543e863a6a246c02f2519ae997a1f8 100644 --- a/frameworks/js/napi/src/manager/napi_sync_config.cpp +++ b/frameworks/js/napi/src/manager/napi_sync_config.cpp @@ -127,6 +127,7 @@ napi_value NapiSetAdditionConfig(napi_env env, napi_callback_info info) .params = paras }; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, paras.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/publish.cpp b/frameworks/js/napi/src/publish.cpp index 74a187cd332ae7306ef8f0de4e4b2fee11d3d332..bc91f55536de4832dbf1af675313fc26c423435b 100644 --- a/frameworks/js/napi/src/publish.cpp +++ b/frameworks/js/napi/src/publish.cpp @@ -84,7 +84,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, if (valuetype == napi_number) { int32_t recvUserId = SUBSCRIBE_USER_INIT; NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM1], &recvUserId)); - params.request.SetReceiverUserId(recvUserId); + params.request.SetOwnerUserId(recvUserId); } else { napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } @@ -239,7 +239,6 @@ napi_value ParseShowOptions(const napi_env &env, const napi_callback_info &info, NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); if (argc == 0) { ANS_LOGW("Wrong number of arguments."); - Common::NapiThrow(env, ERROR_PARAM_INVALID, MANDATORY_PARAMETER_ARE_LEFT_UNSPECIFIED); return nullptr; } @@ -248,8 +247,6 @@ napi_value ParseShowOptions(const napi_env &env, const napi_callback_info &info, NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); if (valuetype != napi_object) { ANS_LOGW("Wrong argument type. Object expected."); - std::string msg = "Incorrect parameter types.The type of param must be object."; - Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } @@ -442,7 +439,7 @@ napi_value ParsePublishAsBundleParameters( NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); if (valuetype != napi_number) { ANS_LOGW("Wrong argument type. Number expected."); - std::string msg = "Incorrect parameter types.The type of param must be number."; + std::string msg = "Incorrect parameter types.The type of userId must be number."; Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index ee3b923d2339d7a7ebc8ee846e146f2f1763a2c8..7b24798403794bc4487197f2dfb7943239968d5d 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -15,6 +15,7 @@ #include "subscribe.h" #include "ans_inner_errors.h" +#include "inner_event.h" #include #include @@ -22,6 +23,7 @@ namespace OHOS { namespace NotificationNapi { 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"; @@ -36,6 +38,22 @@ const std::string BADGE_CHANGED = "OnBadgeChanged"; const std::string BADGE_ENABLED_CHANGED = "OnBadgeEnabledChanged"; const std::string BATCH_CANCEL = "onBatchCancel"; +enum class Type { + UNKNOWN, + CANCEL, + BATCH_CANCEL, + CONSUME, + UPDATE, + CONNECTED, + DIS_CONNECTED, + DIE, + DISTURB_DATE_CHANGE, + DISTURB_CHANGED, + ENABLE_NOTIFICATION_CHANGED, + BADGE_CHANGED, + BADGE_ENABLED_CHANGED +}; + struct NotificationReceiveDataWorker { napi_env env = nullptr; napi_ref ref = nullptr; @@ -48,7 +66,8 @@ struct NotificationReceiveDataWorker { int32_t deleteReason = 0; int32_t result = 0; int32_t disturbMode = 0; - SubscriberInstance *subscriber = nullptr; + std::shared_ptr subscriber = nullptr; + Type type; }; napi_value SetSubscribeCallbackData(const napi_env &env, @@ -126,6 +145,9 @@ SubscriberInstance::SubscriberInstance() SubscriberInstance::~SubscriberInstance() { + if (tsfn_ != nullptr) { + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); + } if (canceCallbackInfo_.ref != nullptr) { napi_delete_reference(canceCallbackInfo_.env, canceCallbackInfo_.ref); } @@ -207,9 +229,8 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrGetNotificationRequest().GetNotificationId()); - ANS_LOGI("OnCanceled sortingMap size = %{public}zu", sortingMap->GetKey().size()); - ANS_LOGI("OnCanceled deleteReason = %{public}d", deleteReason); + ANS_LOGI("OnCanceled NotificationKey = %{public}s. sortingMap size = %{public}zu. deleteReason = %{public}d", + request->GetKey().c_str(), sortingMap->GetKey().size(), deleteReason); NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); if (dataWorker == nullptr) { @@ -222,10 +243,11 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrdeleteReason = deleteReason; dataWorker->env = canceCallbackInfo_.env; dataWorker->ref = canceCallbackInfo_.ref; + dataWorker->type = Type::CANCEL; - napi_acquire_threadsafe_function(canceCallbackInfo_.tsfn); - napi_call_threadsafe_function(canceCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(canceCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnBatchCancel(napi_env env, napi_value jsCallback, void* context, void* data) @@ -287,7 +309,12 @@ void SubscriberInstance::OnBatchCanceled(const std::vectorGetKey().size()); ANS_LOGI("OnBatchCancel deleteReason = %{public}d", deleteReason); - + std::string notificationKeys = ""; + for (auto notification : requestList) { + notificationKeys.append(notification->GetKey()).append("-"); + } + ANS_LOGI("OnBatchCancel. cancel keys = %{public}s", notificationKeys.c_str()); + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); if (dataWorker == nullptr) { ANS_LOGE("DataWorker is nullptr."); @@ -298,10 +325,11 @@ void SubscriberInstance::OnBatchCanceled(const std::vectordeleteReason = deleteReason; dataWorker->env = batchCancelCallbackInfo_.env; dataWorker->ref = batchCancelCallbackInfo_.ref; + dataWorker->type = Type::BATCH_CANCEL; - napi_acquire_threadsafe_function(batchCancelCallbackInfo_.tsfn); - napi_call_threadsafe_function(batchCancelCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(batchCancelCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); return; } @@ -356,7 +384,7 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrGetNotificationRequest().GetAgentBundle() != nullptr) { - ANS_LOGD("OnConsumed NotificGetAgentBundle = %{public}s", - request->GetNotificationRequest().GetAgentBundle()->Dump().c_str()); - } else { - ANS_LOGD("OnConsumed NotificGetAgentBundle = null"); - } - ANS_LOGI("OnConsumed Notification key = %{public}s, sortingMap size = %{public}zu", - request->GetKey().c_str(), sortingMap->GetKey().size()); + auto notificationFlags = request->GetNotificationRequest().GetFlags(); + ANS_LOGI("OnConsumed Notification key = %{public}s, sortingMap size = %{public}zu, notificationFlag = %{public}s", + request->GetKey().c_str(), sortingMap->GetKey().size(), + notificationFlags == nullptr ? "null" : notificationFlags->Dump().c_str()); ANS_LOGD("OnConsumed Notification info is %{public}s", request->GetNotificationRequest().Dump().c_str()); NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); @@ -391,10 +414,10 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrsortingMap = sortingMap; dataWorker->env = consumeCallbackInfo_.env; dataWorker->ref = consumeCallbackInfo_.ref; - - napi_acquire_threadsafe_function(consumeCallbackInfo_.tsfn); - napi_call_threadsafe_function(consumeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(consumeCallbackInfo_.tsfn, napi_tsfn_release); + dataWorker->type = Type::CONSUME; + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnUpdate(napi_env env, napi_value jsCallback, void* context, void* data) @@ -449,10 +472,11 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr dataWorker->sortingMap = sortingMap; dataWorker->env = updateCallbackInfo_.env; dataWorker->ref = updateCallbackInfo_.ref; + dataWorker->type = Type::UPDATE; - napi_acquire_threadsafe_function(updateCallbackInfo_.tsfn); - napi_call_threadsafe_function(updateCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(updateCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnConnected(napi_env env, napi_value jsCallback, void* context, void* data) @@ -479,7 +503,7 @@ void SubscriberInstance::OnConnected() return; } - if (subscribeCallbackInfo_.tsfn == nullptr) { + if (tsfn_ == nullptr) { ANS_LOGI("subscribe tsfn is null"); return; } @@ -492,10 +516,11 @@ void SubscriberInstance::OnConnected() dataWorker->env = subscribeCallbackInfo_.env; dataWorker->ref = subscribeCallbackInfo_.ref; + dataWorker->type = Type::CONNECTED; - napi_acquire_threadsafe_function(subscribeCallbackInfo_.tsfn); - napi_call_threadsafe_function(subscribeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(subscribeCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnDisconnected(napi_env env, napi_value jsCallback, void* context, void* data) @@ -509,7 +534,7 @@ void ThreadSafeOnDisconnected(napi_env env, napi_value jsCallback, void* context } Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); - + DelSubscriberInstancesInfo(dataWorkerData->env, dataWorkerData->subscriber); delete dataWorkerData; dataWorkerData = nullptr; } @@ -523,7 +548,7 @@ void SubscriberInstance::OnDisconnected() return; } - if (unsubscribeCallbackInfo_.tsfn == nullptr) { + if (tsfn_ == nullptr) { ANS_LOGI("unsubscribe tsfn is null"); return; } @@ -536,12 +561,12 @@ void SubscriberInstance::OnDisconnected() dataWorker->env = unsubscribeCallbackInfo_.env; dataWorker->ref = unsubscribeCallbackInfo_.ref; - dataWorker->subscriber = this; + dataWorker->subscriber = std::static_pointer_cast(shared_from_this()); + dataWorker->type = Type::DIS_CONNECTED; - napi_acquire_threadsafe_function(unsubscribeCallbackInfo_.tsfn); - napi_call_threadsafe_function(unsubscribeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(unsubscribeCallbackInfo_.tsfn, napi_tsfn_abort); - DelSubscriberInstancesInfo(dataWorker->env, dataWorker->subscriber); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnDestroy(napi_env env, napi_value jsCallback, void* context, void* data) @@ -578,10 +603,11 @@ void SubscriberInstance::OnDied() dataWorker->env = dieCallbackInfo_.env; dataWorker->ref = dieCallbackInfo_.ref; + dataWorker->type = Type::DIE; - napi_acquire_threadsafe_function(dieCallbackInfo_.tsfn); - napi_call_threadsafe_function(dieCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(dieCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnDoNotDisturbDateChange(napi_env env, napi_value jsCallback, void* context, void* data) @@ -639,10 +665,11 @@ void SubscriberInstance::OnDoNotDisturbDateChange(const std::shared_ptrdate = *date; dataWorker->env = disturbDateCallbackInfo_.env; dataWorker->ref = disturbDateCallbackInfo_.ref; + dataWorker->type = Type::DISTURB_DATE_CHANGE; - napi_acquire_threadsafe_function(disturbDateCallbackInfo_.tsfn); - napi_call_threadsafe_function(disturbDateCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(disturbDateCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } @@ -659,10 +686,6 @@ void ThreadSafeOnDoNotDisturbChanged(napi_env env, napi_value jsCallback, void* napi_value result = nullptr; napi_handle_scope scope; napi_open_handle_scope(dataWorkerData->env, &scope); - if (scope == nullptr) { - ANS_LOGE("Scope is null"); - return; - } napi_create_object(dataWorkerData->env, &result); if (!Common::SetDoNotDisturbDate(dataWorkerData->env, dataWorkerData->date, result)) { @@ -699,10 +722,11 @@ void SubscriberInstance::onDoNotDisturbChanged(const std::shared_ptrdate = *date; dataWorker->env = disturbChangedCallbackInfo_.env; dataWorker->ref = disturbChangedCallbackInfo_.ref; + dataWorker->type = Type::DISTURB_CHANGED; - napi_acquire_threadsafe_function(disturbChangedCallbackInfo_.tsfn); - napi_call_threadsafe_function(disturbChangedCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(disturbChangedCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnEnabledNotificationChanged(napi_env env, napi_value jsCallback, void* context, void* data) @@ -759,10 +783,11 @@ void SubscriberInstance::OnEnabledNotificationChanged( dataWorker->callbackData = *callbackData; dataWorker->env = enabledNotificationCallbackInfo_.env; dataWorker->ref = enabledNotificationCallbackInfo_.ref; + dataWorker->type = Type::ENABLE_NOTIFICATION_CHANGED; - napi_acquire_threadsafe_function(enabledNotificationCallbackInfo_.tsfn); - napi_call_threadsafe_function(enabledNotificationCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(enabledNotificationCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnBadgeChanged(napi_env env, napi_value jsCallback, void* context, void* data) @@ -818,10 +843,11 @@ void SubscriberInstance::OnBadgeChanged( dataWorker->badge = *badgeData; dataWorker->env = setBadgeCallbackInfo_.env; dataWorker->ref = setBadgeCallbackInfo_.ref; + dataWorker->type = Type::BADGE_CHANGED; - napi_acquire_threadsafe_function(setBadgeCallbackInfo_.tsfn); - napi_call_threadsafe_function(setBadgeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(setBadgeCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnBadgeEnabledChanged(napi_env env, napi_value jsCallback, void* context, void* data) @@ -874,24 +900,22 @@ void SubscriberInstance::OnBadgeEnabledChanged( dataWorker->callbackData = *callbackData; dataWorker->env = setBadgeEnabledCallbackInfo_.env; dataWorker->ref = setBadgeEnabledCallbackInfo_.ref; + dataWorker->type = Type::BADGE_ENABLED_CHANGED; - napi_acquire_threadsafe_function(setBadgeEnabledCallbackInfo_.tsfn); - napi_call_threadsafe_function(setBadgeEnabledCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(setBadgeEnabledCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } -void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref) +void SubscriberInstance::SetThreadSafeFunction(const napi_threadsafe_function &tsfn) { - canceCallbackInfo_.env = env; - canceCallbackInfo_.ref = ref; + tsfn_ = tsfn; } -void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) +void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref) { canceCallbackInfo_.env = env; canceCallbackInfo_.ref = ref; - canceCallbackInfo_.tsfn = tsfn; } void SubscriberInstance::SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref) @@ -900,139 +924,60 @@ void SubscriberInstance::SetConsumeCallbackInfo(const napi_env &env, const napi_ consumeCallbackInfo_.ref = ref; } -void SubscriberInstance::SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - consumeCallbackInfo_.env = env; - consumeCallbackInfo_.ref = ref; - consumeCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref) { updateCallbackInfo_.env = env; updateCallbackInfo_.ref = ref; } -void SubscriberInstance::SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - updateCallbackInfo_.env = env; - updateCallbackInfo_.ref = ref; - updateCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref) { subscribeCallbackInfo_.env = env; subscribeCallbackInfo_.ref = ref; } -void SubscriberInstance::SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - subscribeCallbackInfo_.env = env; - subscribeCallbackInfo_.ref = ref; - subscribeCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref) { unsubscribeCallbackInfo_.env = env; unsubscribeCallbackInfo_.ref = ref; } -void SubscriberInstance::SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - unsubscribeCallbackInfo_.env = env; - unsubscribeCallbackInfo_.ref = ref; - unsubscribeCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetDieCallbackInfo(const napi_env &env, const napi_ref &ref) { dieCallbackInfo_.env = env; dieCallbackInfo_.ref = ref; } -void SubscriberInstance::SetDieCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - dieCallbackInfo_.env = env; - dieCallbackInfo_.ref = ref; - dieCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref) { disturbModeCallbackInfo_.env = env; disturbModeCallbackInfo_.ref = ref; } -void SubscriberInstance::SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - disturbModeCallbackInfo_.env = env; - disturbModeCallbackInfo_.ref = ref; - disturbModeCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetEnabledNotificationCallbackInfo(const napi_env &env, const napi_ref &ref) { enabledNotificationCallbackInfo_.env = env; enabledNotificationCallbackInfo_.ref = ref; } -void SubscriberInstance::SetEnabledNotificationCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - enabledNotificationCallbackInfo_.env = env; - enabledNotificationCallbackInfo_.ref = ref; - enabledNotificationCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetDisturbDateCallbackInfo(const napi_env &env, const napi_ref &ref) { disturbDateCallbackInfo_.env = env; disturbDateCallbackInfo_.ref = ref; } -void SubscriberInstance::SetDisturbDateCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - disturbDateCallbackInfo_.env = env; - disturbDateCallbackInfo_.ref = ref; - disturbDateCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetDisturbChangedCallbackInfo(const napi_env &env, const napi_ref &ref) { disturbChangedCallbackInfo_.env = env; disturbChangedCallbackInfo_.ref = ref; } -void SubscriberInstance::SetDisturbChangedCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - disturbChangedCallbackInfo_.env = env; - disturbChangedCallbackInfo_.ref = ref; - disturbChangedCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetBadgeCallbackInfo(const napi_env &env, const napi_ref &ref) { setBadgeCallbackInfo_.env = env; setBadgeCallbackInfo_.ref = ref; } -void SubscriberInstance::SetBadgeCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - setBadgeCallbackInfo_.env = env; - setBadgeCallbackInfo_.ref = ref; - setBadgeCallbackInfo_.tsfn = tsfn; -} void SubscriberInstance::SetBadgeEnabledCallbackInfo(const napi_env &env, const napi_ref &ref) { @@ -1040,29 +985,12 @@ void SubscriberInstance::SetBadgeEnabledCallbackInfo(const napi_env &env, const setBadgeEnabledCallbackInfo_.ref = ref; } -void SubscriberInstance::SetBadgeEnabledCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - setBadgeEnabledCallbackInfo_.env = env; - setBadgeEnabledCallbackInfo_.ref = ref; - setBadgeEnabledCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetBatchCancelCallbackInfo(const napi_env &env, const napi_ref &ref) { batchCancelCallbackInfo_.env = env; batchCancelCallbackInfo_.ref = ref; } -void SubscriberInstance::SetBatchCancelCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - batchCancelCallbackInfo_.env = env; - batchCancelCallbackInfo_.ref = ref; - batchCancelCallbackInfo_.tsfn = tsfn; -} - - void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref) { if (type == CONSUME) { @@ -1096,41 +1024,6 @@ void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string } } - -void SubscriberInstance::SetCallbackInfo(const std::string &type, const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - if (type == CONSUME) { - SetConsumeCallbackInfo(env, ref, tsfn); - } else if (type == CANCEL) { - SetCancelCallbackInfo(env, ref, tsfn); - } else if (type == UPDATE) { - SetUpdateCallbackInfo(env, ref, tsfn); - } else if (type == CONNECTED) { - SetSubscribeCallbackInfo(env, ref, tsfn); - } else if (type == DIS_CONNECTED) { - SetUnsubscribeCallbackInfo(env, ref, tsfn); - } else if (type == DIE) { - SetDieCallbackInfo(env, ref, tsfn); - } else if (type == DISTURB_MODE_CHANGE) { - SetDisturbModeCallbackInfo(env, ref, tsfn); - } else if (type == DISTURB_DATE_CHANGE) { - SetDisturbDateCallbackInfo(env, ref, tsfn); - } else if (type == DISTURB_CHANGED) { - SetDisturbChangedCallbackInfo(env, ref, tsfn); - } else if (type == ENABLE_NOTIFICATION_CHANGED) { - SetEnabledNotificationCallbackInfo(env, ref, tsfn); - } else if (type == BADGE_CHANGED) { - SetBadgeCallbackInfo(env, ref, tsfn); - } else if (type == BADGE_ENABLED_CHANGED) { - SetBadgeEnabledCallbackInfo(env, ref, tsfn); - } else if (type == BATCH_CANCEL) { - SetBatchCancelCallbackInfo(env, ref, tsfn); - } else { - ANS_LOGW("type is error"); - } -} - bool HasNotificationSubscriber(const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo) { std::lock_guard lock(mutex_); @@ -1152,6 +1045,52 @@ void ThreadFinished(napi_env env, void* data, [[maybe_unused]] void* context) ANS_LOGD("ThreadFinished"); } +void ThreadSafeCommon(napi_env env, napi_value jsCallback, void* context, void* data) +{ + ANS_LOGI("common thread safe start"); + auto dataWorkerData = reinterpret_cast(data); + switch (dataWorkerData->type) { + case Type::CANCEL: + ThreadSafeOnCancel(env, jsCallback, context, data); + break; + case Type::BATCH_CANCEL: + ThreadSafeOnBatchCancel(env, jsCallback, context, data); + break; + case Type::CONSUME: + ThreadSafeOnConsumed(env, jsCallback, context, data); + break; + case Type::UPDATE: + ThreadSafeOnUpdate(env, jsCallback, context, data); + break; + case Type::CONNECTED: + ThreadSafeOnConnected(env, jsCallback, context, data); + break; + case Type::DIS_CONNECTED: + ThreadSafeOnDisconnected(env, jsCallback, context, data); + break; + case Type::DIE: + ThreadSafeOnDestroy(env, jsCallback, context, data); + break; + case Type::DISTURB_DATE_CHANGE: + ThreadSafeOnDoNotDisturbDateChange(env, jsCallback, context, data); + break; + case Type::DISTURB_CHANGED: + ThreadSafeOnDoNotDisturbChanged(env, jsCallback, context, data); + break; + case Type::ENABLE_NOTIFICATION_CHANGED: + ThreadSafeOnEnabledNotificationChanged(env, jsCallback, context, data); + break; + case Type::BADGE_CHANGED: + ThreadSafeOnBadgeChanged(env, jsCallback, context, data); + break; + case Type::BADGE_ENABLED_CHANGED: + ThreadSafeOnBadgeEnabledChanged(env, jsCallback, context, data); + break; + default: + break; + } +} + napi_value GetNotificationSubscriber( const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo) { @@ -1160,7 +1099,7 @@ napi_value GetNotificationSubscriber( napi_valuetype valuetype = napi_undefined; napi_ref result = nullptr; - subscriberInfo.subscriber = new (std::nothrow) SubscriberInstance(); + subscriberInfo.subscriber = std::make_shared(); if (subscriberInfo.subscriber == nullptr) { ANS_LOGE("subscriber is null"); std::string msg = "Mandatory parameters are left unspecified. subscriber is null"; @@ -1170,6 +1109,13 @@ napi_value GetNotificationSubscriber( napi_create_reference(env, value, 1, &subscriberInfo.ref); + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "tsfn", NAPI_AUTO_LENGTH, &resourceName); + napi_threadsafe_function tsfn = nullptr; + napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, + ThreadFinished, nullptr, ThreadSafeCommon, &tsfn); + subscriberInfo.subscriber->SetThreadSafeFunction(tsfn); + // onConsume?:(data: SubscribeCallbackData) => void NAPI_CALL(env, napi_has_named_property(env, value, "onConsume", &hasProperty)); if (hasProperty) { @@ -1183,13 +1129,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnConsumed, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onConsume", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnConsumed, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(CONSUME, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, CONSUME, result); } // onCancel?:(data: SubscribeCallbackData) => void NAPI_CALL(env, napi_has_named_property(env, value, "onCancel", &hasProperty)); @@ -1204,13 +1144,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnCanceled, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onCancel", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnCancel, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(CANCEL, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, CANCEL, result); } // onUpdate?:(data: NotificationSortingMap) => void NAPI_CALL(env, napi_has_named_property(env, value, "onUpdate", &hasProperty)); @@ -1225,13 +1159,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnUpdate, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onUpdate", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnUpdate, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(UPDATE, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, UPDATE, result); } // onConnect?:() => void NAPI_CALL(env, napi_has_named_property(env, value, "onConnect", &hasProperty)); @@ -1246,13 +1174,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnConnected, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onConnect", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnConnected, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(CONNECTED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, CONNECTED, result); } // onDisconnect?:() => void NAPI_CALL(env, napi_has_named_property(env, value, "onDisconnect", &hasProperty)); @@ -1267,13 +1189,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDisConnect, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onDisconnect", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnDisconnected, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(DIS_CONNECTED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, DIS_CONNECTED, result); } // onDestroy?:() => void NAPI_CALL(env, napi_has_named_property(env, value, "onDestroy", &hasProperty)); @@ -1288,13 +1204,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDied, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onDestroy", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnDestroy, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(DIE, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, DIE, result); } // onDisturbModeChange?:(mode: notification.DoNotDisturbMode) => void NAPI_CALL(env, napi_has_named_property(env, value, "onDisturbModeChange", &hasProperty)); @@ -1325,13 +1235,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDisturbDateChanged, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onDoNotDisturbDateChange", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnDoNotDisturbDateChange, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(DISTURB_DATE_CHANGE, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, DISTURB_DATE_CHANGE, result); } // onDoNotDisturbChanged?:(mode: notificationManager.DoNotDisturbDate) => void @@ -1347,13 +1251,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDoNotDisturbChanged, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onDoNotDisturbChanged", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnDoNotDisturbChanged, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(DISTURB_CHANGED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, DISTURB_CHANGED, result); } // onEnabledNotificationChanged?:(data: notification.EnabledNotificationCallbackData) => void @@ -1369,13 +1267,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnEnabledNotificationChanged, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onEnabledNotificationChanged", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnEnabledNotificationChanged, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(ENABLE_NOTIFICATION_CHANGED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, ENABLE_NOTIFICATION_CHANGED, result); } // onBadgeChanged?:(data: BadgeNumberCallbackData) => void @@ -1391,13 +1283,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnBadgeChanged, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onBadgeChanged", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnBadgeChanged, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(BADGE_CHANGED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, BADGE_CHANGED, result); } // onBadgeEnabledChanged?:(data: EnabledNotificationCallbackData) => void @@ -1413,13 +1299,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnBadgeEnabledChanged, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onBadgeEnabledChanged", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnBadgeEnabledChanged, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(BADGE_ENABLED_CHANGED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, BADGE_ENABLED_CHANGED, result); } // onBatchCancel?:(data: Array) => void @@ -1435,13 +1315,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, onBatchCancel, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onBatchCancel", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnBatchCancel, &tsfn); - subscriberInfo.subscriber->SetCallbackInfo(BATCH_CANCEL, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, BATCH_CANCEL, result); } return Common::NapiGetNull(env); @@ -1464,31 +1338,33 @@ bool AddSubscriberInstancesInfo(const napi_env &env, const SubscriberInstancesIn return true; } -bool DelSubscriberInstancesInfo(const napi_env &env, const SubscriberInstance *subscriber) +bool DelSubscriberInstancesInfo(const napi_env &env, const std::shared_ptr subscriber) { ANS_LOGD("enter"); if (subscriber == nullptr) { ANS_LOGE("subscriber is null"); return false; } - - std::lock_guard lock(mutex_); - for (auto it = subscriberInstances_.begin(); it != subscriberInstances_.end(); ++it) { - if ((*it).subscriber == subscriber) { - if ((*it).ref != nullptr) { - napi_delete_reference(env, (*it).ref); + std::lock_guard lock(delMutex_); + auto iter = std::find(DeletingSubscriber.begin(), DeletingSubscriber.end(), subscriber); + if (iter != DeletingSubscriber.end()) { + DeletingSubscriber.erase(iter); + std::lock_guard lock(mutex_); + for (auto it = subscriberInstances_.begin(); it != subscriberInstances_.end(); ++it) { + if ((*it).subscriber == subscriber) { + if ((*it).ref != nullptr) { + napi_delete_reference(env, (*it).ref); + } + subscriberInstances_.erase(it); + return true; } - DelDeletingSubscriber((*it).subscriber); - delete (*it).subscriber; - (*it).subscriber = nullptr; - subscriberInstances_.erase(it); - return true; } } return false; } + napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, - NotificationSubscribeInfo &subscriberInfo, SubscriberInstance *&subscriber, napi_ref &callback) + NotificationSubscribeInfo &subscriberInfo, std::shared_ptr &subscriber, napi_ref &callback) { ANS_LOGD("enter"); @@ -1517,18 +1393,10 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, if (!HasNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo)) { if (GetNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo) == nullptr) { ANS_LOGE("NotificationSubscriber parse failed"); - if (subscriberInstancesInfo.subscriber) { - delete subscriberInstancesInfo.subscriber; - subscriberInstancesInfo.subscriber = nullptr; - } return nullptr; } if (!AddSubscriberInstancesInfo(env, subscriberInstancesInfo)) { ANS_LOGE("AddSubscriberInstancesInfo add failed"); - if (subscriberInstancesInfo.subscriber) { - delete subscriberInstancesInfo.subscriber; - subscriberInstancesInfo.subscriber = nullptr; - } return nullptr; } } @@ -1570,14 +1438,10 @@ napi_value Subscribe(napi_env env, napi_callback_info info) ANS_LOGD("enter"); napi_ref callback = nullptr; - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; NotificationSubscribeInfo subscriberInfo; if (ParseParameters(env, info, subscriberInfo, objectInfo, callback) == nullptr) { ANS_LOGD("ParseParameters is nullptr."); - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } return Common::NapiGetUndefined(env); } @@ -1586,10 +1450,6 @@ napi_value Subscribe(napi_env env, napi_callback_info info) }; if (!asynccallbackinfo) { ANS_LOGD("Asynccallbackinfo is nullptr."); - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -1656,7 +1516,7 @@ napi_value Subscribe(napi_env env, napi_callback_info info) } } -bool AddDeletingSubscriber(SubscriberInstance *subscriber) +bool AddDeletingSubscriber(std::shared_ptr subscriber) { std::lock_guard lock(delMutex_); auto iter = std::find(DeletingSubscriber.begin(), DeletingSubscriber.end(), subscriber); @@ -1668,7 +1528,7 @@ bool AddDeletingSubscriber(SubscriberInstance *subscriber) return true; } -void DelDeletingSubscriber(SubscriberInstance *subscriber) +void DelDeletingSubscriber(std::shared_ptr subscriber) { std::lock_guard lock(delMutex_); auto iter = std::find(DeletingSubscriber.begin(), DeletingSubscriber.end(), subscriber); diff --git a/frameworks/js/napi/src/subscribe/napi_remove.cpp b/frameworks/js/napi/src/subscribe/napi_remove.cpp index 5b5f53207e97f348fc77fdd840c85df750678027..e8e24f01c0654a3be2cdec21ce3036131a5383c3 100644 --- a/frameworks/js/napi/src/subscribe/napi_remove.cpp +++ b/frameworks/js/napi/src/subscribe/napi_remove.cpp @@ -72,6 +72,7 @@ napi_value NapiRemove(napi_env env, napi_callback_info info) } auto removeInfo = new (std::nothrow) AsyncCallbackInfoRemove {.env = env, .asyncWork = nullptr, .params = params}; if (!removeInfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -103,6 +104,7 @@ napi_value NapiRemoveAll(napi_env env, napi_callback_info info) AsyncCallbackInfoRemove *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoRemove {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/subscribe/napi_subscribe.cpp b/frameworks/js/napi/src/subscribe/napi_subscribe.cpp index 1d3bf9d58a9151239b0fd5d4e56d7f536693b83e..ef7d3910edcaece8c61d9f48a4aae1448ec37d56 100644 --- a/frameworks/js/napi/src/subscribe/napi_subscribe.cpp +++ b/frameworks/js/napi/src/subscribe/napi_subscribe.cpp @@ -18,6 +18,8 @@ #include "ans_inner_errors.h" #include "subscribe.h" #include "unsubscribe.h" +#include +#include namespace OHOS { namespace NotificationNapi { @@ -25,13 +27,9 @@ napi_value NapiSubscribe(napi_env env, napi_callback_info info) { ANS_LOGD("enter"); napi_ref callback = nullptr; - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; NotificationSubscribeInfo subscriberInfo; if (ParseParameters(env, info, subscriberInfo, objectInfo, callback) == nullptr) { - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } Common::NapiThrow(env, ERROR_PARAM_INVALID); return Common::NapiGetUndefined(env); } @@ -40,10 +38,7 @@ napi_value NapiSubscribe(napi_env env, napi_callback_info info) .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .subscriberInfo = subscriberInfo }; if (!asynccallbackinfo) { - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -65,15 +60,16 @@ napi_value NapiSubscribe(napi_env env, napi_callback_info info) if (asynccallbackinfo) { if (asynccallbackinfo->subscriberInfo.hasSubscribeInfo) { ANS_LOGI("Subscribe with NotificationSubscribeInfo"); - OHOS::Notification::NotificationSubscribeInfo subscribeInfo; - subscribeInfo.AddAppNames(asynccallbackinfo->subscriberInfo.bundleNames); - subscribeInfo.AddAppUserId(asynccallbackinfo->subscriberInfo.userId); - subscribeInfo.AddDeviceType(asynccallbackinfo->subscriberInfo.deviceType); + sptr subscribeInfo = + new (std::nothrow) OHOS::Notification::NotificationSubscribeInfo(); + subscribeInfo->AddAppNames(asynccallbackinfo->subscriberInfo.bundleNames); + subscribeInfo->AddAppUserId(asynccallbackinfo->subscriberInfo.userId); + subscribeInfo->AddDeviceType(asynccallbackinfo->subscriberInfo.deviceType); asynccallbackinfo->info.errorCode = - NotificationHelper::SubscribeNotification(*(asynccallbackinfo->objectInfo), subscribeInfo); + NotificationHelper::SubscribeNotification(asynccallbackinfo->objectInfo, subscribeInfo); } else { asynccallbackinfo->info.errorCode = - NotificationHelper::SubscribeNotification(*(asynccallbackinfo->objectInfo)); + NotificationHelper::SubscribeNotification(asynccallbackinfo->objectInfo); } } }, @@ -114,13 +110,9 @@ napi_value NapiSubscribeSelf(napi_env env, napi_callback_info info) { ANS_LOGD("enter"); napi_ref callback = nullptr; - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; NotificationSubscribeInfo subscriberInfo; if (ParseParameters(env, info, subscriberInfo, objectInfo, callback) == nullptr) { - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } Common::NapiThrow(env, ERROR_PARAM_INVALID); return Common::NapiGetUndefined(env); } @@ -129,10 +121,7 @@ napi_value NapiSubscribeSelf(napi_env env, napi_callback_info info) .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .subscriberInfo = subscriberInfo }; if (!asynccallbackinfo) { - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -153,7 +142,7 @@ napi_value NapiSubscribeSelf(napi_env env, napi_callback_info info) auto asynccallbackinfo = reinterpret_cast(data); if (asynccallbackinfo) { asynccallbackinfo->info.errorCode = - NotificationHelper::SubscribeNotificationSelf(*(asynccallbackinfo->objectInfo)); + NotificationHelper::SubscribeNotificationSelf(asynccallbackinfo->objectInfo); } }, [](napi_env env, napi_status status, void *data) { @@ -201,6 +190,7 @@ napi_value NapiUnsubscribe(napi_env env, napi_callback_info info) AsyncCallbackInfoUnsubscribe *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoUnsubscribe {.env = env, .asyncWork = nullptr, .objectInfo = paras.objectInfo}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, paras.callback); } napi_value promise = nullptr; @@ -226,7 +216,7 @@ napi_value NapiUnsubscribe(napi_env env, napi_callback_info info) bool ret = AddDeletingSubscriber(asynccallbackinfo->objectInfo); if (ret) { asynccallbackinfo->info.errorCode = - NotificationHelper::UnSubscribeNotification(*(asynccallbackinfo->objectInfo)); + NotificationHelper::UnSubscribeNotification(asynccallbackinfo->objectInfo); if (asynccallbackinfo->info.errorCode != ERR_OK) { DelDeletingSubscriber(asynccallbackinfo->objectInfo); } diff --git a/frameworks/test/moduletest/BUILD.gn b/frameworks/test/moduletest/BUILD.gn index 83c5b849c08d1dd22af218d7273aef9c43a9cce6..c37703db69c8720a60baf1f58438cbf156bab196 100644 --- a/frameworks/test/moduletest/BUILD.gn +++ b/frameworks/test/moduletest/BUILD.gn @@ -326,7 +326,7 @@ group("moduletest") { deps = [] deps += [ - ":ReminderAgentJsTest", + # ":ReminderAgentJsTest", # ":ans_fw_module_test", ":ans_innerkits_module_publish_test", diff --git a/frameworks/test/moduletest/ans_innerkits_module_setting_test.cpp b/frameworks/test/moduletest/ans_innerkits_module_setting_test.cpp index cea73bb09226153bb207fa7556085cf23df9ab9c..20b785ebc32e6d79caceaa1cad3fc51eb699532f 100644 --- a/frameworks/test/moduletest/ans_innerkits_module_setting_test.cpp +++ b/frameworks/test/moduletest/ans_innerkits_module_setting_test.cpp @@ -78,28 +78,9 @@ HWTEST_F(AnsInnerKitsModuleSettingTest, ANS_Interface_MT_NotificationSetting_001 bundleOption.SetBundleName("bundlename"); bundleOption.SetUid(CALLING_UID); GTEST_LOG_(INFO) << "BundleOption is:"< sound_ {nullptr}; std::vector vibrationStyle_ {}; + uint64_t autoDeletedTimerId_ {0}; friend class AdvancedNotificationService; friend class NotificationSlotFilter; diff --git a/interfaces/inner_api/notification_bundle_option.h b/interfaces/inner_api/notification_bundle_option.h index 56fd66a32a23c2fab5487f5adb81fff23cdd337a..cf31b0489ac9a84b11d84b22ff324c856b2f3181 100644 --- a/interfaces/inner_api/notification_bundle_option.h +++ b/interfaces/inner_api/notification_bundle_option.h @@ -77,6 +77,20 @@ public: */ int32_t GetInstanceKey() const; + /** + * @brief Sets the application index. + * + * @param uid Indicates the application index. + */ + void SetAppIndex(const int32_t appIndex); + + /** + * @brief Obtains the application index. + * + * @return Returns the application index. + */ + int32_t GetAppIndex() const; + /** * @brief Returns a string representation of the object. * @@ -129,6 +143,7 @@ private: std::string bundleName_ {}; int32_t uid_ {}; int32_t instanceKey_ {}; + int32_t appIndex_ = -1; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/inner_api/notification_capsule.h b/interfaces/inner_api/notification_capsule.h index 2b1ec578a4b988dbfb67a55e1a1010662bd9a9d2..a6dea0d22785e67bfa7c268ee858d24c4681bdb3 100644 --- a/interfaces/inner_api/notification_capsule.h +++ b/interfaces/inner_api/notification_capsule.h @@ -16,7 +16,7 @@ #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CAPSULE_H #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CAPSULE_H -#include "foundation/multimedia/image_framework/interfaces/innerkits/include/pixel_map.h" +#include "pixel_map.h" #include "notification_json_convert.h" #include "parcel.h" #include @@ -107,6 +107,7 @@ public: void ResetIcon(); private: + /** * @brief Read a NotificationConversationalMessage object from a Parcel. * @@ -124,4 +125,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CAPSULE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CAPSULE_H diff --git a/interfaces/inner_api/notification_constant.h b/interfaces/inner_api/notification_constant.h index d01c1afea847c4e61896417f40f6650140e36f2f..6f4de3f91f3326b0fa2eba7e628c9634781e8cde 100644 --- a/interfaces/inner_api/notification_constant.h +++ b/interfaces/inner_api/notification_constant.h @@ -65,6 +65,7 @@ public: LIVE_VIEW, // the notification type is live view CUSTOMER_SERVICE, // the notification type is customer service EMERGENCY_INFORMATION, // the notification type is emergency information + ILLEGAL_TYPE, // invalid type,it is used as the upper limit of the enumerated value }; enum ReminderFlag { @@ -74,6 +75,7 @@ public: LIGHTSCREEN_FLAG = 1 << 3, VIBRATION_FLAG = 1 << 4, STATUSBAR_ICON_FLAG = 1 << 5, + SA_SELF_BANNER_FLAG = 1 << 9, }; enum class VisiblenessType { @@ -93,7 +95,12 @@ public: /** * notifications are not displayed on the lock screen. */ - SECRET + SECRET, + /** + * invalid type + * It is used as the upper limit of the enumerated value. + */ + ILLEGAL_TYPE }; enum class DoNotDisturbType { @@ -285,6 +292,11 @@ public: */ static const int32_t SLOT_ENABLED_REASON_DELETE = 29; + /** + * Indicates that a notification is deleted because recover live live validated need delete. + */ + static const int32_t RECOVER_LIVE_VIEW_DELETE = 30; + /** * Indicates that a notification is deleted for other reasons. */ diff --git a/interfaces/inner_api/notification_content.h b/interfaces/inner_api/notification_content.h index 3d68945a8a7af4c24b23f5605dde20a76365facb..836c0e80d023b5f1e0a4f7bf451534aee9807bdf 100644 --- a/interfaces/inner_api/notification_content.h +++ b/interfaces/inner_api/notification_content.h @@ -75,7 +75,12 @@ public: * Indicates notifications that include a live view. * Such notifications are created using NotificationLiveViewContent. */ - LIVE_VIEW + LIVE_VIEW, + /** + * invalid type + * It is used as the upper limit of the enumerated value. + */ + ILLEGAL_TYPE }; /** diff --git a/interfaces/inner_api/notification_do_not_disturb_profile.h b/interfaces/inner_api/notification_do_not_disturb_profile.h index fbfc7144df7e99b0abb64e9a97578e5f19561d96..477cb63f35624bd219f264d65b9fc9319b1f00bb 100644 --- a/interfaces/inner_api/notification_do_not_disturb_profile.h +++ b/interfaces/inner_api/notification_do_not_disturb_profile.h @@ -104,6 +104,7 @@ public: static NotificationDoNotDisturbProfile *Unmarshalling(Parcel &parcel); std::string ToJson(); void FromJson(const std::string &value); + void GetProfileJson(nlohmann::json &jsonObject) const; private: int32_t id_; @@ -112,4 +113,4 @@ private: }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_DO_NOT_DISTURB_PROFILE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_DO_NOT_DISTURB_PROFILE_H diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index 6838448b224b25e0f1e915c506b91714a24d92a0..95a3d9c994070c36d2430f2ed3115b21c7548a2c 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -28,6 +28,7 @@ #include "notification_subscriber.h" #include "notification_local_live_view_subscriber.h" #include "want_params.h" +#include namespace OHOS { namespace Notification { @@ -135,6 +136,17 @@ public: */ static ErrCode PublishNotification(const NotificationRequest &request); + /** + * @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. + * + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns publish notification result. + */ + static ErrCode PublishNotificationForIndirectProxy(const NotificationRequest &request); + /** * @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, @@ -169,7 +181,7 @@ public: /** * @brief Cancels all the published notifications. * - * @note To cancel a specified notification, see CancelNotification(int_32). + * @note To cancel a specified notification, see CancelNotification(int32_t). * @return Returns cancel all notifications result. */ static ErrCode CancelAllNotifications(); @@ -299,6 +311,13 @@ public: */ static ErrCode CanPopEnableNotificationDialog(sptr &hostClient, bool &canPop, std::string &bundleName); + + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + static ErrCode RemoveEnableNotificationDialog(); /** * @brief Allow the current application to publish notifications on a specified device. @@ -337,26 +356,57 @@ public: * notification. To subscribe to notifications published only by specified sources, for example, * notifications from certain applications, * call the {SubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotification(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns unsubscribe notification result. */ static ErrCode SubscribeNotification(const NotificationSubscriber &subscriber); + /** + * @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. + * After the notification is published, subscribers that meet the filter criteria can receive the + * notification. To subscribe to notifications published only by specified sources, for example, + * notifications from certain applications, + * call the {SubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + static ErrCode SubscribeNotification(const std::shared_ptr &subscriber); + /** * @brief Subscribes to notifications from the appliaction self. * @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. * After the notification is published, subscribers that meet the filter criteria can receive the * notification. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotificationSelf(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns unsubscribe notification result. */ static ErrCode SubscribeNotificationSelf(const NotificationSubscriber &subscriber); + /** + * @brief Subscribes to notifications from the appliaction self. + * @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. + * After the notification is published, subscribers that meet the filter criteria can receive the + * notification. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + static ErrCode SubscribeNotificationSelf(const std::shared_ptr &subscriber); + /** * @brief Subscribes to all notifications based on the filtering criteria. This method can be called only * by applications with required system permissions. @@ -367,7 +417,9 @@ public: * After the notification is published, subscribers that meet the filter criteria can receive the * notification. To subscribe to and receive all notifications, call the * {SubscribeNotification(NotificationSubscriber)} method. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotification(const std::shared_ptr &subscriber, + * const sptr &subscribeInfo)'. * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. * For details, see {NotificationSubscriber}. * @param subscribeInfo Indicates the filters for specified notification sources, including application name, @@ -377,6 +429,26 @@ public: static ErrCode SubscribeNotification( const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo); + /** + * @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}. + * 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. + * After the notification is published, subscribers that meet the filter criteria can receive the + * notification. To subscribe to and receive all notifications, call the + * {SubscribeNotification(NotificationSubscriber)} method. + * + * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. + * For details, see {NotificationSubscriber}. + * @param subscribeInfo Indicates the filters for specified notification sources, including application name, + * user ID, or device name. This parameter is optional. + * @return Returns subscribe notification result. + */ + static ErrCode SubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo); + /** * @brief Subscribes the localLiveView button click. This method can be called only * by applications with required system permissions. @@ -401,18 +473,38 @@ public: * To unsubscribe from notifications published only by specified sources, for example, * notifications from certain applications, call the * {UnSubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. - * + * @deprecated This function is deprecated, + * use 'UnSubscribeNotification(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns unsubscribe notification result. */ static ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber); + /** + * @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 + * to receive a notification any longer, unsubscribe from that notification using this method. + * You can unsubscribe from only those notifications that your application has subscribed to. + * To unsubscribe from notifications published only by specified sources, for example, + * notifications from certain applications, call the + * {UnSubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + static ErrCode UnSubscribeNotification(const std::shared_ptr &subscriber); + /** * @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. - * + * @deprecated This function is deprecated, + * use 'UnSubscribeNotification(const std::shared_ptr &subscriber, + * const sptr &subscribeInfo)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @param subscribeInfo Indicates the filters for , including application name, @@ -421,6 +513,20 @@ public: */ static ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo); + /** + * @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. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @param subscribeInfo Indicates the filters for , including application name, + * user ID, or device name. This parameter is optional. + * @return Returns unsubscribe notification result. + */ + static ErrCode UnSubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo); + /** * @brief Trigger the local live view after the button has been clicked. * @note Your application must have platform signature to use this method. @@ -667,6 +773,14 @@ public: */ static ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + static ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType); + /** * @brief Check if the device supports distributed notification. * @@ -995,6 +1109,23 @@ public: * @return Returns register swing callback result. */ static ErrCode RegisterSwingCallback(const std::function swingCbFunc); + + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + static ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile); + + /** + * @brief Update Notification Timer by uid + * + * @param uid uid. + * @return Returns Update result. + */ + static ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused); }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/inner_api/notification_local_live_view_button.h b/interfaces/inner_api/notification_local_live_view_button.h index 70f38f0f6c48a2809c6970ff8207157b37b4f164..8f5f330822fd68122d96943fbb456fb2244c760e 100644 --- a/interfaces/inner_api/notification_local_live_view_button.h +++ b/interfaces/inner_api/notification_local_live_view_button.h @@ -16,8 +16,8 @@ #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_LOCAL_LIVE_VIEW_BUTTON_H #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_LOCAL_LIVE_VIEW_BUTTON_H -#include "base/notification/distributed_notification_service/interfaces/inner_api/notification_button_option.h" -#include "foundation/multimedia/image_framework/interfaces/innerkits/include/pixel_map.h" +#include "notification_button_option.h" +#include "pixel_map.h" #include "message_user.h" #include "notification_json_convert.h" #include "parcel.h" diff --git a/interfaces/inner_api/notification_local_live_view_content.h b/interfaces/inner_api/notification_local_live_view_content.h index 59c6b56627ac919d4239e0e7b00dff3b669f63e7..cd7c18e1c329f4ef3f301b4ec13c8d5257695acc 100644 --- a/interfaces/inner_api/notification_local_live_view_content.h +++ b/interfaces/inner_api/notification_local_live_view_content.h @@ -16,9 +16,9 @@ #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_LOCAL_LIVE_VIEW_CONTENT_H #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_LOCAL_LIVE_VIEW_CONTENT_H -#include "base/notification/distributed_notification_service/interfaces/inner_api/notification_capsule.h" -#include "base/notification/distributed_notification_service/interfaces/inner_api/notification_progress.h" -#include "base/notification/distributed_notification_service/interfaces/inner_api/notification_local_live_view_button.h" +#include "notification_capsule.h" +#include "notification_progress.h" +#include "notification_local_live_view_button.h" #include "message_user.h" #include "notification_basic_content.h" #include "notification_conversational_message.h" @@ -38,7 +38,7 @@ public: TIME, INITIAL_TIME, }; - + NotificationLocalLiveViewContent() = default; ~NotificationLocalLiveViewContent() = default; @@ -85,7 +85,7 @@ public: * @brief Sets the progress to be included in a local live view notification. * * @param progress Indicates the type to be included. - + */ void SetProgress(NotificationProgress progress); @@ -99,7 +99,7 @@ public: * @brief Sets the time to be included in a local live view notification. * * @param time Indicates the type to be included. - + */ void SetTime(NotificationTime time); @@ -113,7 +113,7 @@ public: * @add flag function. * * @param flag Indicates the flag to be added. - + */ void addFlag(int32_t flag); @@ -187,4 +187,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CONVERSATIONAL_CONTENT_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CONVERSATIONAL_CONTENT_H diff --git a/interfaces/inner_api/notification_request.h b/interfaces/inner_api/notification_request.h index 541f8529434e844b219a1884f67dc058e02a9b52..1e4b142e1c33b6323b186641675baf4ab218fcb9 100644 --- a/interfaces/inner_api/notification_request.h +++ b/interfaces/inner_api/notification_request.h @@ -38,6 +38,7 @@ namespace OHOS { namespace Notification { inline const std::string REQUEST_STORAGE_KEY_PREFIX {"ans_live_view"}; +inline const std::string REQUEST_STORAGE_SECURE_KEY_PREFIX {"secure_live_view"}; struct NotificationKey { int32_t id {}; @@ -64,7 +65,12 @@ public: /** * displayed as a small icon. */ - LITTLE + LITTLE, + /** + * invalid type + * It is used as the upper limit of the enumerated value. + */ + ILLEGAL_TYPE }; enum class GroupAlertType { @@ -82,7 +88,12 @@ public: * the overview notification has sound or vibration but child notifications are muted (no sound or vibration) * in a group if sound or vibration is enabled for the associated NotificationSlot objects. */ - OVERVIEW + OVERVIEW, + /** + * invalid type + * It is used as the upper limit of the enumerated value. + */ + ILLEGAL_TYPE }; /** @@ -507,6 +518,13 @@ public: */ const std::shared_ptr GetLittleIcon() const; + /** + * @brief Obtains the icon type of the notification. + * + * @return Returns the notification icon type + */ + const std::string GetLittleIconType() const; + /** * @brief Sets the large icon of this notification, which is usually displayed on the right of the notification. * @@ -514,6 +532,12 @@ public: */ void SetBigIcon(const std::shared_ptr &bigIcon); + /** + * @brief reset the large icon of this notification, which is usually displayed on the right of the notification. + * + */ + void ResetBigIcon() const; + /** * @brief Obtains the large icon of this notification. * @@ -1239,6 +1263,13 @@ public: */ std::string GetKey(); + /** + * @brief Get notification request key. + * + * @return Return the unique key of notification request. + */ + std::string GetSecureKey(); + /** * @brief Get notification request base key. * @@ -1273,7 +1304,7 @@ public: * @param bundleOption Indicates the bundleOption of this notification. */ void SetBundleOption(const std::shared_ptr &bundleOption); - + /** * @brief Obtains the bundleOption of the notification. * @@ -1497,7 +1528,9 @@ private: std::shared_ptr maxScreenWantAgent_ {}; std::shared_ptr additionalParams_ {}; std::shared_ptr littleIcon_ {}; - std::shared_ptr bigIcon_ {}; + std::string littleIconType_ {}; + mutable std::shared_ptr bigIcon_ {}; + std::shared_ptr overlayIcon_ {}; std::shared_ptr notificationContent_ {}; diff --git a/interfaces/inner_api/notification_sorting.h b/interfaces/inner_api/notification_sorting.h index 32410161396fafd50bc7a8b5bcbfb837fa820b7d..fd8b4752eaa305461747764e85de401f8d8229f5 100644 --- a/interfaces/inner_api/notification_sorting.h +++ b/interfaces/inner_api/notification_sorting.h @@ -20,6 +20,7 @@ #include "notification_slot.h" #include "parcel.h" #include "uri.h" +#include namespace OHOS { namespace Notification { @@ -74,9 +75,16 @@ public: * * @return Returns the NotificationSlot of the notification. */ - inline NotificationSlot GetSlot() const + inline NotificationSlot* GetSlot() { - return *slot_; + if (!slot_) { + slot_ = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::OTHER); + if (!slot_) { + ANS_LOGE("Failed to create NotificationSlot"); + slot_ = nullptr; + } + } + return slot_; }; /** diff --git a/interfaces/inner_api/notification_subscriber.h b/interfaces/inner_api/notification_subscriber.h index d74564c2519e7fd65849472ca8388f96653f42e1..63310b4d24e859a4c022b0d1291a0a427de2215f 100644 --- a/interfaces/inner_api/notification_subscriber.h +++ b/interfaces/inner_api/notification_subscriber.h @@ -24,7 +24,7 @@ namespace OHOS { namespace Notification { -class NotificationSubscriber { +class NotificationSubscriber : public std::enable_shared_from_this { public: NotificationSubscriber(); @@ -172,9 +172,12 @@ private: sptr GetAnsManagerProxy(); + void OnSubscriberDestory(); + public: NotificationSubscriber &subscriber_; sptr recipient_ {nullptr}; + std::atomic_bool isSubscriberDestory_ {false}; }; private: diff --git a/interfaces/inner_api/reminder_request.h b/interfaces/inner_api/reminder_request.h index 841e6a688325b9bbc4b4fe6622305d00b66e1607..eb5c2de5406585bb5846599c48c16ce876dd3ec7 100644 --- a/interfaces/inner_api/reminder_request.h +++ b/interfaces/inner_api/reminder_request.h @@ -19,11 +19,9 @@ #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" #include "want_params.h" namespace OHOS { @@ -437,6 +435,27 @@ public: */ std::string GetBundleName() const; + /** + * @brief Set the reminder type. + * + * @param reminderType the reminder type. + */ + void SetReminderType(const ReminderType type); + + /** + * @brief Set the reminder state. + * + * @param state the reminder state. + */ + void SetState(const uint8_t state); + + /** + * @brief Set the reminder repeat days of week. + * + * @param state the reminder repeat days of week. + */ + void SetRepeatDaysOfWeek(const uint8_t repeatDaysOfWeek); + /** * @brief Set the app system. * @@ -608,17 +627,6 @@ public: */ virtual bool OnTimeZoneChange(); - void RecoverBasicFromOldVersion(const std::shared_ptr& resultSet); - virtual void RecoverFromOldVersion(const std::shared_ptr& resultSet); - - /** - * @brief Recovery reminder instance from database record. - * - * @param resultSet Indicates the resultSet with pointer to the row of record data. - */ - void RecoverFromDbBase(const std::shared_ptr& resultSet); - virtual void RecoverFromDb(const std::shared_ptr& resultSet) {}; - /** * @brief Sets action button. * @@ -801,7 +809,9 @@ public: return true; } + void SetWantAgentStr(const std::string& wantStr); std::string GetWantAgentStr(); + void SetMaxWantAgentStr(const std::string& maxWantStr); std::string GetMaxWantAgentStr(); /** @@ -860,6 +870,16 @@ public: */ void SetCustomRingUri(const std::string &uri); + /** + * @brief Gets notification bundle option. + */ + sptr GetNotificationBundleOption() const; + + /** + * @brief Sets notification bundle option. + */ + void SetNotificationBundleOption(const sptr& option); + /** * @brief Update notification attributes. * @@ -879,6 +899,17 @@ public: */ std::vector GetDaysOfWeek() const; + /** + * @brief Create notification request struct when recover from rdb or + * recv reminder info from ipc. + */ + bool InitNotificationRequest(); + + /** + * @brief Gets repeat days of week + */ + uint8_t GetRepeatDaysOfWeek() const; + /** * @brief When system language change, will call this function. * need load resource to update button title @@ -886,15 +917,34 @@ public: */ void OnLanguageChange(const std::shared_ptr &resMgr); +public: + /** + * @brief Serialize want agent info and max want agent info to string. + * Persist to the rdb. + */ + void SerializeWantAgent(std::string& wantInfoStr, std::string& maxWantInfoStr); + + /** + * @brief Deserialize want agent info and max want agent info from string. + * Recover from the rdb. + */ + void DeserializeWantAgent(const std::string& wantAgentInfo, const uint8_t type); + + /** + * @brief Serialize action button info to string. + * Persist to the rdb. + */ + std::string SerializeButtonInfo() const; + + /** + * @brief Deserialize action button info from string. + * Recover from the rdb. + */ + void DeserializeButtonInfo(const std::string& buttonInfoStr); + 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 GetAppIndex(const int32_t uid); - static int32_t GetUserId(const int32_t &uid); - static void AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values, - bool oldVersion = false); static std::vector StringSplit(std::string source, const std::string &split); static int32_t GLOBAL_ID; @@ -979,9 +1029,6 @@ protected: return INVALID_LONG_LONG_VALUE; } - int64_t RecoverInt64FromDb(const std::shared_ptr &resultSet, - const std::string &columnName, const DbRecoveryType &columnType); - uint8_t repeatDaysOfWeek_{0}; /** @@ -993,7 +1040,6 @@ protected: */ int64_t GetNextDaysOfWeek(const time_t now, const time_t target) const; void SetRepeatDaysOfWeek(bool set, const std::vector &daysOfWeek); - uint8_t GetRepeatDaysOfWeek() const; time_t GetTriggerTimeWithDST(const time_t now, const time_t nextTriggerTime) const; uint64_t GetTriggerTime(const time_t now, const time_t nextTriggerTime) const; uint64_t GetNowInstantMilli() const; @@ -1003,17 +1049,16 @@ private: void AddRemovalWantAgent(); std::shared_ptr CreateWantAgent(AppExecFwk::ElementName &element) const; std::shared_ptr CreateMaxWantAgent(AppExecFwk::ElementName &element) const; - std::string GetButtonInfo() const; std::string GetShowTime(const uint64_t showTime) const; std::string GetTimeInfoInner(const time_t &timeInSecond, const TimeFormat &format, bool keep24Hour) const; std::string GetState(const uint8_t state) const; 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); + void SetExtraInfo(const AAFwk::WantParams& params); void UpdateActionButtons(const bool &setSnooze); bool UpdateNextReminder(const bool &force); void UpdateNotificationContent(const bool &setSnooze); @@ -1047,18 +1092,12 @@ private: */ void UpdateNotificationStateForSnooze(); - static void AppendWantAgentValuesBucket(const sptr& reminder, - NativeRdb::ValuesBucket& values); - bool MarshallingWantParameters(Parcel& parcel, const AAFwk::WantParams& params) const; bool MarshallingActionButton(Parcel& parcel) const; bool ReadWantParametersFromParcel(Parcel& parcel, AAFwk::WantParams& wantParams); bool ReadActionButtonFromParcel(Parcel& parcel); - void RecoverBasicFromDb(const std::shared_ptr& resultSet); void RecoverActionButtonJsonMode(const std::string& jsonString); - void RecoverActionButton(const std::shared_ptr& resultSet); - void RecoverWantAgent(const std::string& wantAgentInfo, const uint8_t& type); void RecoverWantAgentByJson(const std::string& wantAgentInfo, const uint8_t& type); static const uint32_t MIN_TIME_INTERVAL_IN_MILLI; @@ -1105,6 +1144,8 @@ private: std::string wantAgentStr_{}; std::string maxWantAgentStr_{}; + + sptr notificationOption_ {nullptr}; }; } // namespace Reminder } // namespace OHOS diff --git a/interfaces/inner_api/reminder_request_alarm.h b/interfaces/inner_api/reminder_request_alarm.h index d82f093a39a5024e33fc984115f208a692c304eb..e9f01d9222a073e8987584492e035b904faabf51 100644 --- a/interfaces/inner_api/reminder_request_alarm.h +++ b/interfaces/inner_api/reminder_request_alarm.h @@ -71,6 +71,20 @@ public: */ uint8_t GetMinute() const; + /** + * @brief Sets the hour. + * + * @param hour Indicates the hour. + */ + void SetHour(const uint8_t hour); + + /** + * @brief Sets the minute. + * + * @param minute Indicates the minute. + */ + void SetMinute(const uint8_t minute); + virtual bool UpdateNextReminder() override; /** @@ -95,10 +109,6 @@ public: * @return true if read parcel success. */ bool ReadFromParcel(Parcel &parcel) override; - virtual void RecoverFromDb(const std::shared_ptr& resultSet) override; - virtual void RecoverFromOldVersion(const std::shared_ptr& resultSet) override; - static void AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values); protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) override; diff --git a/interfaces/inner_api/reminder_request_calendar.h b/interfaces/inner_api/reminder_request_calendar.h index 38578e528f114340415c6e1d642d93e82394a5b5..6e2ff9dbc1229028ca81f5d539003bc851562e2b 100644 --- a/interfaces/inner_api/reminder_request_calendar.h +++ b/interfaces/inner_api/reminder_request_calendar.h @@ -118,6 +118,133 @@ public: return firstDesignateDay_; } + /** + * @brief Gets the repeat day. + */ + uint32_t GetRepeatDay() const + { + return repeatDay_; + } + + /** + * @brief Gets the repeat month. + */ + uint16_t GetRepeatMonth() const + { + return repeatMonth_; + } + + /** + * @brief Gets the start date time. + */ + uint64_t GetDateTime() const; + + /** + * @brief Gets the end date time. + */ + uint64_t GetEndDateTime() const; + + /** + * @brief Sets the year. + * + * @param year Indicates the year. + */ + void SetYear(const uint16_t year); + + /** + * @brief Sets the month. + * + * @param month Indicates the month. + */ + void SetMonth(const uint8_t month); + + /** + * @brief Sets the day. + * + * @param day Indicates the day. + */ + void SetDay(const uint8_t day); + + /** + * @brief Sets the hour. + * + * @param hour Indicates the hour. + */ + void SetHour(const uint8_t hour); + + /** + * @brief Sets the minute. + * + * @param minute Indicates the minute. + */ + void SetMinute(const uint8_t minute); + + /** + * @brief Sets the repeat day. + * + * @param repeatDay Indicates the repeat day. + */ + void SetRepeatDay(const uint32_t repeatDay); + + /** + * @brief Sets the repeat month. + * + * @param repeatMonth Indicates the repeat month. + */ + void SetRepeatMonth(const uint16_t repeatMonth); + + /** + * @brief Sets the first designate year. + * + * @param firstDesignateYear Indicates the first designate year. + */ + void SetFirstDesignateYear(const uint16_t firstDesignateYear); + + /** + * @brief Sets the first designate month. + * + * @param firstDesignateMonth Indicates the first designate month. + */ + void SetFirstDesignageMonth(const uint16_t firstDesignateMonth); + + /** + * @brief Sets the first designate day. + * + * @param firstDesignateDay Indicates the first designate day. + */ + void SetFirstDesignateDay(const uint16_t firstDesignateDay); + + /** + * @brief Sets the hour. + * + * @param hour Indicates the hour. + */ + void SetDateTime(const uint64_t time); + + /** + * @brief Serialize the rrule to string. + * Persist to the rdb. + */ + std::string SerializationRRule(); + + /** + * @brief Deserialize the rrule from string. + * Recover from the rdb. + */ + void DeserializationRRule(const std::string& str); + + /** + * @brief Serialize the exclude date to string. + * Persist to the rdb. + */ + std::string SerializationExcludeDates(); + + /** + * @brief Deserialize the exclude date from string. + * Recover from the rdb. + */ + void DeserializationExcludeDates(const std::string& str); + bool InitTriggerTime(); std::vector GetRepeatMonths() const; @@ -171,11 +298,6 @@ public: bool ReadFromParcel(Parcel &parcel) override; bool SetNextTriggerTime() override; - virtual void RecoverFromDb(const std::shared_ptr& resultSet) override; - virtual void RecoverFromOldVersion(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); bool SetEndDateTime(const uint64_t time); @@ -204,14 +326,6 @@ private: uint8_t GetNextDay(const uint16_t &settedYear, const uint8_t &settedMonth, const tm &now, const tm &target) const; uint64_t GetNextTriggerTime(const bool updateLast = false); 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; @@ -234,15 +348,6 @@ private: */ void CalcLastStartDateTime(); - void SetDateTime(const uint64_t time); - uint64_t GetDateTime(); - uint64_t GetEndDateTime(); - - std::string SerializationRRule(); - std::string SerializationExcludeDates(); - void DeserializationRRule(const std::string& str); - void DeserializationExcludeDates(const std::string& str); - static const uint8_t DEFAULT_SNOOZE_TIMES; tm dateTime_ = { diff --git a/interfaces/inner_api/reminder_request_timer.h b/interfaces/inner_api/reminder_request_timer.h index 1e9d4b5f2936282b2056709cb9602ed6cb505b07..527b65cbe0235cf5a63ca83521615b2756666347 100644 --- a/interfaces/inner_api/reminder_request_timer.h +++ b/interfaces/inner_api/reminder_request_timer.h @@ -51,6 +51,8 @@ public: ~ReminderRequestTimer() override {}; uint64_t GetInitInfo() const; + void SetInitInfo(const uint64_t countDownTimeInSeconds); + virtual bool OnDateTimeChange() override; virtual bool OnTimeZoneChange() override; virtual bool UpdateNextReminder() override; @@ -69,10 +71,6 @@ public: 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); - protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) override; diff --git a/frameworks/core/test/unittest/ans_manager_death_recipient_test/BUILD.gn b/interfaces/ndk/BUILD.gn similarity index 51% rename from frameworks/core/test/unittest/ans_manager_death_recipient_test/BUILD.gn rename to interfaces/ndk/BUILD.gn index 4f7cfcc8b4ab0b9094a4593d31ccb4419e11b85b..b5763690c6cde9e08780fdff4e52420b9b1c8bf7 100644 --- a/frameworks/core/test/unittest/ans_manager_death_recipient_test/BUILD.gn +++ b/interfaces/ndk/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2023 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,35 +13,56 @@ import("//base/notification/distributed_notification_service/notification.gni") import("//build/ohos.gni") -import("//build/test.gni") -module_output_path = "${component_name}/unittest" +cflags = [] -ohos_unittest("ans_manager_death_recipient_test") { - module_out_path = module_output_path - include_dirs = [ "${core_path}/include" ] +config("notification_ndk_config") { + visibility = [ ":*" ] - sources = [ "ans_manager_death_recipient_unit_test.cpp" ] + include_dirs = [ + "${inner_api_path}", + "${notification_ndk_path}/include", + ] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +config("notification_ndk_public_config") { + visibility = [ ":*" ] + + include_dirs = [ "${notification_ndk_path}/include" ] +} + +ohos_shared_library("ohnotification") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" + + configs = [ ":notification_ndk_config" ] + + public_configs = [ ":notification_ndk_public_config" ] + + sources = [ "src/notification.cpp" ] deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] external_deps = [ - "ability_base:want", + "ability_base:base", "ability_base:zuri", - "ability_runtime:wantagent_innerkits", "c_utils:utils", "hilog:libhilog", - "image_framework:image_native", "relational_store:native_rdb", ] - + output_extension = "so" + innerapi_tags = [ "ndk" ] subsystem_name = "${subsystem_name}" part_name = "${component_name}" } - -group("unittest") { - testonly = true - deps = [] - - deps += [ ":ans_manager_death_recipient_test" ] -} diff --git a/interfaces/ndk/include/notification.h b/interfaces/ndk/include/notification.h new file mode 100644 index 0000000000000000000000000000000000000000..236608ca53d3ebd599a9b2877a36da6d4c06cf82 --- /dev/null +++ b/interfaces/ndk/include/notification.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup NOTIFICATION + * @{ + * + * @brief Provides the definition of the C interface for the notification service. + * + * @since 14 + */ +/** + * @file notification.h + * + * @brief Declares the APIs of notification service. + * + * @library libohnotification.so + * @kit NotificationKit + * @syscap SystemCapability.Notification.Notification + * @since 14 + */ + +#ifndef OH_NOTIFICATION_H +#define OH_NOTIFICATION_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Checks whether this application is allowed to publish notifications. + * + * @return true - This application is allowed to publish notifications. + * false - This application is not allowed to publish notifications. + * @since 14 + */ +bool OH_Notification_IsNotificationEnabled(void); + +#ifdef __cplusplus +} +#endif +#endif // OH_NOTIFICATION_H +/** @} */ diff --git a/interfaces/ndk/src/notification.cpp b/interfaces/ndk/src/notification.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b1fe73aa82a2799763bbe13cb7577c7dab04adc --- /dev/null +++ b/interfaces/ndk/src/notification.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "notification.h" + +#include "notification_helper.h" +#include "ans_log_wrapper.h" + +#ifdef __cplusplus +extern "C" { +#endif + +bool OH_Notification_IsNotificationEnabled(void) +{ + bool isEnable = false; + int32_t result = OHOS::Notification::NotificationHelper::IsAllowedNotifySelf(isEnable); + if (result != OHOS::ERR_OK) { + ANS_LOGW("Get notification enable failed %{public}d", result); + return false; + } + return isEnable; +} + +#ifdef __cplusplus +} +#endif diff --git a/notification.gni b/notification.gni index b04f143f40ab3ddf00f221111f085bbcdbb057f4..1659de9e7244799d67ab07d374118e84818188c4 100644 --- a/notification.gni +++ b/notification.gni @@ -27,6 +27,7 @@ frameworks_path = "${component_path}/frameworks" frameworks_module_ans_path = "${frameworks_path}/ans" interfaces_path = "${component_path}/interfaces" inner_api_path = "${interfaces_path}/inner_api" +notification_ndk_path = "${interfaces_path}/ndk" core_path = "${frameworks_path}/core" test_path = "${component_path}/test" tools_path = "${component_path}/tools" @@ -58,6 +59,8 @@ declare_args() { notification_smart_reminder_supported = true ans_config_policy_enable = true screenlock_mgr_enable = true + telephony_cust = true + distributed_notification_service_feature_enable_fa_model = true if (defined(global_parts_info) && !defined(global_parts_info.resourceschedule_device_usage_statistics)) { @@ -65,7 +68,7 @@ declare_args() { } if (defined(global_parts_info) && - !defined(global_parts_info.hiviewdfx_hisysevent_native)) { + !defined(global_parts_info.hiviewdfx_hisysevent)) { hisysevent_usage = false } @@ -95,6 +98,11 @@ declare_args() { notification_smart_reminder_supported = false } + if (defined(global_parts_info) && + !defined(global_parts_info.telephony_telephony_cust)) { + telephony_cust = false + } + print("hisysevent_usage = " + "$hisysevent_usage") print("ans_hitrace_usage = " + "$ans_hitrace_usage") } diff --git a/sa_profile/3203.json b/sa_profile/3203.json index 08a6f695df150540d09763eff32c7b581fd106f9..0f52289d7865838a2b8c924d73ad0e6c0d4c6578 100644 --- a/sa_profile/3203.json +++ b/sa_profile/3203.json @@ -8,6 +8,7 @@ "depend": [ 3299 ], + "extension": ["backup", "restore"], "depend_time_out": 60000, "distributed": false, "dump_level": 1 diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 80bf8239591eb81c091ffd06e18857810f34d16c..9c2059a1a4971a43d8a1563c57d63fe5743e3241 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -49,7 +49,9 @@ ohos_shared_library("libans") { "src/advanced_datashare_helper.cpp", "src/advanced_datashare_helper_ext.cpp", "src/advanced_datashare_observer.cpp", + "src/advanced_notification_clone_service.cpp", "src/advanced_notification_event_service.cpp", + "src/advanced_notification_flow_control_service.cpp", "src/advanced_notification_inline.cpp", "src/advanced_notification_live_view_service.cpp", "src/advanced_notification_publish/base_publish_process.cpp", @@ -63,6 +65,12 @@ ohos_shared_library("libans") { "src/advanced_notification_subscriber_service.cpp", "src/advanced_notification_utils.cpp", "src/bundle_manager_helper.cpp", + "src/clone/notification_clone_bundle_info.cpp", + "src/clone/notification_clone_bundle_service.cpp", + "src/clone/notification_clone_disturb_service.cpp", + "src/clone/notification_clone_manager.cpp", + "src/clone/notification_clone_util.cpp", + "src/common/aes_gcm_helper.cpp", "src/common/file_utils.cpp", "src/common/notification_analytics_util.cpp", "src/common/notification_config_parse.cpp", @@ -89,10 +97,16 @@ ohos_shared_library("libans") { "src/reminder_data_manager.cpp", "src/reminder_data_manager_inner.cpp", "src/reminder_event_manager.cpp", + "src/reminder_store.cpp", + "src/reminder_store_strategy.cpp", "src/reminder_swing_decision_center.cpp", + "src/reminder_table.cpp", + "src/reminder_table_old.cpp", "src/reminder_timer_info.cpp", + "src/report_time_info.cpp", "src/system_dialog_connect_stb.cpp", "src/system_event_observer.cpp", + "src/telephony_extension_wrapper.cpp", ] configs = [ ":public_ans_config" ] @@ -155,6 +169,7 @@ ohos_shared_library("libans") { "image_framework:image_native", "init:libbegetutil", "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", "os_account:os_account_innerkits", "relational_store:native_rdb", "resource_management:global_resmgr", @@ -187,10 +202,6 @@ ohos_shared_library("libans") { defines += [ "HITRACE_METER_ENABLE" ] } - if (distributed_notification_service_feature_summary) { - defines += [ "ENABLE_ANS_EXT_WRAPPER" ] - } - if (ans_config_policy_enable) { external_deps += [ "config_policy:configpolicy_util" ] defines += [ "CONFIG_POLICY_ENABLE" ] @@ -201,6 +212,18 @@ ohos_shared_library("libans") { defines += [ "SCREENLOCK_MGR_ENABLE" ] } + if (distributed_notification_service_feature_summary) { + defines += [ "ENABLE_ANS_EXT_WRAPPER" ] + } + + if (telephony_cust) { + defines += [ "ENABLE_ANS_TELEPHONY_CUST_WRAPPER" ] + } + + if (distributed_notification_service_feature_enable_fa_model) { + defines += [ "ANS_ENABLE_FA_MODEL" ] + } + subsystem_name = "${subsystem_name}" part_name = "${component_name}" } diff --git a/services/ans/include/advanced_datashare_helper.h b/services/ans/include/advanced_datashare_helper.h index d0971ed7db29ada9613ab2fdf699a3737ade8034..7490c0ef1a90a9394929e74f0dbd6d413fb70c13 100644 --- a/services/ans/include/advanced_datashare_helper.h +++ b/services/ans/include/advanced_datashare_helper.h @@ -27,6 +27,8 @@ namespace Notification { namespace { constexpr const char *KEY_FOCUS_MODE_ENABLE = "focus_mode_enable"; constexpr const char *KEY_FOCUS_MODE_PROFILE = "focus_mode_profile"; +constexpr const char *KEY_FOCUS_MODE_CALL_MESSAGE_POLICY = "focus_mode_call_message_policy"; +constexpr const char *KEY_FOCUS_MODE_REPEAT_CALLERS_ENABLE = "focus_mode_repeate_callers_enable"; } // namespace class AdvancedDatashareHelper : DelayedSingleton { @@ -34,12 +36,23 @@ public: AdvancedDatashareHelper(); ~AdvancedDatashareHelper() = default; bool Query(Uri &uri, const std::string &key, std::string &value); + bool isRepeatCall(const std::string &phoneNumber); + ErrCode QueryContact(Uri &uri, const std::string &phoneNumber, const std::string &policy); std::string GetFocusModeEnableUri(const int32_t &userId) const; std::string GetFocusModeProfileUri(const int32_t &userId) const; + std::string GetFocusModeCallPolicyUri(const int32_t &userId) const; + std::string GetFocusModeRepeatCallUri(const int32_t &userId) const; std::string GetUnifiedGroupEnableUri() const; private: + enum ContactPolicy { + ALLOW_FAVORITE_CONTACTS = 4, + ALLOW_SPECIFIED_CONTACTS = 5, + }; std::shared_ptr CreateDataShareHelper(); + std::shared_ptr CreateContactDataShareHelper(std::string uri); + bool dealWithContactResult(std::shared_ptr helper, + std::shared_ptr resultSet, const std::string &policy); }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/advanced_datashare_helper_ext.h b/services/ans/include/advanced_datashare_helper_ext.h index 76842aac051ab1ede104605d10fdb5070f7fc356..6309f1e034ba67ef74aeadb78f8a939c10ad3a5a 100644 --- a/services/ans/include/advanced_datashare_helper_ext.h +++ b/services/ans/include/advanced_datashare_helper_ext.h @@ -27,6 +27,7 @@ namespace Notification { namespace { constexpr const char *KEY_FOCUS_MODE_ENABLE_EXT = "focus_mode_enable"; constexpr const char *KEY_FOCUS_MODE_PROFILE_EXT = "focus_mode_profile"; +constexpr const char *KEY_FOCUS_MODE_CALL_MESSAGE_POLICY_EXT = "focus_mode_call_message_policy"; } // namespace class AdvancedDatashareHelperExt : DelayedSingleton { diff --git a/services/ans/include/advanced_notification_flow_control_service.h b/services/ans/include/advanced_notification_flow_control_service.h new file mode 100644 index 0000000000000000000000000000000000000000..cb182f8174f8ce3b49c9d8a75cdf29945f9b5ef4 --- /dev/null +++ b/services/ans/include/advanced_notification_flow_control_service.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_FLOW_CONTROL_SERVICE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_FLOW_CONTROL_SERVICE_H + +#include +#include +#include +#include + +#include "errors.h" +#include "singleton.h" +#include "ans_const_define.h" +#include "notification_record.h" + +namespace OHOS { +namespace Notification { +struct FlowControlThreshold { + uint32_t maxCreateNumPerSecond = MAX_CREATE_NUM_PERSECOND; + uint32_t maxUpdateNumPerSecond = MAX_UPDATE_NUM_PERSECOND; + uint32_t maxCreateNumPerSecondPerApp = MAX_CREATE_NUM_PERSECOND_PERAPP; + uint32_t maxUpdateNumPerSecondPerApp = MAX_UPDATE_NUM_PERSECOND_PERAPP; +}; + +class FlowControlService : public DelayedSingleton { +public: + FlowControlService(); + ErrCode FlowControl(const std::shared_ptr &record, + const int32_t callingUid, bool isNotificationExists); + +private: + ErrCode PublishFlowCtrl(const std::shared_ptr &record, const int32_t callingUid); + ErrCode PublishGlobalFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now); + ErrCode PublishSingleAppFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid); + void PublishRecordTimestamp(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid); + void PublishSingleAppFlowCtrlRemoveExpire(std::chrono::system_clock::time_point now); + + ErrCode UpdateFlowCtrl(const std::shared_ptr &record, const int32_t callingUid); + ErrCode UpdateGlobalFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now); + ErrCode UpdateSingleAppFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid); + void UpdateRecordTimestamp(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid); + void UpdateSingleAppFlowCtrlRemoveExpire(std::chrono::system_clock::time_point now); + +private: + static std::mutex flowControlMutex_; + std::list flowControlUpdateTimestampList_; + std::list flowControlPublishTimestampList_; + static std::mutex systemFlowControlMutex_; + std::list systemFlowControlUpdateTimestampList_; + std::list systemFlowControlPublishTimestampList_; + static std::mutex singleAppFlowControlMutex_; + std::map>> singleAppFlowControlUpdateTimestampMap_; + std::map>> singleAppFlowControlPublishTimestampMap_; + + FlowControlThreshold threshold_; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_FLOW_CONTROL_SERVICE_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 864046222973298ea2971c1a6f681a0c71e2022f..31ba34776c66608e9f37a37e288351846901efd2 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -17,10 +17,10 @@ #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H #include -#include #include #include #include +#include #include "event_handler.h" #include "event_runner.h" @@ -51,6 +51,8 @@ namespace OHOS { namespace Notification { + +static const uint32_t DEFAULT_SLOT_FLAGS = 59; // 0b111011 class AdvancedNotificationService final : public AnsManagerStub { public: struct NotificationRequestDb { @@ -101,6 +103,17 @@ public: */ ErrCode Publish(const std::string &label, const sptr &request) override; + /** + * @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. + * + * @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 PublishNotificationForIndirectProxy(const sptr &request) override; + /** * @brief Cancels a published notification matching the specified label and notificationId. * @@ -362,11 +375,8 @@ public: ErrCode RemoveAllNotificationsForDisable(const sptr &bundleOption); ErrCode RemoveNotifications(const std::vector &keys, int32_t removeReason) override; - - ErrCode GetUnifiedGroupInfoFromDb(std::string &enable); - ErrCode RemoveNotificationBySlot(const sptr &bundleOption, - const sptr &slot, const int reason); + ErrCode GetUnifiedGroupInfoFromDb(std::string &enable); /** * @brief Delete notification based on key. @@ -551,6 +561,15 @@ public: */ ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; + + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog() override; + + ErrCode RemoveEnableNotificationDialog(const sptr &bundleOption); /** * @brief Checks whether notifications are allowed for a specific bundle. @@ -601,6 +620,14 @@ public: */ ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override; + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) override; + /** * @brief Cancel notifications according to group. * @@ -916,7 +943,7 @@ public: ErrCode CancelPreparedNotification(int32_t notificationId, const std::string &label, const sptr &bundleOption, const int32_t reason); - + ErrCode PrepareNotificationInfo( const sptr &request, sptr &bundleOption); ErrCode PublishPreparedNotification(const sptr &request, @@ -991,7 +1018,7 @@ public: ErrCode SetDistributedEnabledByBundle(const sptr &bundleOption, const std::string &deviceType, const bool enabled) override; - /** + /* * @brief Get whether to allow a specified application to publish notifications cross * device collaboration. The caller must have system permissions to call this method. * @@ -1100,7 +1127,7 @@ public: /** * @brief Recover LiveView from DB. */ - void RecoverLiveViewFromDb(); + void RecoverLiveViewFromDb(int32_t userId = -1); #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** @@ -1122,6 +1149,29 @@ public: */ bool AllowUseReminder(const std::string& bundleName); + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile object. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) override; + + int32_t OnBackup(MessageParcel& data, MessageParcel& reply); + + int32_t OnRestore(MessageParcel& data, MessageParcel& reply); + + void ResetDistributedEnabled(); + + /** + * @brief Update notification timer by uid + * + * @param uid uid. + * @param isPaused if paused + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) override; protected: /** * @brief Query whether there is a agent relationship between the two apps. @@ -1138,6 +1188,14 @@ private: size_t recentCount = 16; }; + enum UploadStatus { + CREATE, + FIRST_UPDATE_TIME_OUT, + CONTINUOUS_UPDATE_TIME_OUT, + END, + FINISH + }; + struct SoundPermissionInfo { std::set bundleName_; std::atomic needUpdateCache_ = true; @@ -1145,12 +1203,12 @@ private: std::mutex dbMutex_; }; - enum UploadStatus { - CREATE, - FIRST_UPDATE_TIME_OUT, - CONTINUOUS_UPDATE_TIME_OUT, - END, - FINISH + enum ContactPolicy { + FORBID_EVERYONE = 1, + ALLOW_EVERYONE = 2, + ALLOW_EXISTING_CONTACTS = 3, + ALLOW_FAVORITE_CONTACTS = 4, + ALLOW_SPECIFIED_CONTACTS = 5, }; AdvancedNotificationService(); @@ -1158,7 +1216,8 @@ private: void StartFilters(); void StopFilters(); ErrCode Filter(const std::shared_ptr &record, bool isRecover = false); - void ChangeNotificationByControlFlags(const std::shared_ptr &record); + void ChangeNotificationByControlFlags(const std::shared_ptr &record, + const bool isAgentController); ErrCode CheckPublishPreparedNotification(const std::shared_ptr &record, bool isSystemApp); void AddToNotificationList(const std::shared_ptr &record); void AddToDelayNotificationList(const std::shared_ptr &record); @@ -1181,8 +1240,9 @@ private: void SortNotificationList(); static bool NotificationCompare( const std::shared_ptr &first, const std::shared_ptr &second); - ErrCode FlowControl(const std::shared_ptr &record); - ErrCode PublishFlowControl(const std::shared_ptr &record); + ErrCode PublishInNotificationList(const std::shared_ptr &record); + ErrCode RemoveNotificationBySlot(const sptr &bundleOption, + const sptr &slot, const int reason); sptr GenerateSortingMap(); static sptr GenerateBundleOption(); @@ -1190,7 +1250,6 @@ private: std::string TimeToString(int64_t time); int64_t GetNowSysTime(); - void ExtendDumpForFlags(std::shared_ptr, std::stringstream &stream); ErrCode ActiveNotificationDump(const std::string& bundle, int32_t userId, int32_t recvUserId, std::vector &dumpInfo); ErrCode RecentNotificationDump(const std::string& bundle, int32_t userId, int32_t recvUserId, @@ -1205,7 +1264,7 @@ private: void AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate); ErrCode PrepareNotificationRequest(const sptr &request); ErrCode PrepareContinuousTaskNotificationRequest(const sptr &request, const int32_t &uid); - static bool GetActiveUserId(int& userId); + void TriggerRemoveWantAgent(const sptr &request); bool CheckApiCompatibility(const sptr &bundleOption); ErrCode IsAllowedNotifySelf(const sptr &bundleOption, bool &allowed); @@ -1259,6 +1318,7 @@ private: ErrCode SetRequestBundleInfo(const sptr &request, int32_t uid, std::string &bundle); ErrCode PrePublishNotificationBySa(const sptr &request, int32_t uid, std::string &bundle); + ErrCode PrePublishRequest(const sptr &request); ErrCode PublishNotificationBySa(const sptr &request); bool IsNeedPushCheck(const sptr &request); void FillExtraInfoToJson(const sptr &request, @@ -1272,6 +1332,12 @@ private: void SetAgentNotification(sptr& notificationRequest, std::string& bundleName); ErrCode SetDefaultNotificationEnabled( const sptr &bundleOption, bool enabled); + ErrCode IsAllowedNotifyForBundle(const sptr &bundleOption, bool &allowed); + void AddLiveViewSubscriber(); + void EraseLiveViewSubsciber(const std::string &bundleName); + bool GetLiveViewSubscribeState(const std::string &bundleName); + bool CheckLocalLiveViewSubscribed(const sptr &request); + bool CheckLocalLiveViewAllowed(const sptr &request); static bool GetBundleInfoByNotificationBundleOption( const sptr &bundleOption, AppExecFwk::BundleInfo &bundleInfo); @@ -1281,14 +1347,19 @@ private: NotificationContent::Type contentType, std::vector>& recordList); ErrCode RemoveNotificationFromRecordList(const std::vector>& recordList); void OnSubscriberAdd(const std::shared_ptr &record); + void OnSubscriberAddInffrt(const std::shared_ptr &record); bool IsLiveViewCanRecover(const sptr request); ErrCode FillNotificationRecord(const NotificationRequestDb &requestdbObj, std::shared_ptr record); static int32_t SetNotificationRequestToDb(const NotificationRequestDb &requestDb); static int32_t GetNotificationRequestFromDb(const std::string &key, NotificationRequestDb &requestDb); - static int32_t GetBatchNotificationRequestsFromDb(std::vector &requests); + static int32_t GetBatchNotificationRequestsFromDb(std::vector &requests, + int32_t userId = -1); + static int32_t DoubleDeleteNotificationFromDb(const std::string &key, + const std::string &secureKey, const int32_t userId); static int32_t DeleteNotificationRequestFromDb(const std::string &key, const int32_t userId); void CancelTimer(uint64_t timerId); + void BatchCancelTimer(std::vector timerIds); ErrCode UpdateNotificationTimerInfo(const std::shared_ptr &record); ErrCode SetFinishTimer(const std::shared_ptr &record); ErrCode StartFinishTimer(const std::shared_ptr &record, @@ -1300,18 +1371,21 @@ private: void CancelUpdateTimer(const std::shared_ptr &record); void StartArchiveTimer(const std::shared_ptr &record); void CancelArchiveTimer(const std::shared_ptr &record); + ErrCode StartAutoDeletedTimer(const std::shared_ptr &record); void ProcForDeleteLiveView(const std::shared_ptr &record); + ErrCode IsAllowedGetNotificationByFilter(const std::shared_ptr &record); void QueryDoNotDisturbProfile(const int32_t &userId, std::string &enable, std::string &profileId); void CheckDoNotDisturbProfile(const std::shared_ptr &record); + void ReportDoNotDisturbModeChanged(const int32_t &userId, std::string &enable); void DoNotDisturbUpdataReminderFlags(const std::shared_ptr &record); ErrCode CheckCommonParams(); std::shared_ptr GetRecordFromNotificationList( int32_t notificationId, int32_t uid, const std::string &label, const std::string &bundleName); std::shared_ptr MakeNotificationRecord( const sptr &request, const sptr &bundleOption); - ErrCode IsAllowedNotifyForBundle(const sptr &bundleOption, bool &allowed); void FillActionButtons(const sptr &request); - ErrCode IsAllowedGetNotificationByFilter(const std::shared_ptr &record); + ErrCode IsAllowedGetNotificationByFilter(const std::shared_ptr &record, + const sptr &bundleOption); ErrCode FillRequestByKeys(const sptr &oldRequest, const std::vector extraInfoKeys, sptr &newRequest); ErrCode IsAllowedRemoveSlot(const sptr &bundleOption, @@ -1320,27 +1394,27 @@ private: ErrCode CheckBundleOptionValid(sptr &bundleOption); bool IsNeedNotifyConsumed(const sptr &request); ErrCode AddRecordToMemory(const std::shared_ptr &record, - bool isSystemApp, bool isUpdateByOwner); + bool isSystemApp, bool isUpdateByOwner, const bool isAgentController); ErrCode DuplicateMsgControl(const sptr &request); void RemoveExpiredUniqueKey(); bool IsDuplicateMsg(const std::string &uniqueKey); + void DeleteDuplicateMsgs(const sptr &bundleOption); ErrCode PublishRemoveDuplicateEvent(const std::shared_ptr &record); - ErrCode UpdateSlotAuthInfo(const std::shared_ptr &record); std::vector GetBundlesOfActiveUser(); - void RemoveNotificationList(const std::shared_ptr &record); + ErrCode UpdateSlotAuthInfo(const std::shared_ptr &record); void FillLockScreenPicture(const sptr &newRequest, const sptr &oldRequest); + ErrCode CancelAsBundleWithAgent( + const sptr &bundleOption, const int32_t id, const std::string &label, int32_t userId); static ErrCode SetLockScreenPictureToDb(const sptr &request); static ErrCode GetLockScreenPictureFromDb(NotificationRequest *request); void RemoveDoNotDisturbProfileTrustList(const sptr &bundleOption); - ErrCode DeleteAllByUserInner(const int32_t &userId, int32_t reason, bool isAsync = false); - ErrCode RemoveAllNotificationsInner(const sptr &bundleOption, int32_t reason); ErrCode AssignValidNotificationSlot(const std::shared_ptr &record, const sptr &bundleOption); ErrCode UpdateSlotReminderModeBySlotFlags(const sptr &bundle, uint32_t slotFlags); ErrCode CheckSoundPermission(const sptr &request, std::string bundleName); - void GenerateSlotReminderMode( - const sptr &slot, const sptr &bundle, bool isSpecifiedSlot = false); + void GenerateSlotReminderMode(const sptr &slot, const sptr &bundle, + bool isSpecifiedSlot = false, uint32_t defaultSlotFlags = DEFAULT_SLOT_FLAGS); static void CloseAlert(const std::shared_ptr &record); bool IsUpdateSystemLiveviewByOwner(const sptr &request); bool IsSaCreateSystemLiveViewAsBundle(const std::shared_ptr &record, int32_t ipcUid); @@ -1350,12 +1424,21 @@ private: ErrCode StartPublishDelayedNotification(const std::shared_ptr &record); void StartPublishDelayedNotificationTimeOut(const int32_t ownerUid, const int32_t notificationId); void UpdateRecordByOwner(const std::shared_ptr &record, bool isSystemApp); - ErrCode CheckSystemLiveView(const sptr &request, const std::string &key); + ErrCode DeleteAllByUserInner(const int32_t &userId, int32_t reason, bool isAsync = false); + ErrCode RemoveAllNotificationsInner(const sptr &bundleOption, int32_t reason); + void RemoveNotificationList(const std::shared_ptr &record); + void StartFinishTimerForUpdate(const std::shared_ptr &record, uint64_t process); + ErrCode CheckLongTermLiveView(const sptr &request, const std::string &key); void ExcuteCancelGroupCancel(const sptr& bundleOption, const std::string &groupName, const int32_t reason); ErrCode ExcuteCancelAll(const sptr& bundleOption, const int32_t reason); ErrCode ExcuteDelete(const std::string &key, const int32_t removeReason); - + ErrCode CheckNeedSilent(const std::string &phoneNumber, int32_t callerType, int32_t userId); + uint32_t GetDefaultSlotFlags(const sptr &request); + bool IsSystemUser(int32_t userId); + + ErrCode OnRecoverLiveView(const std::vector &keys); + void HandleUpdateLiveViewNotificationTimer(const int32_t uid, const bool isPaused); private: static sptr instance_; static std::mutex instanceMutex_; @@ -1366,10 +1449,6 @@ private: std::shared_ptr runner_ = nullptr; std::shared_ptr handler_ = nullptr; std::list> notificationList_; - static std::mutex flowControlMutex_; - std::list flowControlTimestampList_; - std::list flowControlUpdateTimestampList_; - std::list flowControlPublishTimestampList_; std::shared_ptr recentInfo_ = nullptr; std::shared_ptr distributedKvStoreDeathRecipient_ = nullptr; std::shared_ptr systemEventObserver_ = nullptr; @@ -1385,9 +1464,11 @@ private: std::shared_ptr permissonFilter_ = nullptr; std::shared_ptr notificationSlotFilter_ = nullptr; std::shared_ptr dialogManager_ = nullptr; - std::list> uniqueKeyList_; + std::list> uniqueKeyList_; std::list, uint64_t>> delayNotificationList_; std::mutex delayNotificationMutext_; + static std::mutex doNotDisturbMutex_; + std::map doNotDisturbEnableRecord_; }; /** diff --git a/services/ans/include/advanced_notification_service_ability.h b/services/ans/include/advanced_notification_service_ability.h index 7ee5d2fd77dcfebea894f3eeb054fbec6d2b800c..229e57197d78441ad7928b5660a2714d611f776f 100644 --- a/services/ans/include/advanced_notification_service_ability.h +++ b/services/ans/include/advanced_notification_service_ability.h @@ -50,6 +50,7 @@ private: void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; void OnReceiveEvent(const EventFwk::CommonEventData &data); + int32_t OnExtension(const std::string& extension, MessageParcel& data, MessageParcel& reply) override; private: std::atomic isDatashaReready_ {false}; diff --git a/services/ans/include/aes_gcm_helper.h b/services/ans/include/aes_gcm_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..0cb078258d29e1348a3431b52ed8affdfdf71e8c --- /dev/null +++ b/services/ans/include/aes_gcm_helper.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_AES_GCM_HELPER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_AES_GCM_HELPER_H +#include + +#include "errors.h" +#include "ans_inner_errors.h" + +namespace OHOS { +namespace Notification { +class AesGcmHelper final { +public: + static ErrCode Encrypt(const std::string &plainText, std::string &cipherText); + static ErrCode Decrypt(std::string &plainText, const std::string &cipherText); + +private: + static bool EncryptAesGcm(const std::string &plainText, std::string &cipherText, std::string &key); + static bool DecryptAesGcm(std::string &plainText, const std::string &cipherText, std::string &key); + static bool GenerateKey(std::string &key); + static std::string Byte2Hex(const std::string &bytes); + static std::string Hex2Byte(const std::string &hex); + static unsigned char HexChar2Byte(const char &hexCh); +}; +} // namespace OHOS::Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_AES_GCM_HELPER_H \ No newline at end of file diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index ea71a8b83916d264a4a5608a719e62f5207e93de..911e3b7732b67c9baf3d9e98a5113824e835f183 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -65,6 +65,16 @@ public: */ int32_t GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId); + /** + * @brief Obtains the default uid. + * + * @param bundle Indicates the bundle name. + * @param userId Indicates the user id. + * @param appIndex Indicates the app Index. + * @return Returns the uid. + */ + int32_t GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId, const int32_t appIndex); + /** * @brief Obtains the bundle info. * @@ -97,7 +107,7 @@ public: */ bool GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, int32_t userId, AppExecFwk::BundleInfo &bundleInfo); - + /** * @brief Obtains BundleInfo of all bundles available in the system through the proxy object. * @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned. @@ -108,6 +118,22 @@ public: bool GetBundleInfos( const AppExecFwk::BundleFlag flag, std::vector &bundleInfos, int32_t userId); + /** + * @brief Check API compatibility. + * + * @param bundleName Indicates the bundle name. + * @param uid Indicates the bundle uid. + * @return Returns the check result. + */ + bool CheckApiCompatibility(const std::string &bundleName, const int32_t &uid); + + /** + * @brief Obtains the app index by uid. + * @param uid Indicates uid. + * @return Returns the query result if succeed, retrun 0(main index) otherwise. + */ + int32_t GetAppIndexByUid(const int32_t uid); + private: void Connect(); void Disconnect(); @@ -123,5 +149,4 @@ private: }; } // namespace Notification } // namespace OHOS - -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H diff --git a/services/ans/include/notification_analytics_util.h b/services/ans/include/notification_analytics_util.h index 6b51afb974e30993b13f32ce51a4b54047b46fd1..3366088cf647bbdf62d4250d44d1ede6f21074e9 100644 --- a/services/ans/include/notification_analytics_util.h +++ b/services/ans/include/notification_analytics_util.h @@ -33,6 +33,7 @@ enum EventSceneId { SCENE_6 = 6, SCENE_7 = 7, SCENE_8 = 8, + SCENE_9 = 9, }; enum EventBranchId { @@ -55,6 +56,7 @@ public: HaMetaMessage& BranchId(uint32_t branchId); HaMetaMessage& ErrorCode(uint32_t errorCode); HaMetaMessage& Message(const std::string& message, bool print = false); + HaMetaMessage& Append(const std::string& message); HaMetaMessage& BundleName(const std::string& bundleName_); HaMetaMessage& AgentBundleName(const std::string& agentBundleName); HaMetaMessage& TypeCode(int32_t typeCode); @@ -79,6 +81,16 @@ public: }; +struct FlowControllerOption { + int32_t count; + int32_t time; +}; + +struct ReportCache { + EventFwk::Want want; + int32_t eventCode; +}; + class NotificationAnalyticsUtil { public: static void ReportPublishFailedEvent(const sptr& request, const HaMetaMessage& message); @@ -89,6 +101,10 @@ public: static void ReportDeleteFailedEvent(const HaMetaMessage& message); + static void RemoveExpired(std::list &list, + const std::chrono::system_clock::time_point &now, int32_t time = 1); + + static int64_t GetCurrentTime(); private: static void ReportNotificationEvent(const sptr& request, EventFwk::Want want, int32_t eventCode, const std::string& reason); @@ -98,6 +114,23 @@ private: static void CommonNotificationEvent(int32_t eventCode, const HaMetaMessage& message); static void ReportNotificationEvent(EventFwk::Want want, int32_t eventCode, const std::string& reason); + + static bool ReportFlowControl(const int32_t reportType); + + static FlowControllerOption GetFlowOptionByType(const int32_t reportType); + + static std::string BuildExtraInfo(const HaMetaMessage& message); + + static std::string BuildExtraInfoWithReq(const HaMetaMessage& message, + const sptr& request); + + static void SetCommonWant(EventFwk::Want& want, const HaMetaMessage& message, std::string& extraInfo); + + static void AddListCache(EventFwk::Want& want, int32_t eventCode); + + static void ExecuteCacheList(); + + static void ReportCommonEvent(const ReportCache& reportCache); }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_clone_bundle_info.h b/services/ans/include/notification_clone_bundle_info.h new file mode 100644 index 0000000000000000000000000000000000000000..99a2af2c4ee798b66d8a14cce6b30f61439187bc --- /dev/null +++ b/services/ans/include/notification_clone_bundle_info.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_INFO_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_INFO_H + +#include "notification_clone_template.h" + +#include "ffrt.h" +#include "notification_constant.h" +#include "notification_bundle_option.h" +#include "notification_do_not_disturb_profile.h" + +namespace OHOS { +namespace Notification { +class NotificationCloneBundleInfo { +public: + class SlotInfo { + public: + std::string Dump() const; + NotificationConstant::SlotType slotType_; + bool enable_; + bool isForceControl_; + }; + NotificationCloneBundleInfo() = default; + ~NotificationCloneBundleInfo() = default; + + void SetBundleName(const std::string &name); + std::string GetBundleName() const; + + void SetAppIndex(const int32_t &appIndex); + int32_t GetAppIndex() const; + + void SetSlotFlags(const uint32_t &slotFlags); + uint32_t GetSlotFlags() const; + + void SetUid(const int32_t &uid); + int32_t GetUid() const; + + void SetIsShowBadge(const bool &isShowBadge); + bool GetIsShowBadge() const; + + void SetEnableNotification(const bool &enable); + bool GetEnableNotification() const; + + void AddSlotInfo(const SlotInfo &slotInfo); + std::vector GetSlotInfo() const; + + void ToJson(nlohmann::json &jsonObject) const; + void FromJson(const nlohmann::json &root); + void SlotsFromJson(const nlohmann::json &jsonObject); + std::string Dump() const; + +private: + std::string bundleName_; + int32_t appIndex_ = -1; + int32_t uid_ = -1; + uint32_t slotFlags_ = 0; + bool isShowBadge_ = false; + bool isEnabledNotification_ = false; + std::vector slotsInfo_; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_INFO_H diff --git a/services/ans/include/notification_clone_bundle_service.h b/services/ans/include/notification_clone_bundle_service.h new file mode 100644 index 0000000000000000000000000000000000000000..7e30c466423652801d2150491e262d8642a6a435 --- /dev/null +++ b/services/ans/include/notification_clone_bundle_service.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_H + +#include "notification_clone_template.h" + +#include "ffrt.h" +#include "notification_bundle_option.h" +#include "notification_clone_bundle_info.h" + +namespace OHOS { +namespace Notification { +class NotificationCloneBundle final : public NotificationCloneTemplate { +public: + NotificationCloneBundle(); + ~NotificationCloneBundle() override; + static std::shared_ptr GetInstance(); + ErrCode OnBackup(nlohmann::json &jsonObject) override; + void OnRestore(const nlohmann::json &jsonObject) override; + void OnBundleDataAdd(const sptr &bundleOption); + void OnBundleDataUpdate(const sptr &bundleOption); + void HandleBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid); + void OnUserSwitch(int32_t userId) override; +private: + std::vector bundlesInfo_; + std::shared_ptr cloneBundleQueue_ = nullptr; + ffrt::mutex lock_; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_H diff --git a/services/ans/include/notification_clone_disturb_service.h b/services/ans/include/notification_clone_disturb_service.h new file mode 100644 index 0000000000000000000000000000000000000000..ab8a3939c4202a9d8af4e06122714f25bded54a0 --- /dev/null +++ b/services/ans/include/notification_clone_disturb_service.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_DISTURB_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_DISTURB_H + +#include "notification_clone_template.h" + +#include "ffrt.h" +#include "notification_bundle_option.h" +#include "notification_do_not_disturb_profile.h" + +namespace OHOS { +namespace Notification { +class NotificationCloneDisturb final : public NotificationCloneTemplate { +public: + NotificationCloneDisturb(); + ~NotificationCloneDisturb() override; + static std::shared_ptr GetInstance(); + ErrCode OnBackup(nlohmann::json &jsonObject) override; + void OnRestore(const nlohmann::json &jsonObject) override; + void OnBundleDataAdd(const sptr &bundleOption); + void OnBundleDataUpdate(const sptr &bundleOption); + void HandlerBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid); + int32_t GetBundleUid(const std::string bundleName, int32_t userId, int32_t appIndex); + void GetProfileUid(int32_t userId, std::map& uidMap, + std::vector trustList, std::vector& exitBunldleList, + std::vector& notExitBunldleList); + void CheckBundleInfo(std::vector& trustList, + std::vector& bundleList, const NotificationBundleOption& bundle); + int32_t GetActiveUserId(); + void OnUserSwitch(int32_t userId) override; + +private: + std::atomic userId_ = -1; + std::vector> profiles_; + std::shared_ptr cloneDisturbQueue_ = nullptr; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_DISTURB_H diff --git a/services/ans/include/notification_clone_manager.h b/services/ans/include/notification_clone_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..1328e8fd9703dd63c12116f824cd58722012981a --- /dev/null +++ b/services/ans/include/notification_clone_manager.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_MANAGER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_MANAGER_H + +#include +#include + +#include "unique_fd.h" +#include "iremote_proxy.h" +#include "notification_clone_template.h" +namespace OHOS { +namespace Notification { + +class NotificationCloneManager { +public: + static NotificationCloneManager& GetInstance(); + + int32_t OnBackup(MessageParcel& data, MessageParcel& reply); + int32_t OnRestore(MessageParcel& data, MessageParcel& reply); + void OnUserSwitch(int32_t userId); + +private: + NotificationCloneManager(); + ~NotificationCloneManager(); + + void RemoveBackUpFile(); + ErrCode LoadConfig(UniqueFd &fd, std::string& config); + ErrCode SaveConfig(const std::string& config); + std::map> cloneTemplates; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_MANAGER_H diff --git a/services/ans/include/notification_clone_template.h b/services/ans/include/notification_clone_template.h new file mode 100644 index 0000000000000000000000000000000000000000..b9baa74725dd1f94a971a540c63a5bc6b993591e --- /dev/null +++ b/services/ans/include/notification_clone_template.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_TEMPLATE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_TEMPLATE_H + +#include "errors.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace Notification { + +class NotificationCloneTemplate { +public: + NotificationCloneTemplate() = default; + virtual ~NotificationCloneTemplate() = default; + virtual ErrCode OnBackup(nlohmann::json &jsonObject) = 0; + virtual void OnRestore(const nlohmann::json &jsonObject) = 0; + virtual void OnUserSwitch(int32_t userId) = 0; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_TEMPLATE_H diff --git a/services/ans/include/notification_clone_util.h b/services/ans/include/notification_clone_util.h new file mode 100644 index 0000000000000000000000000000000000000000..1d33f80b95a37525291a42c14353f03a2a1e119a --- /dev/null +++ b/services/ans/include/notification_clone_util.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_UTILS_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_UTILS_H + +#include +#include + +namespace OHOS { +namespace Notification { +class NotificationCloneUtil { +public: + NotificationCloneUtil() = default; + ~NotificationCloneUtil() = default; + static int32_t GetActiveUserId(); + static int32_t GetBundleUid(const std::string bundleName, int32_t userId, int32_t appIndex); +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_UTILS_H diff --git a/services/ans/include/notification_config_parse.h b/services/ans/include/notification_config_parse.h index 1948a9134e1bed7801bf78a01c70892c278f027d..18d1bdc2cf0f975b94dc0ce44d4e7a65118b2212 100644 --- a/services/ans/include/notification_config_parse.h +++ b/services/ans/include/notification_config_parse.h @@ -25,8 +25,10 @@ #include "config_policy_utils.h" #endif #include "nlohmann/json.hpp" +#include "notification_bundle_option.h" #include "notification_constant.h" #include "notification_flags.h" +#include "advanced_notification_flow_control_service.h" namespace OHOS { namespace Notification { @@ -39,6 +41,10 @@ public: bool GetCurrentSlotReminder( std::map> ¤tSlotReminder) const; uint32_t GetConfigSlotReminderModeByType(NotificationConstant::SlotType slotType) const; + uint32_t GetConfigSlotReminderModeByType(NotificationConstant::SlotType slotType, + const sptr &bundleOption) const; + void GetFlowCtrlConfigFromCCM(FlowControlThreshold &threshold); + private: std::map defaultCurrentSlotReminder_; std::vector notificationConfigJsons_; @@ -49,6 +55,10 @@ public: constexpr static const char* CFG_KEY_NAME = "name"; constexpr static const char* CFG_KEY_REMINDER_FLAGS = "reminderFlags"; constexpr static const char* APP_PRIVILEGES = "appPrivileges"; + constexpr static const char* CFG_KEY_MAX_CREATE_NUM_PERSECOND = "MaxCreateNumPerSecond"; + constexpr static const char* CFG_KEY_MAX_UPDATE_NUM_PERSECOND = "MaxUpdateNumPerSecond"; + constexpr static const char* CFG_KEY_MAX_CREATE_NUM_PERSECOND_PERAPP = "MaxCreateNumPerSecondPerApp"; + constexpr static const char* CFG_KEY_MAX_UPDATE_NUM_PERSECOND_PERAPP = "MaxUpdateNumPerSecondPerApp"; #ifdef CONFIG_POLICY_ENABLE constexpr static const char* NOTIFICAITON_CONFIG_FILE = "etc/notification/notification_config.json"; # else diff --git a/services/ans/include/notification_dialog.h b/services/ans/include/notification_dialog.h index ea37aa5ae1d12164ae7777ff503a34d3a77795e6..941e7f47f44ae5fc3e3283be2b694ec3bd47fa85 100644 --- a/services/ans/include/notification_dialog.h +++ b/services/ans/include/notification_dialog.h @@ -36,7 +36,6 @@ public: std::string appBundleName, const sptr &callerToken); - static int32_t GetActiveUserId(); static int32_t GetUidByBundleName(const std::string &bundleName); }; } // namespace Notification diff --git a/services/ans/include/notification_dialog_manager.h b/services/ans/include/notification_dialog_manager.h index 67dc1361983eeeb7d06ca9d5a64799f1c8447de0..2d8b6387723dc14f33af1c7140a9e6b777a81575 100644 --- a/services/ans/include/notification_dialog_manager.h +++ b/services/ans/include/notification_dialog_manager.h @@ -101,6 +101,13 @@ public: * @return ERR_OK when add Dialog successfully */ ErrCode AddDialogInfo(const sptr& bundle, const sptr& callback); + + /* + * RemoveDialogInfoByBundleOption + * @return void + */ + void RemoveDialogInfoByBundleOption(const sptr& bundle, + std::unique_ptr& dialogInfoRemoved); inline static const std::string NOTIFICATION_DIALOG_SERVICE_BUNDLE = "com.ohos.notificationdialog"; inline static const std::string NOTIFICATION_DIALOG_SERVICE_ABILITY = "EnableNotificationDialog"; @@ -112,9 +119,6 @@ private: // bundle need to be not null bool AddDialogInfoIfNotExist(const sptr& bundle, const sptr& callback); sptr GetBundleOptionByBundleName(const std::string& bundleName, const int32_t& uid); - // bundle need to be not null - void RemoveDialogInfoByBundleOption(const sptr& bundle, - std::unique_ptr& dialogInfoRemoved); void RemoveAllDialogInfos(std::list>& dialogInfosRemoved); bool OnDialogButtonClicked(const std::string& bundleName, const int32_t& uid, bool enabled); diff --git a/services/ans/include/notification_extension_wrapper.h b/services/ans/include/notification_extension_wrapper.h index 88d465c857969d6c7cee0830d3f855014dd95a09..70fa48e2d262eb5a3cb3cda00c235a6e3a8ccef8 100644 --- a/services/ans/include/notification_extension_wrapper.h +++ b/services/ans/include/notification_extension_wrapper.h @@ -41,6 +41,7 @@ public: typedef int32_t (*LOCAL_CONTROL)(const sptr &request); typedef void (*UPDATE_BY_BUNDLE)(const std::string bundleName, int deleteType); typedef int32_t (*REMINDER_CONTROL)(const std::string &bundleName); + typedef int32_t (*BANNER_CONTROL)(const std::string &bundleName); ErrCode SyncAdditionConfig(const std::string& key, const std::string& value); void UpdateByCancel(const std::vector>& notifications, int deleteReason); @@ -51,6 +52,7 @@ public: int32_t LocalControl(const sptr &request); void UpdateByBundle(const std::string bundleName, int deleteType); int32_t ReminderControl(const std::string &bundleName); + int32_t BannerControl(const std::string &bundleName); private: static int32_t convertToDelType(int32_t deleteReason); @@ -64,6 +66,7 @@ private: LOCAL_CONTROL localControl_ = nullptr; UPDATE_BY_BUNDLE updateByBundle_ = nullptr; REMINDER_CONTROL reminderControl_ = nullptr; + BANNER_CONTROL bannerControl_ = nullptr; bool isRegisterDataSettingObserver = false; }; diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 2f75ed6e279f3edacbc7781c44b297fb4f9a5dc6..9665a58859b71dfcccc256483cb4781483fa8610 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -23,6 +23,7 @@ #include "notification_preferences_database.h" #include #include +#include "notification_clone_bundle_info.h" namespace OHOS { namespace Notification { @@ -313,7 +314,7 @@ public: */ ErrCode SetDistributedEnabledByBundle(const sptr &bundleOption, const std::string &deviceType, const bool enabled); - + /** * @brief Get Enable smartphone to collaborate with other devices for intelligent reminders * @@ -359,7 +360,13 @@ public: */ bool GetBundleSoundPermission(bool &allPackage, std::set &bundleNames); - void InitSettingFromDisturbDB(); + ErrCode UpdateDoNotDisturbProfiles(int32_t userId, int32_t profileId, + const std::string& name, const std::vector& bundleList); + + void UpdateProfilesUtil(std::vector& trustList, + const std::vector bundleList); + + void InitSettingFromDisturbDB(int32_t userId = -1); void RemoveSettings(int32_t userId); void RemoveAnsBundleDbInfo(const sptr &bundleOption); void RemoveEnabledDbByBundle(const sptr &bundleOption); @@ -370,11 +377,19 @@ public: int32_t GetBatchKvsFromDb( const std::string &key, std::unordered_map &values, const int32_t &userId); int32_t DeleteKvFromDb(const std::string &key, const int &userId); + int32_t DeleteBatchKvFromDb(const std::vector &keys, const int &userId); ErrCode GetDoNotDisturbProfile(int32_t profileId, int32_t userId, sptr &profile); bool CheckDoNotDisturbProfileID(int32_t profileId); void RemoveDoNotDisturbProfileTrustList(int32_t userId, const sptr &bundleOption); + void GetDoNotDisturbProfileListByUserId(int32_t userId, + std::vector> &profiles); + void GetAllCLoneBundlesInfo(int32_t userId, std::vector &cloneBundles); + void UpdateCloneBundleInfo(int32_t userId, const NotificationCloneBundleInfo& cloneBundleInfo); + bool IsNotificationSlotFlagsExists(const sptr &bundleOption); private: + bool GetBundleInfo(NotificationPreferencesInfo &preferencesInfo, + const sptr &bundleOption, NotificationPreferencesInfo::BundleInfo &info) const; ErrCode CheckSlotForCreateSlot(const sptr &bundleOption, const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const; ErrCode CheckSlotForRemoveSlot(const sptr &bundleOption, @@ -398,7 +413,7 @@ private: static std::shared_ptr instance_; NotificationPreferencesInfo preferencesInfo_ {}; std::mutex preferenceMutex_; - std::unique_ptr preferncesDB_ = nullptr; + std::shared_ptr preferncesDB_ = nullptr; }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index f4ecb94f3d3dd78d88913968106e0004f3638477..00b49d0353df77c48de1a0dbbfaf18f6be3e6e2a 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -87,7 +87,7 @@ public: */ bool PutNotificationsEnabledForBundle( const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enabled); - + /** * @brief Put distributed enable notification in the of bundle into disturbe DB. * @@ -161,7 +161,7 @@ public: * @param info Indicates notification info. * @return Return true on success, false on failure. */ - bool ParseFromDisturbeDB(NotificationPreferencesInfo &info); + bool ParseFromDisturbeDB(NotificationPreferencesInfo &info, int32_t userId = -1); /** * @brief Delete all data from disturbe DB. @@ -207,6 +207,16 @@ public: */ bool RemoveAllSlotsFromDisturbeDB(const std::string &bundleKey, const int32_t &bundleUid); + /** + * @brief Get bundleInfo from DB. + * + * @param bundleOption Indicates the bundle bundleOption. + * @param bundleInfo Indicates bundle info. + * @return Return true on success, false on failure. + */ + bool GetBundleInfo(const sptr &bundleOption, + NotificationPreferencesInfo::BundleInfo &bundleInfo); + /** * @brief Query whether there is a agent relationship between the two apps. * @@ -231,7 +241,13 @@ public: int32_t GetBatchKvsFromDb( const std::string &key, std::unordered_map &values, const int32_t &userId); int32_t DeleteKvFromDb(const std::string &key, const int32_t &userId); + int32_t DeleteBatchKvFromDb(const std::vector &keys, const int &userId); int32_t DropUserTable(const int32_t userId); + bool UpdateBundlePropertyToDisturbeDB(int32_t userId, const NotificationPreferencesInfo::BundleInfo &bundleInfo); + bool UpdateBundleSlotToDisturbeDB(int32_t userId, const std::string &bundleName, + const int32_t &bundleUid, const std::vector> &slots); + bool IsNotificationSlotFlagsExists(const sptr &bundleOption); + private: bool CheckRdbStore(); @@ -318,6 +334,7 @@ private: const std::string &findString, const int32_t &userId); void ExecuteDisturbeDB(sptr &slot, std::string &typeStr, std::string &valueStr, const std::string &findString, const int32_t &userId); + bool CheckApiCompatibility(const std::string &bundleName, const int32_t &uid); std::shared_ptr rdbDataManager_; }; } // namespace Notification diff --git a/services/ans/include/notification_preferences_info.h b/services/ans/include/notification_preferences_info.h index 0ec01aaf51f3d889dd73070b638d366d080f008d..18c9e5ca1da4f82cde05e50184aeeb1e5e485515 100644 --- a/services/ans/include/notification_preferences_info.h +++ b/services/ans/include/notification_preferences_info.h @@ -25,6 +25,7 @@ #include "notification_slot.h" #include "preferences_constant.h" #include "advanced_notification_service.h" +#include "notification_clone_bundle_info.h" namespace OHOS { namespace Notification { @@ -236,6 +237,7 @@ public: */ NotificationPreferencesInfo() {} + /** * @brief Default destructor. */ @@ -315,6 +317,8 @@ public: void RemoveDoNotDisturbProfiles(int32_t userId, const std::vector> &profiles); bool GetDoNotDisturbProfiles(int32_t profileId, int32_t userId, sptr &profiles); void GetAllDoNotDisturbProfiles(int32_t userId, std::vector> &profiles); + void GetAllCLoneBundlesInfo(const int32_t &userId, const std::unordered_map &bunlesMap, + std::vector &cloneBundles); private: std::map isEnabledAllNotification_; @@ -324,4 +328,4 @@ private: }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_NOTIFICATION_PREFERENCES_INFO_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_NOTIFICATION_PREFERENCES_INFO_H diff --git a/services/ans/include/notification_rdb_data_mgr.h b/services/ans/include/notification_rdb_data_mgr.h index 36a46b29c050c1d2ac1d9ce59943c33b798163ce..58855f1445b2d90a6b417080ef37cb8453106274 100644 --- a/services/ans/include/notification_rdb_data_mgr.h +++ b/services/ans/include/notification_rdb_data_mgr.h @@ -158,6 +158,7 @@ private: std::unordered_map &values); int32_t QueryAllData(const std::string tableName, std::unordered_map &datas); int32_t InitCreatedTables(); + int32_t RestoreForMasterSlaver(); private: NotificationRdbConfig notificationRdbConfig_; diff --git a/services/ans/include/notification_record.h b/services/ans/include/notification_record.h index fa847daae4931fef6f8a0a6b2611ada9af92ded6..d1e78b6e7d26427f3597b1b9d88d7abee7d9742c 100644 --- a/services/ans/include/notification_record.h +++ b/services/ans/include/notification_record.h @@ -33,6 +33,8 @@ struct NotificationRecord { sptr notification; sptr slot; int32_t finish_status = -1; + bool isThirdparty {true}; + bool isNeedFlowCtrl {true}; #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED std::string deviceId; std::string bundleName; diff --git a/services/ans/include/notification_timer_info.h b/services/ans/include/notification_timer_info.h index d7229f3f446c92ede04c64ddc4c4cca4c45c7d35..17d82f567c8a66d894fbe7ee7c39c0c197c459ed 100644 --- a/services/ans/include/notification_timer_info.h +++ b/services/ans/include/notification_timer_info.h @@ -52,9 +52,10 @@ public: void SetCallbackInfo(const std::function &callBack); + std::function GetCallBack(); private: std::function callBack_ = nullptr; }; } // namespace OHOS } // namespace Notification -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_TIMER_INFO_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_TIMER_INFO_H diff --git a/services/ans/include/notification_trust_list.h b/services/ans/include/notification_trust_list.h index f7b1083c0918e2340f320887aa61ce9c5b516bbd..12ab1d1ee7124ccc70b590098c1cd1e3cdeb141c 100644 --- a/services/ans/include/notification_trust_list.h +++ b/services/ans/include/notification_trust_list.h @@ -34,9 +34,11 @@ public: void GetCcmPrivilegesConfig(); + bool IsLiveViewTrtust(const std::string bundleName); bool IsSlotFlagsTrustlistAsBundle(const sptr &bundleOption); bool IsReminderTrustList(const std::string& bundleName); private: + std::set liveViewTrustlist_; std::set reminderTrustlist_; std::set notificationSlotFlagsTrustlist_; constexpr static inline const uint32_t PRIVILEGES_CONFIG_MIN_LEN = 2; diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index 93b657874f95760d2688883ec4cd64543c60ebed..f7c92ee80c4659d0747deef70c801e5e553f7192 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -106,7 +106,7 @@ public: * @param want Want information that transferred when the event trigger by user. * @param cancelNotification Indicates whether need to cancel notification or not. */ - void CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification); + void CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification, bool isButtonClick = true); /** * Dump all the reminders information. @@ -157,7 +157,15 @@ public: void OnUserRemove(const int32_t& userId); - void OnServiceStart(); + /** + * @brief Bundle manager service start. + */ + void OnBundleMgrServiceStart(); + + /** + * @brief Ability manager service start. + */ + void OnAbilityMgrServiceStart(); void OnUserSwitch(const int32_t& userId); @@ -245,20 +253,13 @@ public: */ void TerminateAlerting(const OHOS::EventFwk::Want &want); - /** - * @brief Get resource manager by handle info. - */ - std::shared_ptr GetBundleResMgr( - const AppExecFwk::BundleInfo &bundleInfo); - /** * @brief Update reminders based on the system language. * * Update action button title. */ - void UpdateReminderLanguage(const sptr &reminder); - void UpdateReminderLanguageLocked(const sptr &reminder); - + void UpdateReminderLanguageLocked(const int32_t uid, const std::vector>& reminders); + /** * @brief System language change */ @@ -269,6 +270,11 @@ public: */ void OnRemoveAppMgr(); + /** + * @brief Whether the device is ready or not. + */ + bool IsSystemReady(); + static constexpr uint8_t TIME_ZONE_CHANGE = 0; static constexpr uint8_t DATE_TIME_CHANGE = 1; @@ -418,14 +424,6 @@ private: */ sptr FindReminderRequestLocked(const int32_t &reminderId, const std::string &pkgName); - /** - * Find bundle option from {@link notificationBundleOptionMap_} by reminder id. - * - * @param reminderId Indicates the reminder id. - * @return pointer of NotificationBundleOption or nullptr. - */ - sptr FindNotificationBundleOption(const int32_t &reminderId) const; - /** * Obtains the recent reminder which is not expired from reminder vector. * @@ -436,7 +434,7 @@ private: sptr GetRecentReminderLocked(); void HandleImmediatelyShow(std::vector> &showImmediately, bool isSysTimeChanged); - void HandleExtensionReminder(std::vector> &extensionReminders); + void HandleExtensionReminder(std::vector> &extensionReminders, const int8_t type); /** * @brief Refresh the reminder due to date/time or timeZone change by user. @@ -538,9 +536,11 @@ private: void SetActiveReminder(const sptr &reminder); void SetAlertingReminder(const sptr &reminder); - void ShowActiveReminderExtendLocked(sptr &reminder); - static bool StartExtensionAbility(const sptr &reminder); - static void AsyncStartExtensionAbility(const sptr &reminder, int32_t times); + void ShowActiveReminderExtendLocked(sptr &reminder, + std::vector>& extensionReminders); + static bool StartExtensionAbility(const sptr &reminder, const int8_t type); + static void AsyncStartExtensionAbility(const sptr &reminder, + int32_t times, const int8_t type); void InitServiceHandler(); /** * @brief Show the reminder on SystemUI. @@ -640,11 +640,36 @@ private: bool IsActionButtonDataShareValid(const sptr& reminder, const uint32_t callerTokenId); + /** + * @brief Get resource manager by bundlename and uid. + */ + std::shared_ptr GetResourceMgr(const std::string& bundleName, + const int32_t uid); + + /** + * @brief Get custom ring file desc. + * lock by resourceMutex_ in function + */ + bool GetCustomRingFileDesc(const sptr& reminder, + Global::Resource::ResourceManager::RawFileDescriptor& desc); + + /** + * @brief Close custom ring file desc. + * lock by resourceMutex_ in function + */ + void CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri); + /** * @brief report event to dfx */ void ReportSysEvent(const sptr& reminder); + ErrCode PublishNotificationRequest(sptr& request, + const sptr& bundleOption); + + bool CheckShowLimit(std::unordered_map& limits, int32_t& totalCount, + sptr& reminder); + /** * Single instance. */ @@ -686,11 +711,6 @@ private: */ std::vector> showedReminderVector_; - /** - * Map used to record all the bundle information of the reminders in system. - */ - std::map> notificationBundleOptionMap_; - /** * This timer is used to control the triggerTime of next reminder. */ @@ -714,6 +734,8 @@ private: sptr alertingReminder_ = nullptr; #ifdef PLAYER_FRAMEWORK_ENABLE std::shared_ptr soundPlayer_ = nullptr; + std::mutex resourceMutex_; // for soundResource_ + std::shared_ptr soundResource_ = nullptr; #endif /** * Indicates the total count of reminders in system. @@ -738,6 +760,11 @@ private: * async queue */ std::shared_ptr queue_ = nullptr; + + /** + * Sa ready flag + */ + std::atomic saReadyFlag_{ 0 }; }; } // namespace OHOS } // namespace Notification diff --git a/interfaces/inner_api/reminder_store.h b/services/ans/include/reminder_store.h similarity index 100% rename from interfaces/inner_api/reminder_store.h rename to services/ans/include/reminder_store.h diff --git a/services/ans/include/reminder_store_strategy.h b/services/ans/include/reminder_store_strategy.h new file mode 100644 index 0000000000000000000000000000000000000000..0d0ccefb6af063a12c980bddde7af739176e9f5c --- /dev/null +++ b/services/ans/include/reminder_store_strategy.h @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H + +#include +#include + +#include "reminder_request.h" +#include "rdb_store.h" + +namespace OHOS { +namespace Notification { +class ReminderStrategy { +public: + /** + * @brief Gets the value from rdb result. + * + * @param resultSet the rdb result. + * @param name the column name in rdb. + * @param value the column value in rdb. + */ + template + static void GetRdbValue(const std::shared_ptr& resultSet, + const std::string& name, T& value); + +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket &values, const bool oldVersion = false); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& resultSet); + +private: + /** + * @brief Recovery time related fields from the database(old version rdb). + */ + static void RecoverTimeFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery id related fields from the database(old version rdb). + */ + static void RecoverIdFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery context related from the database(old version rdb). + */ + static void RecoverContextFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Recovery time related fields from the database. + */ + static void RecoverTimeFromDb(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery id related fields from the database. + */ + static void RecoverIdFromDb(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery context related from the database. + */ + static void RecoverContextFromDb(sptr& reminder, + const std::shared_ptr& resultSet); +}; + +class ReminderTimerStrategy { +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, + const std::shared_ptr& resultSet); +}; + +class ReminderAlarmStrategy { +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, + const std::shared_ptr& resultSet); +}; + +class ReminderCalendarStrategy { +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, + const std::shared_ptr& resultSet); + +private: + static void RecoverTime(sptr& reminder, const std::shared_ptr& resultSet); +}; + +template +void ReminderStrategy::GetRdbValue(const std::shared_ptr& resultSet, + const std::string& name, T& value) +{ + value = T(); + int32_t columnIndex = -1; + resultSet->GetColumnIndex(name, columnIndex); + if (columnIndex == -1) { + ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); + return; + } + + if constexpr (std::is_same_v) { + resultSet->GetString(columnIndex, value); + } else if constexpr (std::is_same_v) { + resultSet->GetLong(columnIndex, value); + } else if constexpr (std::is_same_v) { + int64_t t = 0; + resultSet->GetLong(columnIndex, t); + value = static_cast(t); + } else if constexpr (std::is_same_v) { + resultSet->GetInt(columnIndex, value); + } else if constexpr (std::is_same_v) { + int32_t t = 0; + resultSet->GetInt(columnIndex, t); + value = static_cast(t); + } else if constexpr (std::is_same_v) { + int32_t t = 0; + resultSet->GetInt(columnIndex, t); + value = static_cast(t); + } else if constexpr (std::is_same_v) { + int32_t t = 0; + resultSet->GetInt(columnIndex, t); + value = static_cast(t); + } +} +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H \ No newline at end of file diff --git a/interfaces/inner_api/reminder_table.h b/services/ans/include/reminder_table.h similarity index 100% rename from interfaces/inner_api/reminder_table.h rename to services/ans/include/reminder_table.h diff --git a/interfaces/inner_api/reminder_table_old.h b/services/ans/include/reminder_table_old.h similarity index 100% rename from interfaces/inner_api/reminder_table_old.h rename to services/ans/include/reminder_table_old.h diff --git a/services/ans/include/report_timer_info.h b/services/ans/include/report_timer_info.h new file mode 100644 index 0000000000000000000000000000000000000000..44b1d5d827b2a3c30efc1e9fc04fcda9a8203200 --- /dev/null +++ b/services/ans/include/report_timer_info.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_REPORT_TIMER_INFO_H +#define BASE_NOTIFICATION_DISTRIBUTED_REPORT_TIMER_INFO_H + +#include "notification_timer_info.h" +#include "in_process_call_wrapper.h" + +namespace OHOS { +namespace Notification { +class ReportTimerInfo : public NotificationTimerInfo { +public: + virtual ~ReportTimerInfo() {}; + ReportTimerInfo() {}; + /** + * When timing is up, this function will execute as call back. + */ + void OnTrigger() override; +}; +} // namespace OHOS +} // namespace Notification +#endif // BASE_NOTIFICATION_DISTRIBUTED_REPORT_TIMER_INFO_H diff --git a/services/ans/include/smart_reminder_center.h b/services/ans/include/smart_reminder_center.h index 8fb58b2602c776907e17824e40f0970a9f175748..d9b09cd29c3b47dde1c456c234935b6d5c02f53b 100644 --- a/services/ans/include/smart_reminder_center.h +++ b/services/ans/include/smart_reminder_center.h @@ -78,7 +78,7 @@ private: const sptr &request, vector> &reminderAffecteds) const; void GetDeviceStatusByType(const string &deviceType, bitset &bitStatus) const; - bool IsNeedSynergy(const string &deviceType, const string &ownerBundleName) const; + bool IsNeedSynergy(const string &deviceType, const string &ownerBundleName, int32_t ownerUid) const; map> currentReminderMethods_; map>>> reminderMethods_; diff --git a/services/ans/include/system_dialog_connect_stb.h b/services/ans/include/system_dialog_connect_stb.h index 89f09b2a5cca64e72267b1b130972b02707c56ec..3b0ad5be20f44f96ba24b9f63c27a41ae9010ec3 100644 --- a/services/ans/include/system_dialog_connect_stb.h +++ b/services/ans/include/system_dialog_connect_stb.h @@ -38,8 +38,6 @@ public: const sptr &remoteObject, int32_t resultCode) override; void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int32_t resultCode) override; - void SendRemoveBundleEvent(); - private: std::string commandStr_; }; diff --git a/services/ans/include/system_event_observer.h b/services/ans/include/system_event_observer.h index 132200d76460940235ee004178b4edf6299ba29e..e072e87b988f456837f7b1540561280cb5835a69 100644 --- a/services/ans/include/system_event_observer.h +++ b/services/ans/include/system_event_observer.h @@ -44,6 +44,7 @@ private: void OnReceiveEvent(const EventFwk::CommonEventData &data); void OnReceiveEventInner(const EventFwk::CommonEventData &data); sptr GetBundleOption(AAFwk::Want want); + sptr GetBundleOptionDataCleared(AAFwk::Want want); void OnBundleUpdateEventInner(const EventFwk::CommonEventData &data); void OnBundleAddEventInner(const EventFwk::CommonEventData &data); diff --git a/services/ans/include/telephony_extension_wrapper.h b/services/ans/include/telephony_extension_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..56e05d5f49eb06867a204286f1efb3a9180f0745 --- /dev/null +++ b/services/ans/include/telephony_extension_wrapper.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_SERVICES_TELEPHONY_EXTENSION_WRAPPER_H +#define BASE_NOTIFICATION_ANS_SERVICES_TELEPHONY_EXTENSION_WRAPPER_H + +#include + +#include "singleton.h" +#include "datashare_helper.h" + +namespace OHOS::Notification { +class TelExtensionWrapper final { + DECLARE_DELAYED_SINGLETON(TelExtensionWrapper); +public: + void InitTelExtentionWrapper(); + void CloseTelExtentionWrapper(); + typedef ErrCode (*GET_CALLER_INDEX)(std::shared_ptr resultSet, std::string compNum); + ErrCode GetCallerIndex(std::shared_ptr resultSet, std::string compNum); +private: + void* telephonyCustHandle_ = nullptr; + GET_CALLER_INDEX getCallerIndex_ = nullptr; +}; + +#define TEL_EXTENTION_WRAPPER ::OHOS::DelayedSingleton::GetInstance() +} // namespace OHOS::Notification +#endif // BASE_NOTIFICATION_ANS_SERVICES_TELEPHONY_EXTENSION_WRAPPER_H \ No newline at end of file diff --git a/services/ans/src/access_token_helper.cpp b/services/ans/src/access_token_helper.cpp index e0c636abdcca30336025d15716484e9fbad07d3c..a3d66115d7b7e8dc06f5f86f92093ec1fd0125da 100644 --- a/services/ans/src/access_token_helper.cpp +++ b/services/ans/src/access_token_helper.cpp @@ -80,21 +80,13 @@ bool AccessTokenHelper::VerifyShellToken(const AccessTokenID &callerToken) bool AccessTokenHelper::CheckPermission(const std::string &permission) { ANS_LOGD("%{public}s", __FUNCTION__); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1); - if (supportCheckSaPermission_.compare("non-initilization") == 0) { - supportCheckSaPermission_ = OHOS::system::GetParameter(NOTIFICATION_ANS_CHECK_SA_PERMISSION, "false"); - } auto tokenCaller = IPCSkeleton::GetCallingTokenID(); - if (supportCheckSaPermission_.compare("true") != 0) { - bool isSubsystem = VerifyNativeToken(tokenCaller); - if (isSubsystem) { - return true; - } - } + int32_t callingUid = IPCSkeleton::GetCallingUid(); + int32_t callingPid = IPCSkeleton::GetCallingPid(); bool result = VerifyCallerPermission(tokenCaller, permission); if (!result) { - message.Message("Permission denied: " + permission, true); - NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("CheckPermission failed %{public}s, %{public}d, %{public}d", + permission.c_str(), callingUid, callingPid); } return result; } diff --git a/services/ans/src/advanced_datashare_helper.cpp b/services/ans/src/advanced_datashare_helper.cpp index 3964264597e08b410360cdb4e017dfb2d07d70df..516b55b5f8e4a8498a3b82e46e41aadc1e7918b1 100644 --- a/services/ans/src/advanced_datashare_helper.cpp +++ b/services/ans/src/advanced_datashare_helper.cpp @@ -22,6 +22,8 @@ #include "os_account_manager.h" #include "singleton.h" #include "system_ability_definition.h" +#include "ipc_skeleton.h" +#include "telephony_extension_wrapper.h" namespace OHOS { namespace Notification { @@ -35,9 +37,29 @@ constexpr const char *USER_SETTINGS_DATA_SECURE_URI = "datashare:///com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_SECURE_"; constexpr const char *FOCUS_MODE_ENABLE_URI = "?Proxy=true&key=focus_mode_enable"; constexpr const char *FOCUS_MODE_PROFILE_URI = "?Proxy=true&key=focus_mode_profile"; +constexpr const char *FOCUS_MODE_CALL_POLICY_URI = "?Proxy=true&key=focus_mode_call_message_policy"; +constexpr const char *FOCUS_MODE_REPEAT_CALLERS_ENABLE_URI = "?Proxy=true&key=focus_mode_repeate_callers_enable"; constexpr const char *UNIFIED_GROUP_ENABLE_URI = "?Proxy=true&key=unified_group_enable"; +constexpr const char *CONTACT_URI = "datashare:///com.ohos.contactsdataability"; +constexpr const char *CALLLOG_URI = "datashare:///com.ohos.calllogability"; +constexpr const char *CALL_SUBSECTION = "datashare:///com.ohos.calllogability/calls/calllog?Proxy=true"; +constexpr const char *PHONE_NUMBER = "phone_number"; +constexpr const char *IS_DELETED = "is_deleted"; +constexpr const char *TYPE_ID = "type_id"; +constexpr const char *DETAIL_INFO = "detail_info"; +constexpr const char *FORMAT_PHONE_NUMBER = "format_phone_number"; +constexpr const char *FAVORITE = "favorite"; +constexpr const char *FOCUS_MODE_LIST = "focus_mode_list"; constexpr const char *ADVANCED_DATA_COLUMN_KEYWORD = "KEYWORD"; constexpr const char *ADVANCED_DATA_COLUMN_VALUE = "VALUE"; +constexpr const char *CALL_DIRECTION = "call_direction"; +constexpr const char *CREATE_TIME = "create_time"; +constexpr const unsigned int PHONE_NUMBER_LENGTH = 7; +constexpr const unsigned int MAX_TIME_INTERVAL = 15 * 60; +constexpr const int TYPE_ID_FIVE = 5; +constexpr const int ERROR_QUERY_INFO_FAILED = -1; +constexpr const int QUERY_INFO_SUCCESS = 1; +std::vector QUERY_CONTACT_COLUMN_LIST = {FORMAT_PHONE_NUMBER, FAVORITE, FOCUS_MODE_LIST, DETAIL_INFO}; } // namespace AdvancedDatashareHelper::AdvancedDatashareHelper() { @@ -59,6 +81,21 @@ std::shared_ptr AdvancedDatashareHelper::CreateDataS return DataShare::DataShareHelper::Creator(remoteObj, SETTINGS_DATASHARE_URI, SETTINGS_DATA_EXT_URI); } +std::shared_ptr AdvancedDatashareHelper::CreateContactDataShareHelper(std::string uri) +{ + sptr saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (saManager == nullptr) { + ANS_LOGE("The sa manager is nullptr."); + return nullptr; + } + sptr remoteObj = saManager->GetSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID); + if (remoteObj == nullptr) { + ANS_LOGE("The remoteObj is nullptr."); + return nullptr; + } + return DataShare::DataShareHelper::Creator(remoteObj, uri); +} + bool AdvancedDatashareHelper::Query(Uri &uri, const std::string &key, std::string &value) { std::shared_ptr dataShareHelper = CreateDataShareHelper(); @@ -90,6 +127,131 @@ bool AdvancedDatashareHelper::Query(Uri &uri, const std::string &key, std::strin return true; } +ErrCode AdvancedDatashareHelper::QueryContact(Uri &uri, const std::string &phoneNumber, const std::string &policy) +{ + std::string identity = IPCSkeleton::ResetCallingIdentity(); + std::shared_ptr helper = CreateContactDataShareHelper(CONTACT_URI); + if (helper == nullptr) { + ANS_LOGE("The data share helper is nullptr."); + return ERROR_QUERY_INFO_FAILED; + } + DataShare::DataSharePredicates predicates; + predicates.EqualTo(IS_DELETED, 0); + predicates.EqualTo(TYPE_ID, TYPE_ID_FIVE); + if (phoneNumber.size() >= PHONE_NUMBER_LENGTH) { + predicates.EndsWith(DETAIL_INFO, + phoneNumber.substr(phoneNumber.size() - PHONE_NUMBER_LENGTH, phoneNumber.size())); + } else { + predicates.EqualTo(DETAIL_INFO, phoneNumber); + } + auto resultSet = helper->Query(uri, predicates, QUERY_CONTACT_COLUMN_LIST); + IPCSkeleton::SetCallingIdentity(identity); + if (resultSet == nullptr) { + ANS_LOGE("Query error, resultSet is null."); + helper->Release(); + return ERROR_QUERY_INFO_FAILED; + } + int isFound = 0; + int rowCount = 0; + resultSet->GetRowCount(rowCount); + if (rowCount <= 0) { + ANS_LOGI("Query success, but rowCount is 0."); + } else { + int resultId = -1; +#ifdef ENABLE_ANS_TELEPHONY_CUST_WRAPPER + resultId = TEL_EXTENTION_WRAPPER->GetCallerIndex(resultSet, phoneNumber); + ANS_LOGI("QueryContact resultId: %{public}d.", resultId); +#endif + if ((phoneNumber.size() >= PHONE_NUMBER_LENGTH && resultSet->GoToRow(resultId) == DataShare::E_OK) || + (phoneNumber.size() < PHONE_NUMBER_LENGTH && resultSet->GoToFirstRow() == DataShare::E_OK)) { + isFound = dealWithContactResult(helper, resultSet, policy) ? QUERY_INFO_SUCCESS : ERR_OK; + } + } + resultSet->Close(); + helper->Release(); + return isFound; +} + +bool AdvancedDatashareHelper::dealWithContactResult(std::shared_ptr helper, + std::shared_ptr resultSet, const std::string &policy) +{ + bool isNoNeedSilent = false; + int32_t columnIndex; + int32_t favorite; + std::string focus_mode_list; + switch (atoi(policy.c_str())) { + case ContactPolicy::ALLOW_FAVORITE_CONTACTS: + do { + resultSet->GetColumnIndex(FAVORITE, columnIndex); + resultSet->GetInt(columnIndex, favorite); + isNoNeedSilent = favorite == 1; + if (isNoNeedSilent) { + break; + } + } while (resultSet->GoToNextRow() == DataShare::E_OK); + ANS_LOGI("dealWithContactResult: favorite = %{public}d", favorite); + break; + case ContactPolicy::ALLOW_SPECIFIED_CONTACTS: + do { + resultSet->GetColumnIndex(FOCUS_MODE_LIST, columnIndex); + resultSet->GetString(columnIndex, focus_mode_list); + if (focus_mode_list.empty() || focus_mode_list.c_str()[0] == '0') { + isNoNeedSilent = false; + } + if (focus_mode_list.c_str()[0] == '1') { + isNoNeedSilent = true; + break; + } + } while (resultSet->GoToNextRow() == DataShare::E_OK); + ANS_LOGI("dealWithContactResult: focus_mode_list = %{public}s", focus_mode_list.c_str()); + break; + default: + isNoNeedSilent = true; + break; + } + return isNoNeedSilent; +} + +bool AdvancedDatashareHelper::isRepeatCall(const std::string &phoneNumber) +{ + std::string identity = IPCSkeleton::ResetCallingIdentity(); + std::shared_ptr helper = CreateContactDataShareHelper(CALLLOG_URI); + if (helper == nullptr) { + ANS_LOGE("The data share helper is nullptr."); + return false; + } + bool isRepeat = false; + DataShare::DataSharePredicates predicates; + std::vector columns; + Uri uri(CALL_SUBSECTION); + predicates.EqualTo(PHONE_NUMBER, phoneNumber); + predicates.EqualTo(CALL_DIRECTION, 0); + predicates.OrderByDesc(CREATE_TIME); + columns.push_back(CREATE_TIME); + auto resultSet = helper->Query(uri, predicates, columns); + IPCSkeleton::SetCallingIdentity(identity); + if (resultSet == nullptr) { + helper->Release(); + return false; + } + int rowCount = 0; + resultSet->GetRowCount(rowCount); + if (rowCount > 0) { + int32_t callTime = 0; + if (resultSet->GoToFirstRow() == 0) { + int32_t columnIndex; + resultSet->GetColumnIndex(CREATE_TIME, columnIndex); + resultSet->GetInt(columnIndex, callTime); + } + if (time(NULL) - callTime < MAX_TIME_INTERVAL) { + isRepeat = true; + } + } + resultSet->Close(); + helper->Release(); + return isRepeat; +} + std::string AdvancedDatashareHelper::GetFocusModeEnableUri(const int32_t &userId) const { return USER_SETTINGS_DATA_SECURE_URI + std::to_string(userId) + FOCUS_MODE_ENABLE_URI; @@ -99,5 +261,15 @@ std::string AdvancedDatashareHelper::GetFocusModeProfileUri(const int32_t &userI { return USER_SETTINGS_DATA_SECURE_URI + std::to_string(userId) + FOCUS_MODE_PROFILE_URI; } + +std::string AdvancedDatashareHelper::GetFocusModeCallPolicyUri(const int32_t &userId) const +{ + return USER_SETTINGS_DATA_URI + std::to_string(userId) + FOCUS_MODE_CALL_POLICY_URI; +} + +std::string AdvancedDatashareHelper::GetFocusModeRepeatCallUri(const int32_t &userId) const +{ + return USER_SETTINGS_DATA_URI + std::to_string(userId) + FOCUS_MODE_REPEAT_CALLERS_ENABLE_URI; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_datashare_helper_ext.cpp b/services/ans/src/advanced_datashare_helper_ext.cpp index 347f9dd032be762cbdceeeb1ee65743bb9551850..48415abff7317c471c889ee67b593df97e72731e 100644 --- a/services/ans/src/advanced_datashare_helper_ext.cpp +++ b/services/ans/src/advanced_datashare_helper_ext.cpp @@ -20,8 +20,10 @@ #include "iservice_registry.h" #include "message_parcel.h" #include "os_account_manager.h" +#include "os_account_manager_helper.h" #include "singleton.h" #include "system_ability_definition.h" +#include namespace OHOS { namespace Notification { @@ -88,13 +90,9 @@ bool AdvancedDatashareHelperExt::Query(Uri &uri, const std::string &key, std::st std::string AdvancedDatashareHelperExt::GetUnifiedGroupEnableUri() const { - std::vector accountIds; - OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountIds); - std::string userId = "100"; - if (!accountIds.empty()) { - userId = std::to_string(accountIds[0]); - } - return USER_SETTINGS_DATA_SECURE_URI + userId + UNIFIED_GROUP_ENABLE_URI; + int32_t userId = 100; + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId); + return USER_SETTINGS_DATA_SECURE_URI + std::to_string(userId) + UNIFIED_GROUP_ENABLE_URI; } } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_datashare_observer.cpp b/services/ans/src/advanced_datashare_observer.cpp index bcce592880b24e2224a7e243fc608a5e77b98130..36c441163cb4c4352f2096e49d2db4434065d04a 100644 --- a/services/ans/src/advanced_datashare_observer.cpp +++ b/services/ans/src/advanced_datashare_observer.cpp @@ -74,7 +74,6 @@ void AdvancedDatashareObserver::RegisterSettingsObserver( return; } settingHelper->RegisterObserver(uri, dataObserver); - settingHelper->Release(); } bool AdvancedDatashareObserver::CheckIfSettingsDataReady() diff --git a/services/ans/src/advanced_notification_clone_service.cpp b/services/ans/src/advanced_notification_clone_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0d7a8f978e58a756ec218254bf7be531f9dc60e --- /dev/null +++ b/services/ans/src/advanced_notification_clone_service.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "advanced_notification_service.h" + +#include "notification_clone_manager.h" +namespace OHOS { +namespace Notification { + +constexpr int32_t INVALID_FD_NUM = -1; +constexpr int32_t PERMISSION_NUM = 0660; +constexpr const char *EXTENSION_SUCCESS = "notification extension success"; + +int32_t AdvancedNotificationService::OnBackup(MessageParcel& data, MessageParcel& reply) +{ + return NotificationCloneManager::GetInstance().OnBackup(data, reply); +} + +int32_t AdvancedNotificationService::OnRestore(MessageParcel& data, MessageParcel& reply) +{ +// todo double to single + return NotificationCloneManager::GetInstance().OnRestore(data, reply); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/ans/src/advanced_notification_flow_control_service.cpp b/services/ans/src/advanced_notification_flow_control_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..79b23e060cf68143d419ab458092e1010c8b9ee7 --- /dev/null +++ b/services/ans/src/advanced_notification_flow_control_service.cpp @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "advanced_notification_flow_control_service.h" + +#include "ans_inner_errors.h" +#include "notification_config_parse.h" +#include "notification_analytics_util.h" + +namespace OHOS { +namespace Notification { +std::mutex FlowControlService::flowControlMutex_; +std::mutex FlowControlService::systemFlowControlMutex_; +std::mutex FlowControlService::singleAppFlowControlMutex_; + +FlowControlService::FlowControlService() +{ + DelayedSingleton::GetInstance()->GetFlowCtrlConfigFromCCM(threshold_); +} + +ErrCode FlowControlService::FlowControl(const std::shared_ptr &record, + const int32_t callingUid, bool isNotificationExists) +{ + if (record->isNeedFlowCtrl == false) { + return ERR_OK; + } + + ErrCode result = ERR_OK; + if (!isNotificationExists) { + result = PublishFlowCtrl(record, callingUid); + } else { + result = UpdateFlowCtrl(record, callingUid); + } + + return result; +} + +ErrCode FlowControlService::PublishFlowCtrl(const std::shared_ptr &record, + const int32_t callingUid) +{ + if (record->isNeedFlowCtrl == false) { + return ERR_OK; + } + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + ErrCode result = ERR_OK; + result = PublishSingleAppFlowCtrl(record, now, callingUid); + if (result != ERR_OK) { + return result; + } + result = PublishGlobalFlowCtrl(record, now); + if (result != ERR_OK) { + return result; + } + PublishRecordTimestamp(record, now, callingUid); + PublishSingleAppFlowCtrlRemoveExpire(now); + return ERR_OK; +} + +ErrCode FlowControlService::PublishGlobalFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now) +{ + ANS_LOGD("PublishGlobalFlowCtrl size %{public}zu,%{public}zu", + flowControlPublishTimestampList_.size(), systemFlowControlPublishTimestampList_.size()); + if (record->isThirdparty == true) { + // Third-part flow control + std::lock_guard lock(flowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(flowControlPublishTimestampList_, now); + if (flowControlPublishTimestampList_.size() >= threshold_.maxCreateNumPerSecond) { + ANS_LOGE("Third-part PublishGlobalFlowCtrl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_2) + .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("Third-part PublishGlobalFlowCtrl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + } + } else { + // System flow control + std::lock_guard lock(systemFlowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(systemFlowControlPublishTimestampList_, now); + if (systemFlowControlPublishTimestampList_.size() >= threshold_.maxCreateNumPerSecond) { + ANS_LOGE("System PublishGlobalFlowCtrl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_3) + .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("System PublishGlobalFlowCtrl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + } + } + return ERR_OK; +} + +ErrCode FlowControlService::PublishSingleAppFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid) +{ + std::lock_guard lock(singleAppFlowControlMutex_); + auto singleAppFlowControlIter = singleAppFlowControlPublishTimestampMap_.find(callingUid); + if (singleAppFlowControlIter == singleAppFlowControlPublishTimestampMap_.end()) { + return ERR_OK; + } + NotificationAnalyticsUtil::RemoveExpired(*(singleAppFlowControlIter->second), now); + if (singleAppFlowControlIter->second->size() >= threshold_.maxCreateNumPerSecondPerApp) { + ANS_LOGE("SingleAppPublishFlowControl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_4) + .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("SingleAppPublishFlowControl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + } + return ERR_OK; +} + +void FlowControlService::PublishRecordTimestamp(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid) +{ + if (record->isThirdparty == true) { + std::lock_guard lock(flowControlMutex_); + flowControlPublishTimestampList_.push_back(now); + } else { + std::lock_guard lock(systemFlowControlMutex_); + systemFlowControlPublishTimestampList_.push_back(now); + } + + std::lock_guard lock(singleAppFlowControlMutex_); + auto singleAppFlowControlIter = singleAppFlowControlPublishTimestampMap_.find(callingUid); + if (singleAppFlowControlIter == singleAppFlowControlPublishTimestampMap_.end()) { + singleAppFlowControlPublishTimestampMap_[callingUid] = + std::make_shared>(); + singleAppFlowControlIter = singleAppFlowControlPublishTimestampMap_.find(callingUid); + } + singleAppFlowControlIter->second->push_back(now); +} + +void FlowControlService::PublishSingleAppFlowCtrlRemoveExpire(std::chrono::system_clock::time_point now) +{ + std::lock_guard lock(singleAppFlowControlMutex_); + for (auto iter = singleAppFlowControlPublishTimestampMap_.begin(); + iter != singleAppFlowControlPublishTimestampMap_.end();) { + auto latest = iter->second->back(); + if (std::chrono::abs(now - latest) > SINGLE_APP_FLOW_CONTRL_EXPIRE_TIME) { + iter = singleAppFlowControlPublishTimestampMap_.erase(iter); + } else { + ++iter; + } + } +} + +ErrCode FlowControlService::UpdateFlowCtrl(const std::shared_ptr &record, + const int32_t callingUid) +{ + if (record->isNeedFlowCtrl == false) { + return ERR_OK; + } + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + ErrCode result = ERR_OK; + result = UpdateSingleAppFlowCtrl(record, now, callingUid); + if (result != ERR_OK) { + return result; + } + result = UpdateGlobalFlowCtrl(record, now); + if (result != ERR_OK) { + return result; + } + UpdateRecordTimestamp(record, now, callingUid); + UpdateSingleAppFlowCtrlRemoveExpire(now); + return result; +} + +ErrCode FlowControlService::UpdateGlobalFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now) +{ + ANS_LOGD("UpdateGlobalFlowCtrl size %{public}zu,%{public}zu", + flowControlUpdateTimestampList_.size(), systemFlowControlUpdateTimestampList_.size()); + if (record->isThirdparty == true) { + // Third-part flow control + std::lock_guard lock(flowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(flowControlUpdateTimestampList_, now); + if (flowControlUpdateTimestampList_.size() >= threshold_.maxUpdateNumPerSecond) { + ANS_LOGE("Third-part UpdateGlobalFlowCtrl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_3) + .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("Third-part updateGlobalFlowCtrl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; + } + } else { + // System flow control + std::lock_guard lock(systemFlowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(systemFlowControlUpdateTimestampList_, now); + if (systemFlowControlUpdateTimestampList_.size() >= threshold_.maxUpdateNumPerSecond) { + ANS_LOGE("System UpdateGlobalFlowCtrl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_4) + .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("System updateGlobalFlowCtrl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; + } + } + return ERR_OK; +} + +ErrCode FlowControlService::UpdateSingleAppFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid) +{ + std::lock_guard lock(singleAppFlowControlMutex_); + auto singleAppFlowControlIter = singleAppFlowControlUpdateTimestampMap_.find(callingUid); + if (singleAppFlowControlIter == singleAppFlowControlUpdateTimestampMap_.end()) { + return ERR_OK; + } + NotificationAnalyticsUtil::RemoveExpired(*(singleAppFlowControlIter->second), now); + if (singleAppFlowControlIter->second->size() >= threshold_.maxUpdateNumPerSecondPerApp) { + ANS_LOGE("SingleAppUpdateFlowControl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_5) + .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("SingleAppUpdateFlowControl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; + } + return ERR_OK; +} + +void FlowControlService::UpdateRecordTimestamp(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid) +{ + if (record->isThirdparty == true) { + std::lock_guard lock(flowControlMutex_); + flowControlUpdateTimestampList_.push_back(now); + } else { + std::lock_guard lock(systemFlowControlMutex_); + systemFlowControlUpdateTimestampList_.push_back(now); + } + + std::lock_guard lock(singleAppFlowControlMutex_); + auto singleAppFlowControlIter = singleAppFlowControlUpdateTimestampMap_.find(callingUid); + if (singleAppFlowControlIter == singleAppFlowControlUpdateTimestampMap_.end()) { + singleAppFlowControlUpdateTimestampMap_[callingUid] = + std::make_shared>(); + singleAppFlowControlIter = singleAppFlowControlUpdateTimestampMap_.find(callingUid); + } + singleAppFlowControlIter->second->push_back(now); +} + +void FlowControlService::UpdateSingleAppFlowCtrlRemoveExpire(std::chrono::system_clock::time_point now) +{ + std::lock_guard lock(singleAppFlowControlMutex_); + for (auto iter = singleAppFlowControlUpdateTimestampMap_.begin(); + iter != singleAppFlowControlUpdateTimestampMap_.end();) { + auto latest = iter->second->back(); + if (std::chrono::abs(now - latest) > SINGLE_APP_FLOW_CONTRL_EXPIRE_TIME) { + iter = singleAppFlowControlUpdateTimestampMap_.erase(iter); + } else { + ++iter; + } + } +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/advanced_notification_inline.cpp b/services/ans/src/advanced_notification_inline.cpp index 2999bd0006d3ff6848dade2aa8fd50c5f2338108..9be433936f2e42def16925f2046c509589a736e6 100644 --- a/services/ans/src/advanced_notification_inline.cpp +++ b/services/ans/src/advanced_notification_inline.cpp @@ -84,40 +84,35 @@ inline tm GetLocalTime(time_t time) inline ErrCode CheckPictureSize(const sptr &request) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1); auto result = request->CheckImageSizeForContent(); if (result != ERR_OK) { ANS_LOGE("Check image size failed."); + message.ErrorCode(result).Message("Check image size failed."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } if (request->CheckImageOverSizeForPixelMap(request->GetLittleIcon(), MAX_ICON_SIZE)) { + message.ErrorCode(ERR_ANS_ICON_OVER_SIZE).Message("Check little image size failed."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_ICON_OVER_SIZE; } - if (request->CheckImageOverSizeForPixelMap(request->GetBigIcon(), MAX_ICON_SIZE)) { + if (request->CheckImageOverSizeForPixelMap(request->GetOverlayIcon(), MAX_ICON_SIZE)) { + message.ErrorCode(ERR_ANS_ICON_OVER_SIZE).Message("Check overlay size failed."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_ICON_OVER_SIZE; } - if (request->CheckImageOverSizeForPixelMap(request->GetOverlayIcon(), MAX_ICON_SIZE)) { - return ERR_ANS_ICON_OVER_SIZE; + if (request->CheckImageOverSizeForPixelMap(request->GetBigIcon(), MAX_ICON_SIZE)) { + request->ResetBigIcon(); + ANS_LOGI("Check big image size over limit"); } return ERR_OK; } -inline void RemoveExpired( - std::list &list, const std::chrono::system_clock::time_point &now) -{ - auto iter = list.begin(); - while (iter != list.end()) { - if (abs(now - *iter) > std::chrono::seconds(1)) { - iter = list.erase(iter); - } else { - break; - } - } -} - inline OHOS::Notification::HaMetaMessage AddInformationInMessage( OHOS::Notification::HaMetaMessage haMetaMessage, const int32_t reason, std::string message) diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index e5d7810c0b6fbe7e60bc835969246387f5775370..a992adeabfd61373ff3e3cbde1893ffe28f371ef 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -15,6 +15,7 @@ #include "advanced_notification_service.h" +#include "cpp/task.h" #include "errors.h" #include "ans_inner_errors.h" #include "notification_constant.h" @@ -32,70 +33,82 @@ #include "advanced_notification_inline.cpp" #include #include +#include "notification_analytics_util.h" +#include "aes_gcm_helper.h" namespace OHOS { namespace Notification { const std::string LOCK_SCREEN_PICTURE_TAG = "lock_screen_picture"; const std::string PROGRESS_VALUE = "progressValue"; -void AdvancedNotificationService::RecoverLiveViewFromDb() +constexpr int32_t BGTASK_UID = 3051; +constexpr int32_t TYPE_CODE_DOWNLOAD = 8; +void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) { - ANS_LOGI("Start recover live view from db."); - - std::vector requestsdb; - if (GetBatchNotificationRequestsFromDb(requestsdb) != ERR_OK) { - ANS_LOGE("Get liveView from db failed."); + if (notificationSvrQueue_ == nullptr) { + ANS_LOGE("notificationSvrQueue_ is nullptr."); return; } + ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() { + ANS_LOGI("Start recover live view from db. userId:%{public}d", userId); + std::vector requestsdb; + if (GetBatchNotificationRequestsFromDb(requestsdb, userId) != ERR_OK) { + ANS_LOGE("Get liveView from db failed."); + return; + } + ANS_LOGI("The number of live views to recover: %{public}zu.", requestsdb.size()); + std::vector keys; + for (const auto &requestObj : requestsdb) { + ANS_LOGD("Recover request: %{public}s.", requestObj.request->Dump().c_str()); + if (!IsLiveViewCanRecover(requestObj.request)) { + int32_t userId = requestObj.request->GetReceiverUserId(); + keys.emplace_back(requestObj.request->GetBaseKey("")); + if (DoubleDeleteNotificationFromDb(requestObj.request->GetKey(), + requestObj.request->GetSecureKey(), userId) != ERR_OK) { + ANS_LOGE("Delete notification failed."); + } + continue; + } - for (const auto &requestObj : requestsdb) { - ANS_LOGD("Recover request: %{public}s.", requestObj.request->Dump().c_str()); - if (!IsLiveViewCanRecover(requestObj.request)) { - int32_t userId = requestObj.request->GetReceiverUserId(); - if (DeleteNotificationRequestFromDb(requestObj.request->GetKey(), userId) != ERR_OK) { - ANS_LOGE("Delete notification failed."); + auto record = std::make_shared(); + record->isNeedFlowCtrl = false; + if (FillNotificationRecord(requestObj, record) != ERR_OK) { + ANS_LOGE("Fill notification record failed."); + continue; } - continue; - } - auto record = std::make_shared(); - if (FillNotificationRecord(requestObj, record) != ERR_OK) { - ANS_LOGE("Fill notification record failed."); - continue; - } + if (Filter(record, true) != ERR_OK) { + ANS_LOGE("Filter record failed."); + continue; + } - if (Filter(record, true) != ERR_OK) { - ANS_LOGE("Filter record failed."); - continue; - } + // Turn off ringtone and vibration during recovery process + auto notificationFlags = record->request->GetFlags(); + notificationFlags->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE); + notificationFlags->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE); + record->request->SetFlags(notificationFlags); + ANS_LOGI("SetFlags-Recovery, notificationKey = %{public}s flags = %{public}d", + record->request->GetKey().c_str(), notificationFlags->GetReminderFlags()); + if (AssignToNotificationList(record) != ERR_OK) { + ANS_LOGE("Add notification to record list failed."); + continue; + } + UpdateRecentNotification(record->notification, false, 0); - if (FlowControl(record) != ERR_OK) { - ANS_LOGE("Flow control failed."); - continue; + StartFinishTimer(record, requestObj.request->GetFinishDeadLine(), + NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE); + StartUpdateTimer(record, requestObj.request->GetUpdateDeadLine(), + NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE); } - // Turn off ringtone and vibration during recovery process - auto notificationFlags = record->request->GetFlags(); - notificationFlags->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE); - notificationFlags->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE); - record->request->SetFlags(notificationFlags); - if (AssignToNotificationList(record) != ERR_OK) { - ANS_LOGE("Add notification to record list failed."); - continue; + if (!keys.empty()) { + OnRecoverLiveView(keys); } - UpdateRecentNotification(record->notification, false, 0); - - StartFinishTimer(record, requestObj.request->GetFinishDeadLine(), - NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE); - StartUpdateTimer(record, requestObj.request->GetUpdateDeadLine(), - NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE); - } - - // publish notifications - for (const auto &subscriber : NotificationSubscriberManager::GetInstance()->GetSubscriberRecords()) { - OnSubscriberAdd(subscriber); - } - - ANS_LOGI("End recover live view from db."); + // publish notifications + for (const auto &subscriber : NotificationSubscriberManager::GetInstance()->GetSubscriberRecords()) { + OnSubscriberAdd(subscriber); + } + ANS_LOGI("End recover live view from db."); + })); } ErrCode AdvancedNotificationService::UpdateNotificationTimerInfo(const std::shared_ptr &record) @@ -144,7 +157,8 @@ void AdvancedNotificationService::ProcForDeleteLiveView(const std::shared_ptrrequest->GetReceiverUserId(); - if (DeleteNotificationRequestFromDb(record->request->GetKey(), userId) != ERR_OK) { + if (DoubleDeleteNotificationFromDb(record->request->GetKey(), + record->request->GetSecureKey(), userId) != ERR_OK) { ANS_LOGE("Live View cancel, delete notification failed."); } @@ -153,6 +167,14 @@ void AdvancedNotificationService::ProcForDeleteLiveView(const std::shared_ptr &record) +{ + ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([this, record]() { + OnSubscriberAdd(record); + })); +} + void AdvancedNotificationService::OnSubscriberAdd( const std::shared_ptr &record) { @@ -164,7 +186,8 @@ void AdvancedNotificationService::OnSubscriberAdd( sptr sortingMap = GenerateSortingMap(); std::vector> notifications; for (auto notificationRecord : notificationList_) { - if (notificationRecord->notification != nullptr && + if (notificationRecord != nullptr && + notificationRecord->notification != nullptr && notificationRecord->notification->GetNotificationRequest().IsCommonLiveView()) { notifications.emplace_back(notificationRecord->notification); } @@ -228,35 +251,46 @@ int32_t AdvancedNotificationService::SetNotificationRequestToDb(const Notificati ANS_LOGI("Not saving notification request to db for common live view with isOnlyLocalUpdate set to true."); return ERR_OK; } - + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_3). + BundleName(request->GetCreatorBundleName()).NotificationId(request->GetNotificationId()); nlohmann::json jsonObject; if (!NotificationJsonConverter::ConvertToJson(request, jsonObject)) { ANS_LOGE("Convert request to json object failed, bundle name %{public}s, id %{public}d.", request->GetCreatorBundleName().c_str(), request->GetNotificationId()); + NotificationAnalyticsUtil::ReportModifyEvent(message.Message("convert request failed")); return ERR_ANS_TASK_ERR; } auto bundleOption = requestDb.bundleOption; if (!NotificationJsonConverter::ConvertToJson(bundleOption, jsonObject)) { ANS_LOGE("Convert bundle to json object failed, bundle name %{public}s, id %{public}d.", bundleOption->GetBundleName().c_str(), request->GetNotificationId()); + NotificationAnalyticsUtil::ReportModifyEvent(message.Message("convert option failed")); return ERR_ANS_TASK_ERR; } + std::string encryptValue; + ErrCode errorCode = AesGcmHelper::Encrypt(jsonObject.dump(), encryptValue); + if (errorCode != ERR_OK) { + ANS_LOGE("SetNotificationRequestToDb encrypt error"); + return static_cast(errorCode); + } auto result = NotificationPreferences::GetInstance()->SetKvToDb( - request->GetKey(), jsonObject.dump(), request->GetReceiverUserId()); + request->GetSecureKey(), encryptValue, request->GetReceiverUserId()); if (result != ERR_OK) { - ANS_LOGE( - "Set notification request failed, bundle name %{public}s, id %{public}d, key %{public}s, ret %{public}d.", + ANS_LOGE("Set failed, bundle name %{public}s, id %{public}d, key %{public}s, ret %{public}d.", request->GetCreatorBundleName().c_str(), request->GetNotificationId(), request->GetKey().c_str(), result); + NotificationAnalyticsUtil::ReportModifyEvent(message.ErrorCode(result).Message("set failed")); return result; + } else { + DeleteNotificationRequestFromDb(request->GetKey(), request->GetReceiverUserId()); } result = SetLockScreenPictureToDb(request); if (result != ERR_OK) { ANS_LOGE("Failed to set lock screen picture to db"); - return result; + NotificationAnalyticsUtil::ReportModifyEvent(message.ErrorCode(result).Message("SetToDb failed")); } - return ERR_OK; + return result; } int32_t AdvancedNotificationService::GetNotificationRequestFromDb( @@ -290,11 +324,18 @@ int32_t AdvancedNotificationService::GetNotificationRequestFromDb( return ERR_OK; } -int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb(std::vector &requests) +int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb( + std::vector &requests, int32_t userId) { std::unordered_map dbRecords; std::vector userIds; - int32_t ret = OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(userIds); + int ret = ERR_OK; + if (userId == -1) { + ret = OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(userIds); + } else { + userIds.push_back(userId); + } + if (ret != ERR_OK) { ANS_LOGE("Get all os account failed."); return ret; @@ -302,13 +343,28 @@ int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb(std::vec for (const int32_t userId : userIds) { int32_t result = NotificationPreferences::GetInstance()->GetBatchKvsFromDb(REQUEST_STORAGE_KEY_PREFIX, dbRecords, userId); - if (result != ERR_OK) { + int32_t secureResult = + NotificationPreferences::GetInstance()->GetBatchKvsFromDb( + REQUEST_STORAGE_SECURE_KEY_PREFIX, dbRecords, userId); + if (result != ERR_OK && secureResult != ERR_OK) { ANS_LOGE("Get batch notification request failed."); return result; } } for (const auto &iter : dbRecords) { - auto jsonObject = nlohmann::json::parse(iter.second); + std::string decryptValue = iter.second; + if (iter.first.rfind(REQUEST_STORAGE_SECURE_KEY_PREFIX, 0) == 0) { + ErrCode errorCode = AesGcmHelper::Decrypt(decryptValue, iter.second); + if (errorCode != ERR_OK) { + ANS_LOGE("GetBatchNotificationRequestsFromDb decrypt error"); + return static_cast(errorCode); + } + } + if (decryptValue.empty() || !nlohmann::json::accept(decryptValue)) { + ANS_LOGE("Invalid json"); + continue; + } + auto jsonObject = nlohmann::json::parse(decryptValue); auto *request = NotificationJsonConverter::ConvertFromJson(jsonObject); if (request == nullptr) { ANS_LOGE("Parse json string to request failed."); @@ -317,7 +373,8 @@ int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb(std::vec auto *bundleOption = NotificationJsonConverter::ConvertFromJson(jsonObject); if (bundleOption == nullptr) { ANS_LOGE("Parse json string to bundle option failed."); - (void)DeleteNotificationRequestFromDb(request->GetKey(), request->GetReceiverUserId()); + (void)DoubleDeleteNotificationFromDb(request->GetKey(), + request->GetSecureKey(), request->GetReceiverUserId()); continue; } @@ -330,6 +387,19 @@ int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb(std::vec return ERR_OK; } + +int32_t AdvancedNotificationService::DoubleDeleteNotificationFromDb(const std::string &key, + const std::string &secureKey, const int32_t userId) +{ + auto result = NotificationPreferences::GetInstance()->DeleteKvFromDb(secureKey, userId); + if (result != ERR_OK) { + ANS_LOGE("Delete notification request failed, key %{public}s.", key.c_str()); + return result; + } + result = DeleteNotificationRequestFromDb(key, userId); + return result; +} + int32_t AdvancedNotificationService::DeleteNotificationRequestFromDb(const std::string &key, const int32_t userId) { auto result = NotificationPreferences::GetInstance()->DeleteKvFromDb(key, userId); @@ -377,6 +447,14 @@ ErrCode AdvancedNotificationService::IsAllowedRemoveSlot(const sptr &newRequest, const sptr &oldRequest) { + if (oldRequest->GetContent() == nullptr || + newRequest->GetContent() == nullptr) { + return; + } + if (oldRequest->GetContent()->GetNotificationContent() == nullptr || + newRequest->GetContent()->GetNotificationContent() == nullptr) { + return; + } if (newRequest->GetSlotType() != NotificationConstant::SlotType::LIVE_VIEW) { return; } @@ -499,8 +577,12 @@ uint64_t AdvancedNotificationService::StartDelayPublishTimer( { ANS_LOGD("Enter"); - auto timeoutFunc = [this, ownerUid, notificationId] { - StartPublishDelayedNotificationTimeOut(ownerUid, notificationId); + wptr wThis = this; + auto timeoutFunc = [wThis, ownerUid, notificationId] { + sptr sThis = wThis.promote(); + if (sThis != nullptr) { + sThis->StartPublishDelayedNotificationTimeOut(ownerUid, notificationId); + } }; std::shared_ptr notificationTimerInfo = std::make_shared(); notificationTimerInfo->SetCallbackInfo(timeoutFunc); @@ -545,14 +627,13 @@ ErrCode AdvancedNotificationService::StartPublishDelayedNotification(const std:: UpdateRecentNotification(record->notification, false, 0); NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, GenerateSortingMap()); if ((record->request->GetAutoDeletedTime() > GetCurrentTime())) { - StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + StartAutoDeletedTimer(record); } record->finish_status = UploadStatus::FIRST_UPDATE_TIME_OUT; StartFinishTimer(record, GetCurrentTime() + NotificationConstant::TEN_MINUTES, NotificationConstant::TRIGGER_TEN_MINUTES_REASON_DELETE); - + return ERR_OK; } @@ -612,15 +693,13 @@ void AdvancedNotificationService::UpdateRecordByOwner( if (oldRecord == nullptr) { oldRecord = GetFromNotificationList(creatorUid, notificationId); } - if (oldRecord == nullptr) { return; } - auto downloadTemplate = record->notification->GetNotificationRequest().GetTemplate(); auto content = record->notification->GetNotificationRequest().GetContent(); auto wantAgent = record->notification->GetNotificationRequest().GetWantAgent(); - record->request = oldRecord->request; + record->request = new (std::nothrow) NotificationRequest(*(oldRecord->request)); if (wantAgent != nullptr) { record->request->SetWantAgent(wantAgent); } @@ -632,24 +711,15 @@ void AdvancedNotificationService::UpdateRecordByOwner( auto data = downloadTemplate->GetTemplateData(); AAFwk::WantParamWrapper wrapper(*data); ANS_LOGD("Update the template data: %{public}s.", wrapper.ToString().c_str()); - CancelTimer(oldRecord->notification->GetFinishTimer()); - uint64_t process = 0; if (data->HasParam(PROGRESS_VALUE)) { process = data->GetIntParam(PROGRESS_VALUE, 0); } - - if (process == NotificationConstant::FINISH_PER) { - record->finish_status = UploadStatus::FINISH; - StartFinishTimer(record, GetCurrentTime() + NotificationConstant::THIRTY_MINUTES, - NotificationConstant::TRIGGER_FIFTEEN_MINUTES_REASON_DELETE); - } else { - record->finish_status = UploadStatus::CONTINUOUS_UPDATE_TIME_OUT; - StartFinishTimer(record, GetCurrentTime() + NotificationConstant::FIFTEEN_MINUTES, - NotificationConstant::TRIGGER_THIRTY_MINUTES_REASON_DELETE); - } + StartFinishTimerForUpdate(record, process); timerId = record->notification->GetFinishTimer(); + ANS_LOGI("TimerForUpdate,oldTimeId:%{public}d,newTimeId:%{public}d", + (int)(oldRecord->notification->GetFinishTimer()), (int)timerId); } record->notification = new (std::nothrow) Notification(record->request); if (record->notification == nullptr) { @@ -659,5 +729,46 @@ void AdvancedNotificationService::UpdateRecordByOwner( record->bundleOption = oldRecord->bundleOption; record->notification->SetFinishTimer(timerId); } + +void AdvancedNotificationService::StartFinishTimerForUpdate( + const std::shared_ptr &record, uint64_t process) +{ + if (process == NotificationConstant::FINISH_PER) { + record->finish_status = UploadStatus::FINISH; + StartFinishTimer(record, GetCurrentTime() + NotificationConstant::THIRTY_MINUTES, + NotificationConstant::TRIGGER_FIFTEEN_MINUTES_REASON_DELETE); + } else { + record->finish_status = UploadStatus::CONTINUOUS_UPDATE_TIME_OUT; + StartFinishTimer(record, GetCurrentTime() + NotificationConstant::FIFTEEN_MINUTES, + NotificationConstant::TRIGGER_THIRTY_MINUTES_REASON_DELETE); + } +} + +void AdvancedNotificationService::HandleUpdateLiveViewNotificationTimer(const int32_t uid, const bool isPaused) +{ + for (const auto &record : notificationList_) { + const auto &request = record->request; + if (!request || request->GetOwnerUid() != uid) { + continue; + } + if (!request->GetContent() || !request->GetContent()->GetNotificationContent()) { + continue; + } + + bool isContinuousLiveView = request->IsSystemLiveView() && request->GetCreatorUid() == BGTASK_UID; + const auto &liveViewContent = std::static_pointer_cast( + request->GetContent()->GetNotificationContent()); + if (isContinuousLiveView && liveViewContent->GetType() == TYPE_CODE_DOWNLOAD) { + if (isPaused) { + ANS_LOGI("liveview notification timer is being cancelled, uid: %{public}d", uid); + CancelTimer(record->notification->GetFinishTimer()); + } else { + ANS_LOGI("liveview notification timer is being reset, uid: %{public}d", uid); + StartFinishTimer(record, GetCurrentTime() + NotificationConstant::FIFTEEN_MINUTES, + NotificationConstant::TRIGGER_THIRTY_MINUTES_REASON_DELETE); + } + } + } +} } } diff --git a/services/ans/src/advanced_notification_publish/base_publish_process.cpp b/services/ans/src/advanced_notification_publish/base_publish_process.cpp index 90210c59c0c4ea3d5250eb172e238b00daefe8fd..4b28139f964cc71b5c7399e6ed60935ef2b4944b 100644 --- a/services/ans/src/advanced_notification_publish/base_publish_process.cpp +++ b/services/ans/src/advanced_notification_publish/base_publish_process.cpp @@ -43,11 +43,14 @@ ErrCode BasePublishProcess::CommonPublishCheck(const sptr & HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_1); if (request->GetReceiverUserId() != SUBSCRIBE_USER_INIT) { if (!AccessTokenHelper::IsSystemApp()) { + message.Message("Not SystemApp"); message.ErrorCode(ERR_ANS_NON_SYSTEM_APP); NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + message.BranchId(EventBranchId::BRANCH_3); + message.Message("CheckPermission denied"); message.ErrorCode(ERR_ANS_NON_SYSTEM_APP); NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_PERMISSION_DENIED; @@ -61,6 +64,9 @@ ErrCode BasePublishProcess::CommonPublishProcess(const sptr Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); if (AccessTokenHelper::IsDlpHap(callerToken)) { ANS_LOGE("DLP hap not allowed to send notifications"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_5) + .ErrorCode(ERR_ANS_DLP_HAP).Message("CommonPublishProcess failed"); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_DLP_HAP; } return ERR_OK; diff --git a/services/ans/src/advanced_notification_publish/live_publish_process.cpp b/services/ans/src/advanced_notification_publish/live_publish_process.cpp index 52eda9b3dd85b8d00965a9fa1bedb8c1a3d50156..b7f401650972f0206cff4fc9ff4b8994cdff6593 100644 --- a/services/ans/src/advanced_notification_publish/live_publish_process.cpp +++ b/services/ans/src/advanced_notification_publish/live_publish_process.cpp @@ -47,7 +47,12 @@ std::shared_ptr LivePublishProcess::GetInstance() ErrCode LivePublishProcess::PublishPreWork(const sptr &request, bool isUpdateByOwnerAllowed) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1); if (!CheckLocalLiveViewAllowed(request, isUpdateByOwnerAllowed)) { + message.BranchId(EventBranchId::BRANCH_3).ErrorCode(ERR_ANS_NON_SYSTEM_APP) + .Message("CheckLocalLiveViewAllowed is false", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + ANS_LOGE("CheckLocalLiveViewAllowed is false"); return ERR_ANS_NON_SYSTEM_APP; } @@ -61,6 +66,9 @@ ErrCode LivePublishProcess::PublishPreWork(const sptr &requ !AccessTokenHelper::IsSystemApp(); if (isUpdateByOwnerAllowed && isHap) { if (request->GetTemplate() == nullptr) { + message.BranchId(EventBranchId::BRANCH_4).ErrorCode(ERR_ANS_INVALID_PARAM) + .Message("Owner must has template to update", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); ANS_LOGE("Owner must has template to update."); return ERR_ANS_INVALID_PARAM; } diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 0b95ab3cee8b61419878f40d89993d3608953856..f8353b1b96cda8a73e7a54b740990dc0358c4b4a 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -37,21 +37,35 @@ #include "common_event_manager.h" #include "common_event_support.h" #include "common_event_publish_info.h" +#include "os_account_manager_helper.h" #include "want_params_wrapper.h" #include "ans_convert_enum.h" #include "notification_analytics_util.h" #include "advanced_notification_inline.cpp" #include "notification_analytics_util.h" +#include "advanced_datashare_helper.h" +#include "advanced_datashare_helper_ext.h" +#include "datashare_result_set.h" +#include "system_ability_definition.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "datashare_predicates.h" +#include "advanced_notification_flow_control_service.h" namespace OHOS { namespace Notification { constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres"; -constexpr int32_t HOURS_IN_ONE_DAY = 24; +constexpr uint32_t SECONDS_IN_ONE_DAY = 24 * 60 * 60; const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT"; constexpr int32_t RSS_PID = 3051; +constexpr int32_t ANS_UID = 5523; +constexpr int32_t BROKER_UID = 5557; constexpr int32_t TYPE_CODE_DOWNLOAD = 8; +constexpr const char *FOCUS_MODE_REPEAT_CALLERS_ENABLE = "1"; +constexpr const char *CONTACT_DATA = "datashare:///com.ohos.contactsdataability/contacts/contact_data?Proxy=true"; +constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4; ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled( const sptr &bundleOption, bool enabled) @@ -111,7 +125,15 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt if (isSubsystem) { return PublishNotificationBySa(request); } - + if (request->GetRemovalWantAgent() != nullptr && request->GetRemovalWantAgent()->GetPendingWant() != nullptr) { + uint32_t operationType = (uint32_t)(request->GetRemovalWantAgent()->GetPendingWant() + ->GetType(request->GetRemovalWantAgent()->GetPendingWant()->GetTarget())); + bool isSystemApp = AccessTokenHelper::IsSystemApp(); + if (!isSubsystem && !isSystemApp && operationType != OPERATION_TYPE_COMMON_EVENT) { + ANS_LOGI("SetRemovalWantAgent as nullptr"); + request->SetRemovalWantAgent(nullptr); + } + } do { result = publishProcess_[request->GetSlotType()]->PublishNotificationByApp(request); if (result != ERR_OK) { @@ -144,11 +166,98 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt } } while (0); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); SendPublishHiSysEvent(request, result); return result; } +ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const sptr &request) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!request) { + ANSR_LOGE("ReminderRequest object is nullptr"); + return ERR_ANS_INVALID_PARAM; + } + ErrCode result = PrePublishRequest(request); + if (result != ERR_OK) { + return result; + } + auto tokenCaller = IPCSkeleton::GetCallingTokenID(); + bool isAgentController = AccessTokenHelper::VerifyCallerPermission(tokenCaller, + OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER); + // SA not support sound + if (!request->GetSound().empty()) { + request->SetSound(""); + } + std::string bundle = request->GetCreatorBundleName(); + int32_t uid = request->GetCreatorUid(); + request->SetOwnerUid(uid); + request->SetOwnerBundleName(bundle); + std::shared_ptr record = std::make_shared(); + record->request = request; + record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); + record->bundleOption->SetInstanceKey(request->GetCreatorInstanceKey()); + sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); + if (record->bundleOption == nullptr || bundleOption == nullptr) { + ANS_LOGE("Failed to create bundleOption"); + return ERR_ANS_NO_MEMORY; + } + record->notification = new (std::nothrow) Notification(request); + if (record->notification == nullptr) { + ANS_LOGE("Failed to create notification"); + return ERR_ANS_NO_MEMORY; + } + + if (notificationSvrQueue_ == nullptr) { + ANS_LOGE("Serial queue is invalid."); + return ERR_ANS_INVALID_PARAM; + } + + SetRequestBySlotType(record->request, bundleOption); + + auto ipcUid = IPCSkeleton::GetCallingUid(); + ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() { + if (AssignValidNotificationSlot(record, bundleOption) != ERR_OK) { + ANS_LOGE("Can not assign valid slot!"); + } + + CheckDoNotDisturbProfile(record); + ChangeNotificationByControlFlags(record, isAgentController); + if (IsSaCreateSystemLiveViewAsBundle(record, ipcUid) && + (std::static_pointer_cast( + record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) { + result = SaPublishSystemLiveViewAsBundle(record); + if (result == ERR_OK) { + SendLiveViewUploadHiSysEvent(record, UploadStatus::CREATE); + } + return; + } + bool isNotificationExists = IsNotificationExists(record->notification->GetKey()); + result = FlowControlService::GetInstance()->FlowControl(record, ipcUid, isNotificationExists); + if (result != ERR_OK) { + return; + } + if (AssignToNotificationList(record) != ERR_OK) { + ANS_LOGE("Failed to assign notification list"); + return; + } + + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap); + }); + notificationSvrQueue_->wait(handler); + if (result != ERR_OK) { + return result; + } + + if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) { + StartAutoDelete(record, + record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + } + return ERR_OK; +} + bool AdvancedNotificationService::InitPublishProcess() { if (publishProcess_.size() > 0) { @@ -232,6 +341,7 @@ ErrCode AdvancedNotificationService::ExcuteCancelAll( std::vector keys = GetNotificationKeys(bundleOption); std::vector> notifications; + std::vector timerIds; for (auto key : keys) { #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED std::string deviceId; @@ -246,6 +356,7 @@ ErrCode AdvancedNotificationService::ExcuteCancelAll( if (notification != nullptr) { UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -262,6 +373,7 @@ ErrCode AdvancedNotificationService::ExcuteCancelAll( NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( notifications, nullptr, reason); } + BatchCancelTimer(timerIds); result = ERR_OK; })); notificationSvrQueue_->wait(handler); @@ -448,9 +560,6 @@ ErrCode AdvancedNotificationService::Delete(const std::string &key, int32_t remo if (notificationSvrQueue_ == nullptr) { std::string message = "Serial queue is invalidated. key:" + key + "."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 3) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } @@ -476,6 +585,7 @@ ErrCode AdvancedNotificationService::ExcuteDelete(const std::string &key, const if (notification != nullptr) { UpdateRecentNotification(notification, true, removeReason); + CancelTimer(notification->GetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); @@ -531,6 +641,7 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const sptrGetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); @@ -571,9 +682,6 @@ ErrCode AdvancedNotificationService::DeleteAll() if (notificationSvrQueue_ == nullptr) { std::string message = "Serial queue is invalidity."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 10) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } @@ -581,11 +689,12 @@ ErrCode AdvancedNotificationService::DeleteAll() ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); int32_t activeUserId = SUBSCRIBE_USER_INIT; - if (!GetActiveUserId(activeUserId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { return; } std::vector keys = GetNotificationKeys(nullptr); std::vector> notifications; + std::vector timerIds; for (auto key : keys) { #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED std::string deviceId; @@ -602,6 +711,7 @@ ErrCode AdvancedNotificationService::DeleteAll() if (notification->GetUserId() == activeUserId) { UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -615,7 +725,7 @@ ErrCode AdvancedNotificationService::DeleteAll() NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( notifications, nullptr, reason); } - + BatchCancelTimer(timerIds); result = ERR_OK; })); notificationSvrQueue_->wait(handler); @@ -626,18 +736,33 @@ ErrCode AdvancedNotificationService::DeleteAll() ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( const sptr &bundleOption, bool enabled) { + if (bundleOption == nullptr) { + ANS_LOGE("BundleOption is null."); + return ERR_ANS_INVALID_BUNDLE; + } + + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_3); + message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " enabled:" + std::to_string(enabled)); + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + ANS_LOGE("IsSystemApp is false."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { - ANS_LOGD("Check permission is false."); + ANS_LOGE("Permission Denied."); + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_PERMISSION_DENIED; } sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { + ANS_LOGE("Bundle is nullptr."); return ERR_ANS_INVALID_BUNDLE; } @@ -655,6 +780,10 @@ ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( } })); notificationSvrQueue_->wait(handler); + ANS_LOGI("%{public}s_%{public}d, enabled: %{public}s, Set show badge enabled for bundle result: %{public}d", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), std::to_string(enabled).c_str(), result); + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -702,7 +831,7 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle( result = NotificationPreferences::GetInstance()->IsShowBadge(bundle, enabled); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { result = ERR_OK; - enabled = false; + enabled = true; } })); notificationSvrQueue_->wait(handler); @@ -728,7 +857,7 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled) result = NotificationPreferences::GetInstance()->IsShowBadge(bundleOption, enabled); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { result = ERR_OK; - enabled = false; + enabled = true; } })); notificationSvrQueue_->wait(handler); @@ -748,43 +877,59 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string ErrCode result = ERR_OK; sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { - ANS_LOGD("bundleOption == nullptr"); + ANS_LOGE("bundleOption is nullptr."); return ERR_ANS_INVALID_BUNDLE; } // To get the permission bool allowedNotify = false; - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_1) - .BundleName(bundleOption->GetBundleName()); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_5); + message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " deviceId:" + deviceId); result = IsAllowedNotifySelf(bundleOption, allowedNotify); if (result != ERR_OK) { - message.Message("Allow notify self failed: " + std::to_string(result)); + ANS_LOGE("Not allowed notify self"); + message.ErrorCode(result).Append(" Allow failed"); NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } - ANS_LOGI("allowedNotify = %{public}d", allowedNotify); + ANS_LOGI("allowedNotify = %{public}d, bundle = %{public}s", allowedNotify, + bundleOption->GetBundleName().c_str()); if (allowedNotify) { + message.ErrorCode(ERR_OK).Append(" Allow success"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_OK; } // Check to see if it has been popover before bool hasPopped = false; result = GetHasPoppedDialog(bundleOption, hasPopped); if (result != ERR_OK) { - message.Message("Has popped dialog: " + std::to_string(result)); + ANS_LOGE("Get has popped dialog failed."); + message.ErrorCode(result).Append(" Get dialog failed."); NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } if (hasPopped) { + ANS_LOGE("Has popped is true."); + message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Has popped"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NOT_ALLOWED; } if (!CreateDialogManager()) { + ANS_LOGE("Create dialog manager failed."); + message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Create dialog failed"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } + result = dialogManager_->RequestEnableNotificationDailog(bundleOption, callback, callerToken); if (result == ERR_OK) { result = ERR_ANS_DIALOG_POP_SUCCEEDED; } - message.Message("Request dialog: " + std::to_string(result)); + + ANS_LOGI("%{public}s_%{public}d, deviceId: %{public}s, Request enable notification dailog result: %{public}d", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), deviceId.c_str(), result); + message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -809,7 +954,7 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const } int32_t userId = SUBSCRIBE_USER_INIT; - if (!GetActiveUserId(userId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) { return ERR_ANS_GET_ACTIVE_USER_FAILED; } @@ -836,19 +981,36 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s", __FUNCTION__); + if (bundleOption == nullptr) { + ANS_LOGE("BundleOption is null."); + return ERR_ANS_INVALID_BUNDLE; + } + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_4); + message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " enabled:" + std::to_string(enabled) + + " deviceId:" + deviceId); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - ANS_LOGD("IsSystemApp is bogus."); + ANS_LOGE("IsSystemApp is false."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NON_SYSTEM_APP; } - if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + int32_t callingUid = IPCSkeleton::GetCallingUid(); + if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + ANS_LOGE("Permission Denied."); + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_PERMISSION_DENIED; } sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { + message.ErrorCode(ERR_ANS_INVALID_BUNDLE).Append(" Bundle is nullptr."); + NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE(" Bundle is nullptr."); return ERR_ANS_INVALID_BUNDLE; } @@ -861,18 +1023,13 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( ErrCode result = ERR_OK; if (deviceId.empty()) { - bool notificationEnable = false; - ErrCode saveRef = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle( - bundle, notificationEnable); // Local device result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled); - if (!enabled) { - result = RemoveAllNotificationsForDisable(bundle); - } - if (saveRef != ERR_OK) { - SetSlotFlagsTrustlistsAsBundle(bundle); - } if (result == ERR_OK) { + if (!enabled) { + result = RemoveAllNotificationsForDisable(bundle); + } + SetSlotFlagsTrustlistsAsBundle(bundle); NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData); PublishSlotChangeCommonEvent(bundle); } @@ -880,6 +1037,11 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( // Remote device } + ANS_LOGI("%{public}s_%{public}d, deviceId: %{public}s, enable: %{public}s, " + "Set notifications enabled for special bundle result: %{public}d", bundleOption->GetBundleName().c_str(), + bundleOption->GetUid(), deviceId.c_str(), std::to_string(enabled).c_str(), result); + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportModifyEvent(message); SendEnableNotificationHiSysEvent(bundleOption, enabled, result); return result; } @@ -899,7 +1061,7 @@ ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed) } int32_t userId = SUBSCRIBE_USER_INIT; - if (!GetActiveUserId(userId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) { return ERR_ANS_GET_ACTIVE_USER_FAILED; } @@ -934,49 +1096,90 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( ANS_LOGD("%{public}s", __FUNCTION__); canPop = false; ErrCode result = ERR_OK; - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_2); sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { - ANS_LOGE("bundleOption == nullptr"); + ANS_LOGE("bundleOption is nullptr."); return ERR_ANS_INVALID_BUNDLE; } // To get the permission bool allowedNotify = false; - message.BundleName(bundleOption->GetBundleName()); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_2); + message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " canPop:" + std::to_string(canPop)); result = IsAllowedNotifySelf(bundleOption, allowedNotify); if (result != ERR_OK) { - message.Message("Allow notify self failed: " + std::to_string(result)); + ANS_LOGE("Not allowed Notify self."); + message.ErrorCode(result).Append(" Not Allow"); NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } - ANS_LOGI("allowedNotify = %{public}d, bundle = %{public}s", allowedNotify, - bundleOption->GetBundleName().c_str()); + ANS_LOGI("allowedNotify = %{public}d", allowedNotify); if (allowedNotify) { + message.ErrorCode(ERR_OK).Append(" Allow success"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_OK; } // Check to see if it has been popover before bool hasPopped = false; result = GetHasPoppedDialog(bundleOption, hasPopped); if (result != ERR_OK) { - message.Message("Has popped dialog: " + std::to_string(result)); + ANS_LOGE("Get has popped dialog failed. result: %{public}d", result); + message.ErrorCode(result).Append(" Has popped"); NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } if (hasPopped) { - return ERR_OK; + ANS_LOGE("Has popped is true."); + message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Haspopped true"); + NotificationAnalyticsUtil::ReportModifyEvent(message); + return ERR_ANS_NOT_ALLOWED; } if (!CreateDialogManager()) { + ANS_LOGE("Create dialog manager failed."); + message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Create dialog failed"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } result = dialogManager_->AddDialogInfo(bundleOption, callback); if (result != ERR_OK) { + ANS_LOGI("AddDialogInfo result: %{public}d", result); + message.ErrorCode(result).Append(" AddDialogInfo"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } canPop = true; bundleName = bundleOption->GetBundleName(); - ANS_LOGI("CanPopEnableNotificationDialog end"); + ANS_LOGI("%{public}s_%{public}d, canPop: %{public}s, CanPopEnableNotificationDialog result: %{public}d", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), std::to_string(canPop).c_str(), result); + message.ErrorCode(result).Append(" CanPopEnableNotificationDialog end"); + NotificationAnalyticsUtil::ReportModifyEvent(message); + return ERR_OK; +} + +ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog() +{ + ANS_LOGD("%{public}s", __FUNCTION__); + ErrCode result = ERR_OK; + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption == nullptr"); + return ERR_ANS_INVALID_BUNDLE; + } + return RemoveEnableNotificationDialog(bundleOption); +} + +ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog(const sptr &bundleOption) +{ + ANS_LOGI("RemoveEnableNotificationDialog %{public}s, %{public}d", + bundleOption->GetBundleName().c_str(), + bundleOption->GetUid()); + if (!CreateDialogManager()) { + return ERROR_INTERNAL_ERROR; + } + std::unique_ptr dialogInfoRemoved = nullptr; + dialogManager_->RemoveDialogInfoByBundleOption(bundleOption, dialogInfoRemoved); return ERR_OK; } @@ -989,7 +1192,7 @@ ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptrGetNotificationsEnabledForBundle(bundleOption, allowed); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + SetSlotFlagsTrustlistsAsBundle(bundleOption); result = ERR_OK; // FA model app can publish notification without user confirm allowed = CheckApiCompatibility(bundleOption); @@ -1018,7 +1222,7 @@ ErrCode AdvancedNotificationService::IsAllowedNotifyForBundle(const sptrGetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason); } })); @@ -1323,7 +1530,8 @@ ErrCode AdvancedNotificationService::RemoveNotification(const sptrGetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); @@ -1433,7 +1639,8 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptrnotification->IsRemoveAllowed() && isAllowedNotification) { + ANS_LOGI("BatchRemove-FILTER-RemoveNotAllowed-%{public}s", record->notification->GetKey().c_str()); continue; } if (record->slot != nullptr) { if (record->slot->GetForceControl() && record->slot->GetEnable()) { + ANS_LOGI("BatchRemove-FILTER-ForceControl-%{public}s", record->notification->GetKey().c_str()); continue; } } @@ -1482,18 +1688,29 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptrdeviceId.empty() #endif ) { + auto notificationRequest = record->request; + if (!BundleManagerHelper::GetInstance()->IsSystemApp(bundle->GetUid()) && + notificationRequest->IsSystemLiveView()) { + auto localLiveviewContent = std::static_pointer_cast( + notificationRequest->GetContent()->GetNotificationContent()); + if (localLiveviewContent->GetType() == 0) { + continue; + } + } ProcForDeleteLiveView(record); removeList.push_back(record); } } std::vector> notifications; + std::vector timerIds; for (auto record : removeList) { notificationList_.remove(record); if (record->notification != nullptr) { ANS_LOGD("record->notification is not nullptr."); UpdateRecentNotification(record->notification, true, reason); notifications.emplace_back(record->notification); + timerIds.emplace_back(record->notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(record->deviceId, record->bundleName, record->notification); #endif @@ -1508,6 +1725,7 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptrBatchNotifyCanceled(notifications, nullptr, reason); } + BatchCancelTimer(timerIds); })); notificationSvrQueue_->wait(handler); @@ -1535,6 +1753,7 @@ ErrCode AdvancedNotificationService::RemoveNotifications( } ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { std::vector> notifications; + std::vector timerIds; for (auto key : keys) { sptr notification = nullptr; #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -1549,6 +1768,7 @@ ErrCode AdvancedNotificationService::RemoveNotifications( if (notification != nullptr) { UpdateRecentNotification(notification, true, removeReason); notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -1564,6 +1784,7 @@ ErrCode AdvancedNotificationService::RemoveNotifications( if (!notifications.empty()) { NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, removeReason); } + BatchCancelTimer(timerIds); })); notificationSvrQueue_->wait(handler); @@ -1581,11 +1802,6 @@ ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -1600,7 +1816,7 @@ ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptrbundleOption->GetBundleName() == bundle->GetBundleName()) && ((*it)->bundleOption->GetUid() == bundle->GetUid()) && ((*it)->request->GetSlotType() == slot->GetType())) { - if (((*it)->request->IsAgentNotification() && (*it)->request->IsSystemLiveView())) { + if (((*it)->request->GetAgentBundle() != nullptr && (*it)->request->IsSystemLiveView())) { ANS_LOGI("Agent systemliveview no need remove."); it++; continue; @@ -1613,6 +1829,7 @@ ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptrGetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, NotificationConstant::DISABLE_SLOT_REASON_DELETE); } @@ -1626,6 +1843,73 @@ ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptr::GetInstance(); + if (datashareHelper == nullptr) { + ANS_LOGE("The data share helper is nullptr."); + return -1; + } + + int isNeedSilent = 0; + std::string policy; + Uri policyUri(datashareHelper->GetFocusModeCallPolicyUri(userId)); + bool ret = datashareHelper->Query(policyUri, KEY_FOCUS_MODE_CALL_MESSAGE_POLICY, policy); + if (!ret) { + ANS_LOGE("Query focus mode call message policy fail."); + return -1; + } + std::string repeat_call; + Uri repeatUri(datashareHelper->GetFocusModeRepeatCallUri(userId)); + bool repeat_ret = datashareHelper->Query(repeatUri, KEY_FOCUS_MODE_REPEAT_CALLERS_ENABLE, repeat_call); + if (!repeat_ret) { + ANS_LOGE("Query focus mode repeat callers enable fail."); + } + ANS_LOGI("IsNeedSilent: policy: %{public}s, repeat: %{public}s, callerType: %{public}d", + policy.c_str(), repeat_call.c_str(), callerType); + if (repeat_call == FOCUS_MODE_REPEAT_CALLERS_ENABLE && + callerType == 0 && atoi(policy.c_str()) != ContactPolicy::ALLOW_EVERYONE) { + if (datashareHelper->isRepeatCall(phoneNumber)) { + return 1; + } + } + switch (atoi(policy.c_str())) { + case ContactPolicy::FORBID_EVERYONE: + break; + case ContactPolicy::ALLOW_EVERYONE: + isNeedSilent = 1; + break; + case ContactPolicy::ALLOW_EXISTING_CONTACTS: + case ContactPolicy::ALLOW_FAVORITE_CONTACTS: + case ContactPolicy::ALLOW_SPECIFIED_CONTACTS: + Uri uri(CONTACT_DATA); + isNeedSilent = datashareHelper->QueryContact(uri, phoneNumber, policy); + break; + } + ANS_LOGI("IsNeedSilentInDoNotDisturbMode: %{public}d", isNeedSilent); + return isNeedSilent; +} + ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, int32_t instanceKey) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -1653,9 +1937,6 @@ ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, i if (notificationSvrQueue_ == nullptr) { std::string message = "Serial queue is invalid."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 3) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } @@ -1683,11 +1964,13 @@ void AdvancedNotificationService::ExcuteCancelGroupCancel( } std::vector> notifications; + std::vector timerIds; for (auto record : removeList) { notificationList_.remove(record); if (record->notification != nullptr) { UpdateRecentNotification(record->notification, true, reason); notifications.emplace_back(record->notification); + timerIds.emplace_back(record->notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(record->deviceId, record->bundleName, record->notification); #endif @@ -1704,6 +1987,7 @@ void AdvancedNotificationService::ExcuteCancelGroupCancel( NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( notifications, nullptr, reason); } + BatchCancelTimer(timerIds); })); notificationSvrQueue_->wait(handler); } @@ -1753,9 +2037,6 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( if (notificationSvrQueue_ == nullptr) { std::string message = "Serial queue is invalid."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 5) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } @@ -1779,6 +2060,7 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( } std::vector> notifications; + std::vector timerIds; for (auto record : removeList) { notificationList_.remove(record); ProcForDeleteLiveView(record); @@ -1786,6 +2068,7 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( if (record->notification != nullptr) { UpdateRecentNotification(record->notification, true, reason); notifications.emplace_back(record->notification); + timerIds.emplace_back(record->notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(record->deviceId, record->bundleName, record->notification); #endif @@ -1798,6 +2081,7 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( if (!notifications.empty()) { NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason); } + BatchCancelTimer(timerIds); })); notificationSvrQueue_->wait(handler); @@ -1809,6 +2093,7 @@ ErrCode AdvancedNotificationService::RemoveNotificationFromRecordList( { ErrCode result = ERR_OK; std::vector> notifications; + std::vector timerIds; for (auto& record : recordList) { std::string key = record->notification->GetKey(); sptr notification = nullptr; @@ -1826,6 +2111,7 @@ ErrCode AdvancedNotificationService::RemoveNotificationFromRecordList( int32_t reason = NotificationConstant::USER_STOPPED_REASON_DELETE; UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -1841,6 +2127,7 @@ ErrCode AdvancedNotificationService::RemoveNotificationFromRecordList( NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( notifications, nullptr, NotificationConstant::USER_STOPPED_REASON_DELETE); } + BatchCancelTimer(timerIds); return result; } @@ -1915,6 +2202,10 @@ ErrCode AdvancedNotificationService::SetEnabledForBundleSlot(const sptrGetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + + " slotType: " + std::to_string(static_cast(slotType)) + + " enabled: " +std::to_string(enabled) + "isForceControl" + std::to_string(isForceControl)); result = ERR_OK; ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { sptr slot; @@ -1974,6 +2265,10 @@ ErrCode AdvancedNotificationService::SetEnabledForBundleSlot(const sptrwait(handler); + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGI("%{public}s_%{public}d, SetEnabledForBundleSlot successful.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); SendEnableNotificationSlotHiSysEvent(bundleOption, slotType, enabled, result); return result; } @@ -2053,6 +2348,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrGetCreatorUid(); if (request->GetOwnerUid() != DEFAULT_UID) { @@ -2089,6 +2385,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr record = std::make_shared(); record->request = request; + record->isThirdparty = false; if (request->IsAgentNotification()) { record->bundleOption = new (std::nothrow) NotificationBundleOption("", request->GetCreatorUid()); } else { @@ -2111,16 +2408,12 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrrequest, bundleOption); #ifdef ENABLE_ANS_EXT_WRAPPER EXTENTION_WRAPPER->GetUnifiedGroupInfo(request); #endif - auto ipcUid = IPCSkeleton::GetCallingUid(); + const int32_t ipcUid = IPCSkeleton::GetCallingUid(); ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() { if (!bundleOption->GetBundleName().empty()) { ErrCode ret = AssignValidNotificationSlot(record, bundleOption); @@ -2129,7 +2422,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr( record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) { @@ -2139,7 +2432,11 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrnotification->GetKey()); + result = FlowControlService::GetInstance()->FlowControl(record, ipcUid, isNotificationExists); + if (result != ERR_OK) { + return; + } if (AssignToNotificationList(record) != ERR_OK) { ANS_LOGE("Failed to assign notification list"); return; @@ -2155,8 +2452,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrrequest->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) { - StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + StartAutoDeletedTimer(record); } return ERR_OK; } @@ -2182,35 +2478,36 @@ ErrCode AdvancedNotificationService::SetBadgeNumber(int32_t badgeNumber, int32_t NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData); }); notificationSvrQueue_->wait(handler); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_1) - .Message("Set badge number " + bundleName + " " + std::to_string(badgeNumber) - + " " + std::to_string(instanceKey)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_OK; } ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( const sptr &bundleOption, int32_t badgeNumber) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_1); + if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { + return ERR_ANS_INVALID_PARAM; + } + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_6); + message.Message(bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + + " badgeNumber: " + std::to_string(badgeNumber)); if (notificationSvrQueue_ == nullptr) { - message.Message("Serial queue is invalid.", true); - NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_INVALID_PARAM; } bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - message.Message("Client is not a system app or subsystem.", true); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not system app."); NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Not system app."); return ERR_ANS_NON_SYSTEM_APP; } sptr bundle = bundleOption; ErrCode result = CheckBundleOptionValid(bundle); if (result != ERR_OK) { - message.Message("Input bundle option is not correct: " + std::to_string(result), true); + message.ErrorCode(result).Append(" Bundle is invalid."); NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Bundle is invalid."); return result; } @@ -2223,8 +2520,9 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( bool isAgent = false; isAgent = IsAgentRelationship(bundleName, bundle->GetBundleName()); if (!isAgent) { - message.Message("the caller has no agent relationship with the specified bundle.", true); + message.ErrorCode(ERR_ANS_NO_AGENT_SETTING).Append(" No agent setting."); NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("No agent setting."); return ERR_ANS_NO_AGENT_SETTING; } } @@ -2240,9 +2538,6 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData); }); notificationSvrQueue_->wait(handler); - message.Message("Set badgenumber: " + bundle->GetBundleName() + ":" + - std::to_string(badgeNumber) + " " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -2290,14 +2585,27 @@ ErrCode AdvancedNotificationService::SetDistributedEnabledByBundle(const sptrGetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " enabled:" + std::to_string(enabled) + + " deviceType:" + deviceType); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - ANS_LOGD("IsSystemApp is bogus."); + ANS_LOGE("IsSystemApp is false."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append("Not SystemApp"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + ANS_LOGE("Permission Denied."); + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append("No permission"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_PERMISSION_DENIED; } @@ -2306,8 +2614,16 @@ ErrCode AdvancedNotificationService::SetDistributedEnabledByBundle(const sptrSetDistributedEnabledByBundle(bundle, + deviceType, enabled); + + ANS_LOGI("%{public}s_%{public}d, deviceType: %{public}s, enabled: %{public}s, " + "SetDistributedEnabledByBundle result: %{public}d", bundleOption->GetBundleName().c_str(), + bundleOption->GetUid(), deviceType.c_str(), std::to_string(enabled).c_str(), result); + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportModifyEvent(message); - return NotificationPreferences::GetInstance()->SetDistributedEnabledByBundle(bundle, deviceType, enabled); + return result; } ErrCode AdvancedNotificationService::IsDistributedEnabledByBundle(const sptr &bundleOption, @@ -2348,16 +2664,36 @@ ErrCode AdvancedNotificationService::DuplicateMsgControl(const sptr &bundleOption) +{ + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption is nullptr"); + return; + } + const char *keySpliter = "_"; + std::stringstream stream; + stream << bundleOption->GetUid() << keySpliter << bundleOption->GetBundleName() << keySpliter; + std::string uniqueKeyHead = stream.str(); + auto iter = uniqueKeyList_.begin(); + for (auto iter = uniqueKeyList_.begin(); iter != uniqueKeyList_.end();) { + if ((*iter).second.find(uniqueKeyHead) == 0) { + iter = uniqueKeyList_.erase(iter); + } else { + ++iter; + } + } +} + void AdvancedNotificationService::RemoveExpiredUniqueKey() { - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); auto iter = uniqueKeyList_.begin(); while (iter != uniqueKeyList_.end()) { - if (abs(now - (*iter).first) > std::chrono::hours(HOURS_IN_ONE_DAY)) { + if (std::chrono::duration_cast(now - (*iter).first).count() > SECONDS_IN_ONE_DAY) { iter = uniqueKeyList_.erase(iter); } else { break; @@ -2426,16 +2762,28 @@ ErrCode AdvancedNotificationService::PublishRemoveDuplicateEvent(const std::shar ErrCode AdvancedNotificationService::SetSmartReminderEnabled(const std::string &deviceType, const bool enabled) { ANS_LOGD("%{public}s", __FUNCTION__); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_6); + message.Message(" enabled:" + std::to_string(enabled) + " deviceType:" + deviceType); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - ANS_LOGD("IsSystemApp is bogus."); + ANS_LOGE("IsSystemApp is false."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + ANS_LOGE("Permission Denied."); + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_PERMISSION_DENIED; } ErrCode result = NotificationPreferences::GetInstance()->SetSmartReminderEnabled(deviceType, enabled); + + ANS_LOGI("enabled: %{public}s, deviceType: %{public}s,Set smart reminder enabled: %{public}d", + std::to_string(enabled).c_str(), deviceType.c_str(), result); + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } diff --git a/services/ans/src/advanced_notification_reminder_service.cpp b/services/ans/src/advanced_notification_reminder_service.cpp index 96bb1905ea22914666a3fe6a006e6092bc46b341..d73740f7581ead558fff9b8628ed15308d27b26c 100644 --- a/services/ans/src/advanced_notification_reminder_service.cpp +++ b/services/ans/src/advanced_notification_reminder_service.cpp @@ -59,11 +59,14 @@ ErrCode AdvancedNotificationService::PublishReminder(sptr &remi } std::string bundle = GetClientBundleName(); - if (!CheckReminderPermission() || !AllowUseReminder(bundle)) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER" - "or not allowed use reminder"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); return ERR_REMINDER_PERMISSION_DENIED; } + if (!AllowUseReminder(bundle)) { + ANSR_LOGW("The number of reminders exceeds the limit[0]."); + return ERR_REMINDER_NUMBER_OVERLOAD; + } ANSR_LOGD("is system app: %{public}d", AccessTokenHelper::IsSystemApp()); reminder->SetSystemApp(AccessTokenHelper::IsSystemApp()); sptr notificationRequest = reminder->GetNotificationRequest(); @@ -113,9 +116,8 @@ ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId) HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); ANSR_LOGI("Cancel Reminder"); std::string bundleName = GetClientBundleName(); - if (!CheckReminderPermission() || !AllowUseReminder(bundleName)) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER" - "or not allowed use reminder"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); return ERR_REMINDER_PERMISSION_DENIED; } @@ -135,9 +137,8 @@ ErrCode AdvancedNotificationService::CancelAllReminders() HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); ANSR_LOGI("Cancel all reminders"); std::string bundleName = GetClientBundleName(); - if (!CheckReminderPermission() || !AllowUseReminder(bundleName)) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER" - "or not allowed use reminder"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); return ERR_REMINDER_PERMISSION_DENIED; } @@ -160,9 +161,8 @@ ErrCode AdvancedNotificationService::GetValidReminders(std::vector #include -#include "fa_ability_context.h" +#include "ability_context.h" #include "ability_info.h" #include "access_token_helper.h" #include "accesstoken_kit.h" @@ -30,7 +30,6 @@ #include "ans_log_wrapper.h" #include "ans_watchdog.h" #include "ans_permission_def.h" -#include "bundle_manager_helper.h" #include "errors.h" #include "notification_extension_wrapper.h" #include "notification_record.h" @@ -75,6 +74,7 @@ #include "advanced_notification_inline.cpp" #include "advanced_datashare_helper_ext.h" #include "notification_analytics_util.h" +#include "advanced_notification_flow_control_service.h" namespace OHOS { namespace Notification { @@ -87,11 +87,11 @@ constexpr int32_t WINDOW_DEFAULT_WIDTH = 720; constexpr int32_t WINDOW_DEFAULT_HEIGHT = 1280; constexpr int32_t UI_HALF = 2; constexpr int32_t MAX_LIVEVIEW_HINT_COUNT = 1; -constexpr int32_t MAX_SOUND_ITEM_LENGTH = 2048; constexpr int32_t BUNDLE_OPTION_UID_DEFAULT_VALUE = 0; +constexpr int32_t MAX_SOUND_ITEM_LENGTH = 2048; +constexpr int32_t RSS_UID = 3051; +constexpr int32_t RESSCHED_UID = 1096; -const std::string MMS_BUNDLE_NAME = "com.ohos.mms"; -const std::string CONTACTS_BUNDLE_NAME = "com.ohos.contacts"; const std::string DO_NOT_DISTURB_MODE = "1"; constexpr const char *KEY_UNIFIED_GROUP_ENABLE = "unified_group_enable"; } // namespace @@ -99,7 +99,7 @@ constexpr const char *KEY_UNIFIED_GROUP_ENABLE = "unified_group_enable"; sptr AdvancedNotificationService::instance_; std::mutex AdvancedNotificationService::instanceMutex_; std::mutex AdvancedNotificationService::pushMutex_; -std::mutex AdvancedNotificationService::flowControlMutex_; +std::mutex AdvancedNotificationService::doNotDisturbMutex_; std::map slotFlagsDefaultMap_; std::map> AdvancedNotificationService::pushCallBacks_; @@ -145,7 +145,7 @@ ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptrGetOwnerUid() == DEFAULT_UID) { - GetActiveUserId(userId); + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId); uid = bundleManager->GetDefaultUidByBundleName(request->GetOwnerBundleName(), userId); } else { uid = request->GetOwnerUid(); @@ -182,8 +182,11 @@ ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptrGetBundleOption()->GetUid() == DEFAULT_UID) { - int32_t userId = 0; - GetActiveUserId(userId); + int32_t userId = SUBSCRIBE_USER_INIT; + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId); + if (request->GetOwnerUserId() != SUBSCRIBE_USER_INIT) { + userId = request->GetOwnerUserId(); + } std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { uid = bundleManager->GetDefaultUidByBundleName(sourceBundleName, userId); @@ -203,9 +206,15 @@ ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptrSetAgentBundle(agentBundle); - bundle = sourceBundleName; + } else if (request->GetOwnerUserId() != SUBSCRIBE_USER_INIT) { + int32_t uid = BundleManagerHelper::GetInstance()-> + GetDefaultUidByBundleName(bundle, request->GetOwnerUserId()); + if (uid < 0) { + return ERR_ANS_INVALID_UID; + } + request->SetOwnerUid(uid); } - request->SetOwnerBundleName(bundle); + request->SetOwnerBundleName(sourceBundleName); } int32_t uid = IPCSkeleton::GetCallingUid(); @@ -220,6 +229,9 @@ ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptrSetCreatorUserId(userId); request->SetCreatorBundleName(bundle); + if (request->GetOwnerBundleName().empty()) { + request->SetOwnerBundleName(bundle); + } if (request->GetOwnerUserId() == SUBSCRIBE_USER_INIT) { int32_t ownerUserId = SUBSCRIBE_USER_INIT; OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(request->GetOwnerUid(), ownerUserId); @@ -298,11 +310,10 @@ AdvancedNotificationService::AdvancedNotificationService() StartFilters(); std::function &)> callback = - std::bind(&AdvancedNotificationService::OnSubscriberAdd, this, std::placeholders::_1); + std::bind(&AdvancedNotificationService::OnSubscriberAddInffrt, this, std::placeholders::_1); NotificationSubscriberManager::GetInstance()->RegisterOnSubscriberAddCallback(callback); - std::function recoverFunc = std::bind(&AdvancedNotificationService::RecoverLiveViewFromDb, this); - notificationSvrQueue_->submit(recoverFunc); + RecoverLiveViewFromDb(); ISystemEvent iSystemEvent = { std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1), @@ -354,7 +365,7 @@ ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ ErrCode result = ERR_OK; if (!IsNotificationExists(record->notification->GetKey())) { record->request->SetCreateTime(GetCurrentTime()); - result = PublishFlowControl(record); + result = PublishInNotificationList(record); } else { if (record->request->IsAlertOneTime()) { CloseAlert(record); @@ -379,9 +390,6 @@ ErrCode AdvancedNotificationService::CancelPreparedNotification(int32_t notifica if (notificationSvrQueue_ == nullptr) { std::string message = "notificationSvrQueue is null"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 3) - .ErrorCode(ERR_ANS_INVALID_PARAM).NotificationId(notificationId); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } @@ -396,6 +404,7 @@ ErrCode AdvancedNotificationService::CancelPreparedNotification(int32_t notifica if (notification != nullptr) { UpdateRecentNotification(notification, true, reason); + CancelTimer(notification->GetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete("", "", notification); @@ -411,7 +420,6 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( const sptr &request, sptr &bundleOption) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_3); if (request == nullptr) { ANS_LOGE("request is invalid."); return ERR_ANS_INVALID_PARAM; @@ -423,33 +431,28 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( } ErrCode result = PrepareNotificationRequest(request); if (result != ERR_OK) { - message.ErrorCode(result); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } - + std::string sourceBundleName = + request->GetBundleOption() == nullptr ? "" : request->GetBundleOption()->GetBundleName(); if (request->IsAgentNotification()) { bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(), request->GetOwnerUid()); } else { - std::string sourceBundleName = - request->GetBundleOption() == nullptr ? "" : request->GetBundleOption()->GetBundleName(); - if (!sourceBundleName.empty() && - NotificationPreferences::GetInstance()->IsAgentRelationship(GetClientBundleName(), sourceBundleName)) { - ANS_LOGD("There is agent relationship between %{public}s and %{public}s", - GetClientBundleName().c_str(), sourceBundleName.c_str()); - request->SetCreatorBundleName(request->GetOwnerBundleName()); + if ((!sourceBundleName.empty() && + NotificationPreferences::GetInstance()->IsAgentRelationship(GetClientBundleName(), sourceBundleName) && + !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER))) { request->SetCreatorUid(request->GetOwnerUid()); + request->SetCreatorBundleName(request->GetOwnerBundleName()); bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(), request->GetOwnerUid()); } else { - bundleOption = GenerateBundleOption(); + bundleOption = new (std::nothrow) NotificationBundleOption(request->GetCreatorBundleName(), + request->GetCreatorUid()); } } if (bundleOption == nullptr) { - message.ErrorCode(ERR_ANS_INVALID_BUNDLE); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_INVALID_BUNDLE; } ANS_LOGI( @@ -560,6 +563,19 @@ void AdvancedNotificationService::CancelArchiveTimer(const std::shared_ptrnotification->SetArchiveTimer(NotificationConstant::INVALID_TIMER_ID); } +ErrCode AdvancedNotificationService::StartAutoDeletedTimer(const std::shared_ptr &record) +{ + uint64_t timerId = StartAutoDelete(record, + record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + if (timerId == NotificationConstant::INVALID_TIMER_ID) { + std::string message = "Start autoDeleted auto delete timer failed."; + ANS_LOGE("%{public}s", message.c_str()); + return ERR_ANS_TASK_ERR; + } + record->notification->SetAutoDeletedTimer(timerId); + return ERR_OK; +} + ErrCode AdvancedNotificationService::FillNotificationRecord( const NotificationRequestDb &requestdbObj, std::shared_ptr record) { @@ -609,6 +625,9 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrLocalControl(request); @@ -618,8 +637,16 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrisThirdparty = isThirdparty; ErrCode result = CheckPublishPreparedNotification(record, isSystemApp); if (result != ERR_OK) { message.ErrorCode(result); @@ -627,15 +654,10 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrGetUnifiedGroupInfo(request); #endif - int32_t uid = IPCSkeleton::GetCallingUid(); + const int32_t uid = IPCSkeleton::GetCallingUid(); ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); if (record->request->GetSlotType() == NotificationConstant::SlotType::LIVE_VIEW && @@ -648,8 +670,12 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrnotification->GetKey()); + result = FlowControlService::GetInstance()->FlowControl(record, uid, isNotificationExists); + if (result != ERR_OK) { + return; + } + result = AddRecordToMemory(record, isSystemApp, isUpdateByOwner, isAgentController); if (result != ERR_OK) { return; } @@ -676,8 +702,7 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrwait(handler); // live view handled in UpdateNotificationTimerInfo, ignore here. if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) { - StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + StartAutoDeletedTimer(record); } return result; } @@ -708,6 +733,29 @@ void AdvancedNotificationService::QueryDoNotDisturbProfile(const int32_t &userId } } +void AdvancedNotificationService::ReportDoNotDisturbModeChanged(const int32_t &userId, std::string &enable) +{ + std::lock_guard lock(doNotDisturbMutex_); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_2); + std::string info = "Do not disturb mode changed, userId: " + std::to_string(userId) + ", enable: " + enable; + auto it = doNotDisturbEnableRecord_.find(userId); + if (it != doNotDisturbEnableRecord_.end()) { + if (it->second != enable) { + ANS_LOGI("%{public}s", info.c_str()); + message.Message(info); + NotificationAnalyticsUtil::ReportModifyEvent(message); + doNotDisturbEnableRecord_.insert_or_assign(userId, enable); + } + } else { + if (enable == DO_NOT_DISTURB_MODE) { + ANS_LOGI("%{public}s", info.c_str()); + message.Message(info); + NotificationAnalyticsUtil::ReportModifyEvent(message); + } + doNotDisturbEnableRecord_.insert_or_assign(userId, enable); + } +} + void AdvancedNotificationService::CheckDoNotDisturbProfile(const std::shared_ptr &record) { ANS_LOGD("Called."); @@ -719,16 +767,14 @@ void AdvancedNotificationService::CheckDoNotDisturbProfile(const std::shared_ptr std::string enable; std::string profileId; QueryDoNotDisturbProfile(userId, enable, profileId); + ReportDoNotDisturbModeChanged(userId, enable); if (enable != DO_NOT_DISTURB_MODE) { ANS_LOGD("Currently not is do not disturb mode."); return; } std::string bundleName = record->bundleOption->GetBundleName(); - ANS_LOGD("The bundle name is %{public}s", bundleName.c_str()); - if (bundleName == MMS_BUNDLE_NAME || bundleName == CONTACTS_BUNDLE_NAME) { - ANS_LOGI("Currently in do not disturb mode, the bundle name is mms or contacts, keep reminder method."); - return; - } + ANS_LOGI("The disturbMode is on, userId:%{public}d, bundle:%{public}s, profileId:%{public}s", + userId, bundleName.c_str(), profileId.c_str()); sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); if (NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(atoi(profileId.c_str()), userId, profile) != ERR_OK) { @@ -766,7 +812,6 @@ void AdvancedNotificationService::DoNotDisturbUpdataReminderFlags(const std::sha } flags->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE); record->notification->SetEnableSound(false); - flags->SetLockScreenVisblenessEnabled(false); record->request->SetVisibleness(NotificationConstant::VisiblenessType::SECRET); flags->SetBannerEnabled(false); flags->SetLightScreenEnabled(false); @@ -831,11 +876,16 @@ bool AdvancedNotificationService::IsNotificationExists(const std::string &key) ErrCode AdvancedNotificationService::Filter(const std::shared_ptr &record, bool isRecover) { ErrCode result = ERR_OK; - if (!isRecover) { auto oldRecord = GetFromNotificationList(record->notification->GetKey()); result = record->request->CheckNotificationRequest((oldRecord == nullptr) ? nullptr : oldRecord->request); if (result != ERR_OK) { + bool liveView = record->request->IsCommonLiveView(); + int32_t slotType = liveView ? NotificationConstant::SlotType::LIVE_VIEW : + NotificationConstant::SlotType::ILLEGAL_TYPE; + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_5) + .ErrorCode(result).SlotType(slotType).Message("CheckNotificationRequest failed: "); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); ANS_LOGE("Notification(key %{public}s) isn't ready on publish failed with %{public}d.", record->notification->GetKey().c_str(), result); return result; @@ -862,7 +912,8 @@ ErrCode AdvancedNotificationService::Filter(const std::shared_ptr &record) +void AdvancedNotificationService::ChangeNotificationByControlFlags(const std::shared_ptr &record, + const bool isAgentController) { ANS_LOGD("Called."); if (record == nullptr || record->request == nullptr || record->notification == nullptr) { @@ -875,6 +926,10 @@ void AdvancedNotificationService::ChangeNotificationByControlFlags(const std::sh return; } + if (!isAgentController) { + record->request->SetNotificationControlFlags(notificationControlFlags & 0xFFFF); + } + auto flags = record->request->GetFlags(); if (flags == nullptr) { ANS_LOGE("The flags is nullptr."); @@ -943,13 +998,6 @@ void AdvancedNotificationService::AddToNotificationList(const std::shared_ptr &record) { - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - RemoveExpired(flowControlUpdateTimestampList_, now); - if (flowControlUpdateTimestampList_.size() >= MAX_UPDATE_NUM_PERSECOND) { - return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; - } - - flowControlUpdateTimestampList_.push_back(now); auto iter = notificationList_.begin(); while (iter != notificationList_.end()) { if ((*iter)->notification->GetKey() == record->notification->GetKey()) { @@ -1159,6 +1207,7 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptrnotification->IsRemoveAllowed()) { + ANS_LOGI("BatchRemove-FILTER-RemoveNotAllowed-%{public}s", record->notification->GetKey().c_str()); std::string message = "notification unremove."; OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 4) .ErrorCode(ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED); @@ -1194,9 +1243,6 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptr &n static bool SortNotificationsByLevelAndTime( const std::shared_ptr &first, const std::shared_ptr &second) { - if (first->slot->GetLevel() != second->slot->GetLevel()) { - return (first->slot->GetLevel() < second->slot->GetLevel()); + if (first->slot ==nullptr || second->slot == nullptr) { + return (first->request->GetCreateTime() < second->request->GetCreateTime()); } - return (first->request->GetCreateTime() < second->request->GetCreateTime()); + return (first->slot->GetLevel() < second->slot->GetLevel()); } -ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr &record) +bool AdvancedNotificationService::IsSystemUser(int32_t userId) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_2); - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - std::lock_guard lock(flowControlMutex_); - RemoveExpired(flowControlTimestampList_, now); - if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND + MAX_UPDATE_NUM_PERSECOND) { - message.ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); - return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; - } - flowControlTimestampList_.push_back(now); - - return ERR_OK; + return ((userId >= SUBSCRIBE_USER_SYSTEM_BEGIN) && (userId <= SUBSCRIBE_USER_SYSTEM_END)); } -ErrCode AdvancedNotificationService::PublishFlowControl(const std::shared_ptr &record) +ErrCode AdvancedNotificationService::PublishInNotificationList(const std::shared_ptr &record) { - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - RemoveExpired(flowControlPublishTimestampList_, now); - if (flowControlPublishTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND) { - return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; - } - - flowControlPublishTimestampList_.push_back(now); - std::list> bundleList; for (auto item : notificationList_) { if (record->notification->GetBundleName() == item->notification->GetBundleName()) { @@ -1871,8 +1896,10 @@ ErrCode AdvancedNotificationService::RegisterPushCallback( return ERROR_INTERNAL_ERROR; } } - - pushCallBacks_.insert_or_assign(slotType, pushCallBack); + { + std::lock_guard lock(pushMutex_); + pushCallBacks_.insert_or_assign(slotType, pushCallBack); + } ANS_LOGD("insert pushCallBack, slot type %{public}d", slotType); notificationCheckRequest->SetUid(uid); checkRequests_.insert_or_assign(slotType, notificationCheckRequest); @@ -1905,7 +1932,10 @@ ErrCode AdvancedNotificationService::UnregisterPushCallback() return ERR_INVALID_OPERATION; } - pushCallBacks_.clear(); + { + std::lock_guard lock(pushMutex_); + pushCallBacks_.clear(); + } ANS_LOGD("end"); return ERR_OK; @@ -2001,6 +2031,11 @@ ErrCode AdvancedNotificationService::PushCheck(const sptr & } ErrCode result = pushCallBack->OnCheckNotification(jsonObject.dump(), nullptr); + if (result != ERR_OK) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_5) + .ErrorCode(result).Message("Push OnCheckNotification failed."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + } return result; } @@ -2015,6 +2050,7 @@ void AdvancedNotificationService::TriggerAutoDelete(const std::string &hashCode, if (record->notification->GetKey() == hashCode) { UpdateRecentNotification(record->notification, true, reason); + CancelTimer(record->notification->GetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, nullptr, reason); ProcForDeleteLiveView(record); notificationList_.remove(record); @@ -2096,13 +2132,13 @@ ErrCode AdvancedNotificationService::CheckSoundPermission(const sptrGetSound().length(); if (length > MAX_SOUND_ITEM_LENGTH) { ANS_LOGE("Check sound length failed: %{public}d", length); return ERR_ANS_INVALID_PARAM; } - + // Update sound permission info cache ANS_LOGD("Check sound permission: %{public}d, %{public}s, %{public}d", length, bundleName.c_str(), soundPermissionInfo_->needUpdateCache_.load()); @@ -2116,20 +2152,16 @@ ErrCode AdvancedNotificationService::CheckSoundPermission(const sptrneedUpdateCache_ = false; } } - + if (!soundPermissionInfo_->allPackage_ && soundPermissionInfo_->bundleName_.count(bundleName) == 0) { request->SetSound(""); } return ERR_OK; } -ErrCode AdvancedNotificationService::CheckSystemLiveView(const sptr &request, +ErrCode AdvancedNotificationService::CheckLongTermLiveView(const sptr &request, const std::string &key) { - if (!request->IsSystemLiveView()) { - return ERR_OK; - } - // live view, not update std::shared_ptr additionalData = request->GetAdditionalData(); if (additionalData && additionalData->HasParam("SYSTEM_UPDATE_ONLY")) { @@ -2140,7 +2172,7 @@ ErrCode AdvancedNotificationService::CheckSystemLiveView(const sptr &record, bool isSystemApp, bool isUpdateByOwner) + const std::shared_ptr &record, bool isSystemApp, bool isUpdateByOwner, + const bool isAgentController) { auto result = AssignValidNotificationSlot(record, record->bundleOption); if (result != ERR_OK) { @@ -2163,7 +2196,7 @@ ErrCode AdvancedNotificationService::AddRecordToMemory( } if (isSystemApp) { - ChangeNotificationByControlFlags(record); + ChangeNotificationByControlFlags(record, isAgentController); } CheckDoNotDisturbProfile(record); @@ -2174,7 +2207,7 @@ ErrCode AdvancedNotificationService::AddRecordToMemory( } // solve long term continuous update(music) - if (!remove && CheckSystemLiveView(record->request, record->notification->GetKey()) != ERR_OK) { + if (!remove && CheckLongTermLiveView(record->request, record->notification->GetKey()) != ERR_OK) { return ERR_ANS_INVALID_PARAM; } @@ -2202,6 +2235,26 @@ ErrCode AdvancedNotificationService::RegisterSwingCallback(const sptrsubmit_h(std::bind([&]() { + HandleUpdateLiveViewNotificationTimer(uid, isPaused); + })); + notificationSvrQueue_->wait(handler); + return ERR_OK; +} + void PushCallbackRecipient::OnRemoteDied(const wptr &remote) { ANS_LOGI("Push Callback died, remove the proxy object"); diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index b9e8c6c20c5e5f5e837b398c5970055a2debfe35..e02fe5b70e53c2d3546fdd186ff281f00a5b09c8 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -16,6 +16,8 @@ #include "advanced_notification_service_ability.h" #include "notification_extension_wrapper.h" #include "system_event_observer.h" +#include "common_event_manager.h" +#include "telephony_extension_wrapper.h" namespace OHOS { namespace Notification { @@ -23,6 +25,9 @@ namespace { REGISTER_SYSTEM_ABILITY_BY_ID(AdvancedNotificationServiceAbility, ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, true); } +const std::string EXTENSION_BACKUP = "backup"; +const std::string EXTENSION_RESTORE = "restore"; + AdvancedNotificationServiceAbility::AdvancedNotificationServiceAbility(const int32_t systemAbilityId, bool runOnCreate) : SystemAbility(systemAbilityId, runOnCreate), service_(nullptr) {} @@ -48,8 +53,13 @@ void AdvancedNotificationServiceAbility::OnStart() EXTENTION_WRAPPER->InitExtentionWrapper(); AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); + AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); #else - ANS_LOGI("Not enabled ans_ext"); + ANS_LOGD("Not enabled ans_ext"); +#endif + +#ifdef ENABLE_ANS_TELEPHONY_CUST_WRAPPER + TEL_EXTENTION_WRAPPER->InitTelExtentionWrapper(); #endif } @@ -84,6 +94,17 @@ void AdvancedNotificationServiceAbility::OnAddSystemAbility(int32_t systemAbilit return; } EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_); + } else if (systemAbilityId == BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) { + ANS_LOGW("BUNDLE_MGR_SERVICE_SYS_ABILITY_ID"); + if (isDatashaReready_) { + return; + } + auto notificationService = AdvancedNotificationService::GetInstance(); + if (notificationService == nullptr) { + ANS_LOGW("notification service is not initial."); + return; + } + notificationService->ResetDistributedEnabled(); } } @@ -108,5 +129,22 @@ void AdvancedNotificationServiceAbility::OnRemoveSystemAbility(int32_t systemAbi return; } } + +int32_t AdvancedNotificationServiceAbility::OnExtension(const std::string& extension, + MessageParcel& data, MessageParcel& reply) +{ + ANS_LOGI("extension is %{public}s.", extension.c_str()); + auto notificationService = AdvancedNotificationService::GetInstance(); + if (notificationService == nullptr) { + ANS_LOGW("notification service is not initial."); + return ERR_OK; + } + if (extension == EXTENSION_BACKUP) { + return notificationService->OnBackup(data, reply); + } else if (extension == EXTENSION_RESTORE) { + return notificationService->OnRestore(data, reply); + } + return ERR_OK; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index d90d2828d7a234c68f5cfc9fb9de28be993f208d..453a65859f18c61a284c06e9c1b16d0d7679e48a 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -31,11 +31,14 @@ #include "ipc_skeleton.h" #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED #include "smart_reminder_center.h" +#else +#include "notification_config_parse.h" #endif #include "advanced_notification_inline.cpp" #include "notification_extension_wrapper.h" #include "notification_analytics_util.h" +#include "notification_trust_list.h" namespace OHOS { namespace Notification { @@ -44,8 +47,7 @@ namespace { constexpr char CTRL_LIST_KEY_NAME[] = "NOTIFICATION_CTL_LIST_PKG"; constexpr char CALL_UI_BUNDLE[] = "com.ohos.callui"; } -const uint32_t DEFAULT_SLOT_FLAGS = 59; // 0b111011 -const uint32_t SA_SLOT_FLAGS = 63; // 0b111111 + ErrCode AdvancedNotificationService::AddSlots(const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -410,23 +412,31 @@ ErrCode AdvancedNotificationService::SetSlotFlagsAsBundle(const sptrGetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " slotFlags:" + std::to_string(slotFlags)); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - ANS_LOGD("IsSystemApp is false."); + ANS_LOGE("IsSystemApp is false."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + ANS_LOGE("Permission denied."); + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission denied"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_PERMISSION_DENIED; } sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { - ANS_LOGD("Bundle is null."); + ANS_LOGE("Bundle is null."); return ERR_ANS_INVALID_BUNDLE; } @@ -441,13 +451,13 @@ ErrCode AdvancedNotificationService::SetSlotFlagsAsBundle(const sptrGetBundleName().c_str()); + ANS_LOGI("Set slotflags %{public}d to %{public}s.", slotFlags, bundle->GetBundleName().c_str()); result = UpdateSlotReminderModeBySlotFlags(bundle, slotFlags); })); notificationSvrQueue_->wait(handler); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_2) - .Message("Set slotflags " + bundleOption->GetBundleName() + " flag " + - std::to_string(slotFlags) + " ret " + std::to_string(result)); + ANS_LOGI("%{public}s_%{public}d, slotFlags: %{public}d, SetSlotFlagsAsBundle result: %{public}d", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), slotFlags, result); + message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -457,6 +467,7 @@ ErrCode AdvancedNotificationService::AssignValidNotificationSlot(const std::shar { sptr slot; NotificationConstant::SlotType slotType = record->request->GetSlotType(); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_3).SlotType(slotType); ErrCode result = NotificationPreferences::GetInstance()->GetNotificationSlot(bundleOption, slotType, slot); if ((result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) || (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST)) { @@ -474,13 +485,19 @@ ErrCode AdvancedNotificationService::AssignValidNotificationSlot(const std::shar if (result == ERR_OK) { if (slot != nullptr && (bundleOption->GetBundleName() == CALL_UI_BUNDLE || slot->GetEnable() || - (record->request->IsAgentNotification() && record->request->IsSystemLiveView()))) { + (record->request->GetAgentBundle() != nullptr && record->request->IsSystemLiveView()) || + (slot->GetType() == NotificationConstant::SlotType::LIVE_VIEW && + DelayedSingleton::GetInstance()->IsLiveViewTrtust(bundleOption->GetBundleName())))) { record->slot = slot; } else { result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED; ANS_LOGE("Type[%{public}d] slot enable closed", slotType); } } + if (result != ERR_OK) { + message.ErrorCode(result).Message("assign slot failed"); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } return result; } @@ -504,13 +521,10 @@ ErrCode AdvancedNotificationService::UpdateSlotReminderModeBySlotFlags( } for (auto slot : slots) { - auto configSlotReminderMode = - DelayedSingleton::GetInstance()->GetConfigSlotReminderModeByType(slot->GetType()); + auto configSlotReminderMode = DelayedSingleton::GetInstance()-> + GetConfigSlotReminderModeByType(slot->GetType(), bundle); slot->SetReminderMode(slotFlags & configSlotReminderMode); std::string bundleName = (bundle == nullptr) ? "" : bundle->GetBundleName(); - message.Message("Update reminderMode " + std::to_string(slot->GetType()) + ' ' - + std::to_string(slot->GetReminderMode())); - NotificationAnalyticsUtil::ReportModifyEvent(message); ANS_LOGD("Update reminderMode of %{public}d in %{public}s, value is %{public}d.", slot->GetType(), bundleName.c_str(), slot->GetReminderMode()); } @@ -522,22 +536,17 @@ ErrCode AdvancedNotificationService::UpdateSlotReminderModeBySlotFlags( return ret; } -void AdvancedNotificationService::GenerateSlotReminderMode( - const sptr &slot, const sptr &bundle, bool isSpecifiedSlot) +void AdvancedNotificationService::GenerateSlotReminderMode(const sptr &slot, + const sptr &bundle, bool isSpecifiedSlot, uint32_t defaultSlotFlags) { - uint32_t slotFlags = DEFAULT_SLOT_FLAGS; - bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); - if (isSubsystem) { - ANS_LOGD("GenerateSlotReminderMode isSubsystem in"); - slotFlags = SA_SLOT_FLAGS; - } + uint32_t slotFlags = defaultSlotFlags; auto ret = NotificationPreferences::GetInstance()->GetNotificationSlotFlagsForBundle(bundle, slotFlags); if (ret != ERR_OK) { ANS_LOGI("Failed to get slotflags for bundle, use default slotflags."); } - auto configSlotReminderMode = - DelayedSingleton::GetInstance()->GetConfigSlotReminderModeByType(slot->GetType()); + auto configSlotReminderMode = DelayedSingleton::GetInstance()-> + GetConfigSlotReminderModeByType(slot->GetType(), bundle); if (isSpecifiedSlot) { slot->SetReminderMode(configSlotReminderMode & slotFlags & slot->GetReminderMode()); } else { @@ -545,8 +554,27 @@ void AdvancedNotificationService::GenerateSlotReminderMode( } std::string bundleName = (bundle == nullptr) ? "" : bundle->GetBundleName(); - ANS_LOGD("The reminder mode of %{public}d is %{public}d in %{public}s", - slot->GetType(), slot->GetReminderMode(), bundleName.c_str()); + ANS_LOGI("The reminder mode of %{public}d is %{public}d in %{public}s,specifiedSlot:%{public}d default:%{public}u", + slot->GetType(), slot->GetReminderMode(), bundleName.c_str(), isSpecifiedSlot, defaultSlotFlags); +} + +uint32_t AdvancedNotificationService::GetDefaultSlotFlags(const sptr &request) +{ + auto flags = DEFAULT_SLOT_FLAGS; + uint32_t notificationControlFlags = request->GetNotificationControlFlags(); + // SA publish own's notification with banner + if ((notificationControlFlags & NotificationConstant::ReminderFlag::SA_SELF_BANNER_FLAG) != 0) { + ANS_LOGI("Creator:%{public}s %{public}d,Owner: %{public}s %{public}d, controlFlags:%{public}d", + request->GetCreatorBundleName().c_str(), request->GetCreatorUid(), request->GetOwnerBundleName().c_str(), + request->GetOwnerUid(), request->GetNotificationControlFlags()); + } + if (((notificationControlFlags & NotificationConstant::ReminderFlag::SA_SELF_BANNER_FLAG) != 0) && + (request->GetCreatorUid() == IPCSkeleton::GetCallingUid() && request->GetCreatorBundleName().empty() && + request->GetOwnerBundleName().empty())) { + return (flags |= NotificationConstant::ReminderFlag::BANNER_FLAG); + } + + return flags; } void AdvancedNotificationService::SetRequestBySlotType(const sptr &request, @@ -565,7 +593,8 @@ void AdvancedNotificationService::SetRequestBySlotType(const sptrGetReminderMode(); @@ -594,8 +623,8 @@ void AdvancedNotificationService::SetRequestBySlotType(const sptrSetFlags(flags); - ANS_LOGD("The reminder flags of %{public}s is %{public}d", - request->GetBaseKey("").c_str(), flags->GetReminderFlags()); + ANS_LOGI("SetFlags-GetRemindMode, notificationKey = %{public}s flags = %{public}d", + request->GetKey().c_str(), flags->GetReminderFlags()); #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED DelayedSingleton::GetInstance()->ReminderDecisionProcess(request); #endif @@ -749,14 +778,17 @@ bool AdvancedNotificationService::PublishSlotChangeCommonEvent(const sptrSyncAdditionConfig(key, value); if (sync_result != ERR_OK) { + ANS_LOGE("Sync addition config result: %{public}d, key: %{public}s, value: %{public}s", + sync_result, key.c_str(), value.c_str()); message.Message("Set addition config " + key + " ret " + std::to_string(sync_result)); + message.ErrorCode(sync_result); NotificationAnalyticsUtil::ReportModifyEvent(message); return sync_result; } @@ -783,8 +818,13 @@ ErrCode AdvancedNotificationService::SetAdditionConfig(const std::string &key, c result = NotificationPreferences::GetInstance()->SetKvToDb(key, value, SUBSCRIBE_USER_INIT); })); notificationSvrQueue_->wait(handler); - message.Message("Set addition config " + key + " ret " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGI("Set addition config result: %{public}d, key: %{public}s, value: %{public}s", + result, key.c_str(), value.c_str()); + if (result != ERR_OK) { + message.ErrorCode(result); + message.Message("Set addition config " + key + " ret " + std::to_string(result)); + NotificationAnalyticsUtil::ReportModifyEvent(message); + } return result; } diff --git a/services/ans/src/advanced_notification_subscriber_service.cpp b/services/ans/src/advanced_notification_subscriber_service.cpp index 6c4288d54b6000521765b013fd72f264a758da3c..846556fab40bbca01af165264ca9926718ad48fe 100644 --- a/services/ans/src/advanced_notification_subscriber_service.cpp +++ b/services/ans/src/advanced_notification_subscriber_service.cpp @@ -46,7 +46,6 @@ ErrCode AdvancedNotificationService::Subscribe( { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s", __FUNCTION__); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_1); ErrCode errCode = ERR_OK; do { if (subscriber == nullptr) { @@ -78,8 +77,6 @@ ErrCode AdvancedNotificationService::Subscribe( break; } } while (0); - message.Message("Subscribe notification: " + std::to_string(errCode)); - NotificationAnalyticsUtil::ReportModifyEvent(message); SendSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), info, errCode); return errCode; } @@ -90,7 +87,6 @@ ErrCode AdvancedNotificationService::SubscribeSelf(const sptr sptrInfo = new (std::nothrow) NotificationSubscribeInfo(); ErrCode errCode = ERR_OK; - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_2); do { if (subscriber == nullptr) { errCode = ERR_ANS_INVALID_PARAM; @@ -121,13 +117,12 @@ ErrCode AdvancedNotificationService::SubscribeSelf(const sptrsubmit_h(std::bind([&]() { LivePublishProcess::GetInstance()->AddLiveViewSubscriber(callingUid); })); + notificationSvrQueue_->wait(handler); } SendSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), sptrInfo, errCode); return errCode; diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index decf7240db4ef9590049a95a8b889eda82c13705..b7e6baa681c5edd41b7fc72d7926c8227de8144d 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -32,12 +32,14 @@ #include "os_account_manager.h" #include "notification_preferences.h" #include "distributed_database.h" +#include "os_account_manager_helper.h" #include "singleton.h" #include "want_agent_helper.h" #include "hitrace_meter.h" #include "notification_timer_info.h" #include "time_service_client.h" #include "notification_extension_wrapper.h" +#include "string_utils.h" #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED #include "distributed_notification_manager.h" @@ -47,6 +49,9 @@ #include "advanced_notification_inline.cpp" #include "notification_analytics_util.h" +#include "notification_clone_disturb_service.h" +#include "notification_clone_bundle_service.h" +#include "advanced_notification_flow_control_service.h" #define CHECK_BUNDLE_OPTION_IS_INVALID(option) \ if (option == nullptr || option->GetBundleName().empty()) { \ @@ -75,6 +80,12 @@ constexpr char RECENT_NOTIFICATION_OPTION[] = "recent"; constexpr char HIDUMPER_ERR_MSG[] = "error: unknown option.\nThe arguments are illegal and you can enter '-h' for help."; constexpr int32_t MAIN_USER_ID = 100; +constexpr int32_t FIRST_USERID = 0; +constexpr char OLD_KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION[] = "enabledNotificationDistributed"; +constexpr char KEY_TABLE_VERSION[] = "tableVersion"; +constexpr char SPLIT_FLAG[] = "-"; +constexpr int32_t KEYWORD_SIZE = 4; +constexpr int32_t MIN_VERSION = 1; const std::unordered_map HIDUMPER_CMD_MAP = { { "--help", HELP_NOTIFICATION_OPTION }, { "--active", ACTIVE_NOTIFICATION_OPTION }, @@ -91,15 +102,6 @@ constexpr char HIDUMPER_HELP_MSG[] = " --recent, -r list recent notifications\n"; } -static bool SortNotificationsByLevelAndTime( - const std::shared_ptr &first, const std::shared_ptr &second) -{ - if (first->slot->GetLevel() != second->slot->GetLevel()) { - return (first->slot->GetLevel() < second->slot->GetLevel()); - } - return (first->request->GetCreateTime() < second->request->GetCreateTime()); -} - std::shared_ptr AdvancedNotificationService::GetNotificationSvrQueue() { return notificationSvrQueue_; @@ -107,14 +109,11 @@ std::shared_ptr AdvancedNotificationService::GetNotificationSvrQueu sptr AdvancedNotificationService::GenerateBundleOption() { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_1); sptr bundleOption = nullptr; std::string bundle = ""; if (!AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID())) { bundle = GetClientBundleName(); if (bundle.empty()) { - message.Message("bundleOption is nullptr", true); - NotificationAnalyticsUtil::ReportModifyEvent(message); return nullptr; } } @@ -122,8 +121,6 @@ sptr AdvancedNotificationService::GenerateBundleOption int32_t uid = IPCSkeleton::GetCallingUid(); bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); if (bundleOption == nullptr) { - message.Message("Failed to create instance" + std::to_string(uid), true); - NotificationAnalyticsUtil::ReportModifyEvent(message); return nullptr; } return bundleOption; @@ -142,7 +139,7 @@ sptr AdvancedNotificationService::GenerateValidBundleO std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { int32_t activeUserId = -1; - if (!GetActiveUserId(activeUserId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { ANS_LOGE("Failed to get active user id!"); return validBundleOption; } @@ -259,29 +256,13 @@ ErrCode AdvancedNotificationService::FillRequestByKeys(const sptr &record) + const std::shared_ptr &record, const sptr &bundleOption) { - bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); - if (isSubsystem || AccessTokenHelper::IsSystemApp()) { - if (AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { - return ERR_OK; - } - - ANS_LOGD("Get live view by filter failed because check permission is false."); - return ERR_ANS_PERMISSION_DENIED; - } - - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { - ANS_LOGD("Get live view by filter failed because bundle name is empty."); - return ERR_ANS_PERMISSION_DENIED; - } - int32_t uid = IPCSkeleton::GetCallingUid(); - if (uid == record->bundleOption->GetUid() && bundle == record->bundleOption->GetBundleName()) { + if (bundleOption->GetUid() == record->bundleOption->GetUid() && + bundleOption->GetBundleName() == record->bundleOption->GetBundleName()) { return ERR_OK; } - - ANS_LOGD("Get live view by filter failed because no permission."); + ANS_LOGE("Get live view by filter failed because no permission."); return ERR_ANS_PERMISSION_DENIED; } @@ -290,17 +271,26 @@ ErrCode AdvancedNotificationService::GetActiveNotificationByFilter( const std::vector extraInfoKeys, sptr &request) { ANS_LOGD("%{public}s", __FUNCTION__); + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + // get other bundle notification need controller permission + if (bundle->GetUid() == IPCSkeleton::GetCallingUid()) { + ANS_LOGI("Get self notification uid: %{public}d, curUid: %{public}d.", + bundle->GetUid(), IPCSkeleton::GetCallingUid()); + } else { + if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + ANS_LOGW("Get live view by filter failed because check permission is false."); + return ERR_ANS_PERMISSION_DENIED; + } + } if (notificationSvrQueue_ == nullptr) { ANS_LOGE("Serial queue is invalidity."); return ERR_ANS_INVALID_PARAM; } - sptr bundle = GenerateValidBundleOption(bundleOption); - if (bundle == nullptr) { - return ERR_ANS_INVALID_BUNDLE; - } - ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS; ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); @@ -309,7 +299,7 @@ ErrCode AdvancedNotificationService::GetActiveNotificationByFilter( if ((record == nullptr) || (!record->request->IsCommonLiveView())) { return; } - result = IsAllowedGetNotificationByFilter(record); + result = IsAllowedGetNotificationByFilter(record, bundle); if (result != ERR_OK) { return; } @@ -334,7 +324,7 @@ void AdvancedNotificationService::SetAgentNotification(sptr { auto bundleManager = BundleManagerHelper::GetInstance(); int32_t activeUserId = -1; - if (!GetActiveUserId(activeUserId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { ANSR_LOGW("Failed to get active user id!"); return; } @@ -344,30 +334,6 @@ void AdvancedNotificationService::SetAgentNotification(sptr notificationRequest->SetOwnerBundleName(bundleName); } -void AdvancedNotificationService::ExtendDumpForFlags( - std::shared_ptr notificationFlags, std::stringstream &stream) -{ - if (notificationFlags == nullptr) { - ANS_LOGD("The notificationFlags is nullptr."); - return; - } - stream << "\t\tReminderFlags : " << notificationFlags->GetReminderFlags() << "\n"; - bool isEnable = false; - if (notificationFlags->IsSoundEnabled() == NotificationConstant::FlagStatus::OPEN) { - isEnable = true; - } - stream << "\t\tSound : " << isEnable << "\n"; - isEnable = false; - if (notificationFlags->IsVibrationEnabled() == NotificationConstant::FlagStatus::OPEN) { - isEnable = true; - } - stream << "\t\tVibration : " << isEnable << "\n"; - stream << "\t\tLockScreenVisbleness : " << notificationFlags->IsLockScreenVisblenessEnabled() << "\n"; - stream << "\t\tBanner : " << notificationFlags->IsBannerEnabled() << "\n"; - stream << "\t\tLightScreen : " << notificationFlags->IsLightScreenEnabled() << "\n"; - stream << "\t\tStatusIcon : " << notificationFlags->IsStatusIconEnabled() << "\n"; -} - ErrCode AdvancedNotificationService::ActiveNotificationDump(const std::string& bundle, int32_t userId, int32_t recvUserId, std::vector &dumpInfo) { @@ -408,7 +374,6 @@ ErrCode AdvancedNotificationService::ActiveNotificationDump(const std::string& b stream << "\t\tId: " << record->notification->GetId() << "\n"; stream << "\t\tLabel: " << record->notification->GetLabel() << "\n"; stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n"; - ExtendDumpForFlags(record->request->GetFlags(), stream); ANS_LOGD("DumpInfo push stream."); dumpInfo.push_back(stream.str()); } @@ -454,7 +419,6 @@ ErrCode AdvancedNotificationService::RecentNotificationDump(const std::string& b stream << "\t\tId: " << recentNotification->notification->GetId() << "\n"; stream << "\t\tLabel: " << recentNotification->notification->GetLabel() << "\n"; stream << "\t\tSlotType = " << notificationRequest.GetSlotType() << "\n"; - ExtendDumpForFlags(notificationRequest.GetFlags(), stream); dumpInfo.push_back(stream.str()); } return ERR_OK; @@ -498,7 +462,6 @@ ErrCode AdvancedNotificationService::DistributedNotificationDump(const std::stri stream << "\t\tId: " << record->notification->GetId() << "\n"; stream << "\t\tLabel: " << record->notification->GetLabel() << "\n"; stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n"; - ExtendDumpForFlags(record->request->GetFlags(), stream); dumpInfo.push_back(stream.str()); } @@ -547,6 +510,7 @@ void AdvancedNotificationService::OnBundleRemoved(const sptr keys = GetNotificationKeys(bundleOption); #endif std::vector> notifications; + std::vector timerIds; for (auto key : keys) { sptr notification = nullptr; result = RemoveFromNotificationList(key, notification, true, @@ -559,6 +523,7 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrGetAutoDeletedTimer()); ExecBatchCancel(notifications, reason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete("", "", notification); @@ -569,8 +534,10 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrBatchNotifyCanceled( notifications, nullptr, NotificationConstant::PACKAGE_REMOVE_REASON_DELETE); } + BatchCancelTimer(timerIds); NotificationPreferences::GetInstance()->RemoveAnsBundleDbInfo(bundleOption); RemoveDoNotDisturbProfileTrustList(bundleOption); + DeleteDuplicateMsgs(bundleOption); })); NotificationPreferences::GetInstance()->RemoveEnabledDbByBundle(bundleOption); #ifdef ENABLE_ANS_EXT_WRAPPER @@ -625,8 +592,10 @@ void AdvancedNotificationService::OnBundleDataAdd(const sptrOnBundleDataAdd(bundleOption); }; + NotificationCloneDisturb::GetInstance()->OnBundleDataAdd(bundleOption); notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleInstall) : bundleInstall(); } @@ -644,39 +613,17 @@ void AdvancedNotificationService::OnBundleDataUpdate(const sptrGetHasPoppedDialog(bundleOption, hasPopped); + bool enabled = false; + auto errCode = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle( + bundleOption, enabled); if (errCode != ERR_OK) { ANS_LOGD("Get notification user option fail, need to insert data"); - errCode = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle( - bundleOption, bundleInfo.applicationInfo.allowEnableNotification); - if (errCode != ERR_OK) { - ANS_LOGE("Set notification enable error! code: %{public}d", errCode); - } - SetSlotFlagsTrustlistsAsBundle(bundleOption); - errCode = NotificationPreferences::GetInstance()->SetShowBadge(bundleOption, true); - if (errCode != ERR_OK) { - ANS_LOGE("Set badge enable error! code: %{public}d", errCode); - } - return; - } - - if (hasPopped) { - ANS_LOGI("The user has made changes, subject to the user's selection"); + OnBundleDataAdd(bundleOption); return; } - - errCode = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle( - bundleOption, bundleInfo.applicationInfo.allowEnableNotification); - if (errCode != ERR_OK) { - ANS_LOGE("Set notification enable error! code: %{public}d", errCode); - } - errCode = NotificationPreferences::GetInstance()->SetShowBadge(bundleOption, true); - if (errCode != ERR_OK) { - ANS_LOGE("Set badge enable error! code: %{public}d", errCode); - } }; + NotificationCloneDisturb::GetInstance()->OnBundleDataUpdate(bundleOption); notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleUpdate) : bundleUpdate(); } @@ -722,10 +669,10 @@ ErrCode AdvancedNotificationService::GetTargetRecordList(const int32_t uid, std::vector>& recordList) { for (auto& notification : notificationList_) { - if (notification->request != nullptr && notification->request->GetCreatorUid() == uid && - notification->request->GetSlotType()== slotType && - notification->request->GetNotificationType() == contentType) { - recordList.emplace_back(notification); + if (notification->request != nullptr && notification->request->GetSlotType()== slotType && + notification->request->GetNotificationType() == contentType && + notification->request->GetCreatorUid() == uid) { + recordList.emplace_back(notification); } } if (recordList.empty()) { @@ -827,7 +774,7 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptr &profile) +{ + ANS_LOGD("Called."); + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); + if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + return ERR_ANS_PERMISSION_DENIED; + } + int32_t userId = SUBSCRIBE_USER_INIT; + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) { + ANS_LOGW("No active user found."); + return ERR_ANS_GET_ACTIVE_USER_FAILED; + } + + profile = new (std::nothrow) NotificationDoNotDisturbProfile(); + ErrCode result = NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(id, userId, profile); + if (result != ERR_OK) { + ANS_LOGE("profile failed id: %{public}d, userid: %{public}d", id, userId); + } + return result; +} + ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSupport) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -937,7 +908,7 @@ void AdvancedNotificationService::OnDistributedPublish( { ANS_LOGD("%{public}s", __FUNCTION__); int32_t activeUserId = -1; - if (!GetActiveUserId(activeUserId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { ANS_LOGE("Failed to get active user id!"); return; } @@ -946,7 +917,8 @@ void AdvancedNotificationService::OnDistributedPublish( ANS_LOGE("notificationSvrQueue_ is nullptr."); return; } - notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId]() { + const int32_t callingUid = IPCSkeleton::GetCallingUid(); + notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId, callingUid]() { ANS_LOGD("ffrt enter!"); if (!CheckDistributedNotificationType(request)) { ANS_LOGD("CheckDistributedNotificationType is false."); @@ -996,7 +968,12 @@ void AdvancedNotificationService::OnDistributedPublish( return; } - result = PublishFlowControl(record); + bool isNotificationExists = IsNotificationExists(record->notification->GetKey()); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, isNotificationExists); + if (result != ERR_OK) { + return; + } + result = PublishInNotificationList(record); if (result != ERR_OK) { return; } @@ -1012,7 +989,7 @@ void AdvancedNotificationService::OnDistributedUpdate( { ANS_LOGD("%{public}s", __FUNCTION__); int32_t activeUserId = -1; - if (!GetActiveUserId(activeUserId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { ANS_LOGE("Failed to get active user id!"); return; } @@ -1021,7 +998,8 @@ void AdvancedNotificationService::OnDistributedUpdate( ANS_LOGE("Serial queue is invalid."); return; } - notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId]() { + const int32_t callingUid = IPCSkeleton::GetCallingUid(); + notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId, callingUid]() { ANS_LOGD("ffrt enter!"); if (!CheckDistributedNotificationType(request)) { ANS_LOGD("device type not support display."); @@ -1069,7 +1047,11 @@ void AdvancedNotificationService::OnDistributedUpdate( ANS_LOGE("Reject by filters: %{public}d", result); return; } - + bool isNotificationExists = IsNotificationExists(record->notification->GetKey()); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, isNotificationExists); + if (result != ERR_OK) { + return; + } if (IsNotificationExists(record->notification->GetKey())) { if (record->request->IsAlertOneTime()) { CloseAlert(record); @@ -1094,7 +1076,7 @@ void AdvancedNotificationService::OnDistributedDelete( notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, label, id]() { ANS_LOGD("ffrt enter!"); int32_t activeUserId = -1; - if (!GetActiveUserId(activeUserId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { ANS_LOGE("Failed to get active user id!"); return; } @@ -1133,6 +1115,7 @@ void AdvancedNotificationService::OnDistributedDelete( if (notification != nullptr) { int32_t reason = NotificationConstant::APP_CANCEL_REASON_OTHER; UpdateRecentNotification(notification, true, reason); + CancelTimer(notification->GetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason); } })); @@ -1201,8 +1184,10 @@ std::vector AdvancedNotificationService::GetLocalNotificationKeys( std::vector keys; for (auto record : notificationList_) { - if ((bundleOption != nullptr) && (record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) && - (record->bundleOption->GetUid() != bundleOption->GetUid()) && record->deviceId.empty()) { + if ((bundleOption != nullptr) && + ((record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) || + (record->bundleOption->GetUid() != bundleOption->GetUid())) && + record->deviceId.empty()) { continue; } keys.push_back(record->notification->GetKey()); @@ -1259,7 +1244,7 @@ ErrCode AdvancedNotificationService::DoDistributedDelete( const std::string deviceId, const std::string bundleName, const sptr notification) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); - if (!notification->GetNotificationRequest().GetNotificationDistributedOptions().IsDistributed()) { + if (!notification->GetNotificationRequestPoint()->GetNotificationDistributedOptions().IsDistributed()) { return ERR_OK; } if (deviceId.empty()) { @@ -1305,18 +1290,6 @@ ErrCode AdvancedNotificationService::IsSupportTemplate(const std::string& templa return result; } -bool AdvancedNotificationService::GetActiveUserId(int& userId) -{ - std::vector activeUserId; - OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); - if (activeUserId.size() > 0) { - userId = activeUserId[0]; - ANS_LOGD("Return active userId=%{public}d", userId); - return true; - } - return false; -} - void AdvancedNotificationService::TriggerRemoveWantAgent(const sptr &request) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); @@ -1338,7 +1311,7 @@ void AdvancedNotificationService::OnResourceRemove(int32_t userId) ANS_LOGE("Serial queue is invalid."); return; } - ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { + ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() { ANS_LOGD("ffrt enter!"); NotificationPreferences::GetInstance()->RemoveSettings(userId); })); @@ -1354,6 +1327,7 @@ void AdvancedNotificationService::OnBundleDataCleared(const sptr keys = GetNotificationKeys(bundleOption); std::vector> notifications; + std::vector timerIds; for (auto key : keys) { #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED std::string deviceId; @@ -1372,6 +1346,7 @@ void AdvancedNotificationService::OnBundleDataCleared(const sptrGetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -1388,17 +1363,22 @@ void AdvancedNotificationService::OnBundleDataCleared(const sptrBatchNotifyCanceled( notifications, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE); } + BatchCancelTimer(timerIds); })); } bool AdvancedNotificationService::CheckApiCompatibility(const sptr &bundleOption) { +#ifdef ANS_ENABLE_FA_MODEL ANS_LOGD("%{public}s", __FUNCTION__); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager == nullptr) { return false; } return bundleManager->CheckApiCompatibility(bundleOption); +#else + return false; +#endif } void AdvancedNotificationService::OnUserRemoved(const int32_t &userId) @@ -1437,9 +1417,6 @@ ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, if (notificationSvrQueue_ == nullptr) { std::string message = "Serial queue is invalid."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 7) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message); ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } @@ -1448,6 +1425,7 @@ ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, ANS_LOGD("ffrt enter!"); std::vector keys = GetNotificationKeys(nullptr); std::vector> notifications; + std::vector timerIds; for (auto key : keys) { #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED std::string deviceId; @@ -1464,6 +1442,7 @@ ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, if (notification->GetUserId() == userId) { UpdateRecentNotification(notification, true, deleteReason); notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -1477,7 +1456,7 @@ ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( notifications, nullptr, deleteReason); } - + BatchCancelTimer(timerIds); *result = ERR_OK; })); @@ -1735,20 +1714,79 @@ ErrCode AdvancedNotificationService::PrePublishNotificationBySa(const sptrGetOwnerUid() == DEFAULT_UID) { + request->SetOwnerUid(request->GetCreatorUid()); + } + if (request->GetOwnerBundleName().empty()) { + request->SetOwnerBundleName(request->GetCreatorBundleName()); + } ANS_LOGD("creator uid=%{public}d, userId=%{public}d, bundleName=%{public}s ", uid, userId, bundle.c_str()); return ERR_OK; } +ErrCode AdvancedNotificationService::PrePublishRequest(const sptr &request) +{ + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_0); + if (!InitPublishProcess()) { + return ERR_ANS_NO_MEMORY; + } + ErrCode result = publishProcess_[request->GetSlotType()]->PublishPreWork(request, false); + if (result != ERR_OK) { + message.BranchId(EventBranchId::BRANCH_0).ErrorCode(result).Message("publish prework failed", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return result; + } + result = CheckUserIdParams(request->GetReceiverUserId()); + if (result != ERR_OK) { + message.BranchId(EventBranchId::BRANCH_1).ErrorCode(result).Message("User is invalid", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return result; + } + + if (request->GetCreatorUid() <= 0) { + message.BranchId(EventBranchId::BRANCH_2).ErrorCode(ERR_ANS_INVALID_UID) + .Message("createUid failed" + std::to_string(request->GetCreatorUid()), true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return ERR_ANS_INVALID_UID; + } + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager == nullptr) { + ANS_LOGE("failed to get bundleManager!"); + return ERR_ANS_INVALID_BUNDLE; + } + request->SetCreatorPid(IPCSkeleton::GetCallingPid()); + int32_t userId = SUBSCRIBE_USER_INIT; + if (request->GetCreatorUserId() == SUBSCRIBE_USER_INIT) { + OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(request->GetCreatorUid(), userId); + request->SetCreatorUserId(userId); + } + + if (request->GetDeliveryTime() <= 0) { + request->SetDeliveryTime(GetCurrentTime()); + } + result = CheckPictureSize(request); + if (result != ERR_OK) { + message.ErrorCode(result).Message("Failed to check picture size", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return result; + } + return ERR_OK; +} + uint64_t AdvancedNotificationService::StartAutoDelete(const std::shared_ptr &record, int64_t deleteTimePoint, int32_t reason) { ANS_LOGD("Enter"); - - auto triggerFunc = [this, record, reason, deleteTimePoint] { - TriggerAutoDelete(record->notification->GetKey(), reason); - if (record->finish_status != NotificationConstant::DEFAULT_FINISH_STATUS) { - SendLiveViewUploadHiSysEvent(record, record->finish_status); + + wptr wThis = this; + auto triggerFunc = [wThis, record, reason, deleteTimePoint] { + sptr sThis = wThis.promote(); + if (sThis != nullptr) { + sThis->TriggerAutoDelete(record->notification->GetKey(), reason); + if (record->finish_status != NotificationConstant::DEFAULT_FINISH_STATUS) { + sThis->SendLiveViewUploadHiSysEvent(record, record->finish_status); + } } }; std::shared_ptr notificationTimerInfo = std::make_shared(); @@ -1774,6 +1812,14 @@ void AdvancedNotificationService::CancelTimer(uint64_t timerId) MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(timerId); } +void AdvancedNotificationService::BatchCancelTimer(std::vector timerIds) +{ + ANS_LOGD("Enter"); + for (uint64_t timerId : timerIds) { + CancelTimer(timerId); + } +} + void AdvancedNotificationService::SendNotificationsOnCanceled(std::vector> ¬ifications, const sptr ¬ificationMap, int32_t deleteReason) { @@ -1788,8 +1834,9 @@ void AdvancedNotificationService::SendNotificationsOnCanceled(std::vector &bundleOption) { - uint32_t slotFlags = 0b111111; - if (DelayedSingleton::GetInstance()->IsSlotFlagsTrustlistAsBundle(bundleOption)) { + if (!NotificationPreferences::GetInstance()->IsNotificationSlotFlagsExists(bundleOption) && + DelayedSingleton::GetInstance()->IsSlotFlagsTrustlistAsBundle(bundleOption)) { + uint32_t slotFlags = 0b111111; ErrCode saveRef = NotificationPreferences::GetInstance()->SetNotificationSlotFlagsForBundle( bundleOption, slotFlags); if (saveRef != ERR_OK) { @@ -1862,7 +1909,7 @@ ErrCode AdvancedNotificationService::CheckBundleOptionValid(sptr AdvancedNotificationService::GetBundlesOfAct } std::vector activeUserId; - AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); + OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(activeUserId); if (activeUserId.empty()) { activeUserId.push_back(MAIN_USER_ID); } @@ -1921,7 +1968,10 @@ void AdvancedNotificationService::CloseAlert(const std::shared_ptrSetSoundEnabled(NotificationConstant::FlagStatus::CLOSE); flag->SetLightScreenEnabled(false); flag->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE); + flag->SetBannerEnabled(false); record->request->SetFlags(flag); + ANS_LOGI("SetFlags-CloseAlert, notificationKey = %{public}s flags = %{public}d", + record->request->GetKey().c_str(), flag->GetReminderFlags()); } bool AdvancedNotificationService::AllowUseReminder(const std::string& bundleName) @@ -1931,12 +1981,104 @@ bool AdvancedNotificationService::AllowUseReminder(const std::string& bundleName } #ifdef ENABLE_ANS_EXT_WRAPPER int32_t ctrlResult = EXTENTION_WRAPPER->ReminderControl(bundleName); - if (ctrlResult != ERR_OK) { - return ctrlResult; - } + return (ctrlResult == ERR_OK) ? true : false; #else return true; #endif } + +void AdvancedNotificationService::ResetDistributedEnabled() +{ + if (notificationSvrQueue_ == nullptr) { + ANS_LOGE("notificationSvrQueue is nullptr"); + } + ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() { + std::string value; + NotificationPreferences::GetInstance()->GetKvFromDb(KEY_TABLE_VERSION, value, FIRST_USERID); + if (!value.empty()) { + return; + } + ANS_LOGI("start ResetDistributedEnabled"); + std::unordered_map oldValues; + NotificationPreferences::GetInstance()->GetBatchKvsFromDb( + OLD_KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION, oldValues, FIRST_USERID); + if (oldValues.empty()) { + NotificationPreferences::GetInstance()->SetKvToDb( + KEY_TABLE_VERSION, std::to_string(MIN_VERSION), FIRST_USERID); + return; + } + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + std::vector delKeys; + for (auto iter : oldValues) { + std::vector keywordVector; + StringUtils::Split(iter.first, SPLIT_FLAG, keywordVector); + delKeys.push_back(iter.first); + if (keywordVector.size() != KEYWORD_SIZE) { + continue; + } + std::string bundleName = keywordVector[1]; + int32_t activeUserId = atoi(keywordVector[2].c_str()); + std::string deviceType = keywordVector[3]; + bool enabled = atoi(iter.second.c_str()); + int32_t uid = bundleManager->GetDefaultUidByBundleName(bundleName, activeUserId); + if (uid <= 0) { + continue; + } + sptr bundleOption = + new NotificationBundleOption(bundleName, uid); + ErrCode result = NotificationPreferences::GetInstance()->SetDistributedEnabledByBundle( + bundleOption, deviceType, enabled); + if (result != ERR_OK) { + ANS_LOGE("SetDistributeEnabled failed! key:%{public}s, uid:%{public}d", + iter.first.c_str(), uid); + } + } + NotificationPreferences::GetInstance()->DeleteBatchKvFromDb(delKeys, FIRST_USERID); + NotificationPreferences::GetInstance()->SetKvToDb( + KEY_TABLE_VERSION, std::to_string(MIN_VERSION), FIRST_USERID); + })); +} + +ErrCode AdvancedNotificationService::OnRecoverLiveView( + const std::vector &keys) +{ + ANS_LOGD("enter"); + + std::vector> notifications; + int32_t removeReason = NotificationConstant::RECOVER_LIVE_VIEW_DELETE; + std::vector timerIds; + for (auto key : keys) { + ANS_LOGI("BatchRemoveByKeys key = %{public}s", key.c_str()); + sptr notification = nullptr; +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::string deviceId; + std::string bundleName; + GetDistributedInfo(key, deviceId, bundleName); +#endif + ErrCode result = RemoveFromNotificationList(key, notification, true, removeReason); + if (result != ERR_OK) { + continue; + } + if (notification != nullptr) { + notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, bundleName, notification); +#endif + } + if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) { + std::vector> currNotificationList = notifications; + NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( + currNotificationList, nullptr, removeReason); + notifications.clear(); + } + } + + if (!notifications.empty()) { + NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, removeReason); + } + BatchCancelTimer(timerIds); + return ERR_OK; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/bundle_manager_helper.cpp b/services/ans/src/bundle_manager_helper.cpp index 71ff872a248753bd5f6f1125252e8f8468033381..8c6932d1a3f252aafe2ec9f87164c015378ea03c 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -78,13 +78,22 @@ bool BundleManagerHelper::IsSystemApp(int32_t uid) } bool BundleManagerHelper::CheckApiCompatibility(const sptr &bundleOption) +{ + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption is nullptr"); + return false; + } + return CheckApiCompatibility(bundleOption->GetBundleName(), bundleOption->GetUid()); +} + +bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) { AppExecFwk::BundleInfo bundleInfo; int32_t callingUserId; - AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), callingUserId); - if (!GetBundleInfoByBundleName(bundleOption->GetBundleName(), callingUserId, bundleInfo)) { + AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, callingUserId); + if (!GetBundleInfoByBundleName(bundleName, callingUserId, bundleInfo)) { ANS_LOGW("Failed to GetBundleInfoByBundleName, bundlename = %{public}s", - bundleOption->GetBundleName().c_str()); + bundleName.c_str()); return false; } @@ -190,7 +199,7 @@ bool BundleManagerHelper::GetBundleInfo(const std::string &bundleName, const App std::lock_guard lock(connectionMutex_); Connect(); - + if (bundleMgr_ == nullptr) { return false; } @@ -217,5 +226,37 @@ bool BundleManagerHelper::GetBundleInfos( IPCSkeleton::SetCallingIdentity(identity); return ret; } + +int32_t BundleManagerHelper::GetAppIndexByUid(const int32_t uid) +{ + int32_t appIndex = 0; + std::lock_guard lock(connectionMutex_); + Connect(); + if (nullptr == bundleMgr_) { + return appIndex; + } + std::string bundleName; + std::string identity = IPCSkeleton::ResetCallingIdentity(); + bundleMgr_->GetNameAndIndexForUid(uid, bundleName, appIndex); + IPCSkeleton::SetCallingIdentity(identity); + return appIndex; +} + +int32_t BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId, + const int32_t appIndex) +{ + int32_t uid = -1; + std::lock_guard lock(connectionMutex_); + Connect(); + if (bundleMgr_ != nullptr) { + std::string identity = IPCSkeleton::ResetCallingIdentity(); + uid = bundleMgr_->GetUidByBundleName(bundle, userId, appIndex); + if (uid < 0) { + ANS_LOGW("get invalid uid of bundle %{public}s in userId %{public}d", bundle.c_str(), userId); + } + IPCSkeleton::SetCallingIdentity(identity); + } + return uid; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/clone/notification_clone_bundle_info.cpp b/services/ans/src/clone/notification_clone_bundle_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f36a2a0ae14bbdc01ed06bfaaed6c30a15680d3 --- /dev/null +++ b/services/ans/src/clone/notification_clone_bundle_info.cpp @@ -0,0 +1,212 @@ +/* +* Copyright (c) 2024-2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "notification_clone_bundle_info.h" + +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { + +namespace { +constexpr const char *BUNDLE_INFO_NAME = "name"; +constexpr const char *BUNDLE_INFO_APP_INDEX = "index"; +constexpr const char *BUNDLE_INFO_SLOT_FLAGS = "slotFlags"; +constexpr const char *BUNDLE_INFO_SHOW_BADGE = "badge"; +constexpr const char *BUNDLE_INFO_ENABLE_NOTIFICATION = "enable"; +constexpr const char *BUNDLE_INFO_SLOT_LIST = "slotList"; +constexpr const char *BUNDLE_INFO_SLOT_TYPE = "slotType"; +constexpr const char *BUNDLE_INFO_SLOT_ENABLE = "slotEnable"; +constexpr const char *BUNDLE_INFO_SLOT_CONTROL = "slotControl"; +constexpr int32_t CONST_ENABLE_INT = 1; +} +void NotificationCloneBundleInfo::SetBundleName(const std::string &name) +{ + bundleName_ = name; +} + +std::string NotificationCloneBundleInfo::GetBundleName() const +{ + return bundleName_; +} + +void NotificationCloneBundleInfo::SetAppIndex(const int32_t &appIndex) +{ + appIndex_ = appIndex; +} + +int32_t NotificationCloneBundleInfo::GetAppIndex() const +{ + return appIndex_; +} + +void NotificationCloneBundleInfo::SetUid(const int32_t &uid) +{ + uid_ = uid; +} + +int32_t NotificationCloneBundleInfo::GetUid() const +{ + return uid_; +} + +void NotificationCloneBundleInfo::SetSlotFlags(const uint32_t &slotFlags) +{ + slotFlags_ = slotFlags; +} + +uint32_t NotificationCloneBundleInfo::GetSlotFlags() const +{ + return slotFlags_; +} + +void NotificationCloneBundleInfo::SetIsShowBadge(const bool &isShowBadge) +{ + isShowBadge_ = isShowBadge; +} + +bool NotificationCloneBundleInfo::GetIsShowBadge() const +{ + return isShowBadge_; +} + +void NotificationCloneBundleInfo::SetEnableNotification(const bool &enable) +{ + isEnabledNotification_ = enable; +} + +bool NotificationCloneBundleInfo::GetEnableNotification() const +{ + return isEnabledNotification_; +} + +void NotificationCloneBundleInfo::AddSlotInfo(const SlotInfo &slotInfo) +{ + for (auto& item : slotsInfo_) { + if (item.slotType_ == slotInfo.slotType_) { + item.enable_ = slotInfo.enable_; + item.isForceControl_ = slotInfo.isForceControl_; + return; + } + } + slotsInfo_.push_back(slotInfo); +} + +std::vector NotificationCloneBundleInfo::GetSlotInfo() const +{ + return slotsInfo_; +} + +void NotificationCloneBundleInfo::ToJson(nlohmann::json &jsonObject) const +{ + if (!slotsInfo_.empty()) { + nlohmann::json jsonNodes = nlohmann::json::array(); + for (size_t index = 0; index < slotsInfo_.size(); index++) { + nlohmann::json jsonNode; + jsonNode[BUNDLE_INFO_SLOT_TYPE] = static_cast(slotsInfo_[index].slotType_); + jsonNode[BUNDLE_INFO_SLOT_ENABLE] = slotsInfo_[index].enable_ ? 1 : 0; + jsonNode[BUNDLE_INFO_SLOT_CONTROL] = slotsInfo_[index].isForceControl_ ? 1 : 0; + jsonNodes.emplace_back(jsonNode); + } + jsonObject[BUNDLE_INFO_SLOT_LIST] = jsonNodes; + } + + jsonObject[BUNDLE_INFO_NAME] = bundleName_; + jsonObject[BUNDLE_INFO_APP_INDEX] = appIndex_; + jsonObject[BUNDLE_INFO_SLOT_FLAGS] = slotFlags_; + jsonObject[BUNDLE_INFO_SHOW_BADGE] = isShowBadge_ ? 1 : 0; + jsonObject[BUNDLE_INFO_ENABLE_NOTIFICATION] = isEnabledNotification_ ? 1 : 0; +} + +void NotificationCloneBundleInfo::SlotsFromJson(const nlohmann::json &jsonObject) +{ + if (!jsonObject.contains(BUNDLE_INFO_SLOT_LIST) || !jsonObject[BUNDLE_INFO_SLOT_LIST].is_array()) { + return; + } + + for (auto &slotJson : jsonObject.at(BUNDLE_INFO_SLOT_LIST)) { + SlotInfo slotInfo; + if (slotJson.contains(BUNDLE_INFO_SLOT_TYPE) && slotJson[BUNDLE_INFO_SLOT_TYPE].is_number()) { + slotInfo.slotType_ = static_cast( + slotJson.at(BUNDLE_INFO_SLOT_TYPE).get()); + } + if (slotJson.contains(BUNDLE_INFO_SLOT_ENABLE) && slotJson[BUNDLE_INFO_SLOT_ENABLE].is_number()) { + int32_t slotEnable = slotJson.at(BUNDLE_INFO_SLOT_ENABLE).get(); + slotInfo.enable_ = (slotEnable == CONST_ENABLE_INT); + } + if (slotJson.contains(BUNDLE_INFO_SLOT_CONTROL) && slotJson[BUNDLE_INFO_SLOT_CONTROL].is_number()) { + int32_t forceControl = slotJson.at(BUNDLE_INFO_SLOT_CONTROL).get(); + slotInfo.isForceControl_ = (forceControl == CONST_ENABLE_INT); + } + slotsInfo_.emplace_back(slotInfo); + } +} + +void NotificationCloneBundleInfo::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() || !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } + if (jsonObject.is_discarded()) { + ANS_LOGE("Failed to parse json string."); + return; + } + + if (jsonObject.contains(BUNDLE_INFO_NAME) && jsonObject[BUNDLE_INFO_NAME].is_string()) { + bundleName_ = jsonObject.at(BUNDLE_INFO_NAME).get(); + } + if (jsonObject.contains(BUNDLE_INFO_APP_INDEX) && jsonObject[BUNDLE_INFO_APP_INDEX].is_number()) { + appIndex_ = jsonObject.at(BUNDLE_INFO_APP_INDEX).get(); + } + if (jsonObject.contains(BUNDLE_INFO_SLOT_FLAGS) && jsonObject[BUNDLE_INFO_SLOT_FLAGS].is_number()) { + slotFlags_ = jsonObject.at(BUNDLE_INFO_SLOT_FLAGS).get(); + } + if (jsonObject.contains(BUNDLE_INFO_SHOW_BADGE) && jsonObject[BUNDLE_INFO_SHOW_BADGE].is_number()) { + int32_t showBadge = jsonObject.at(BUNDLE_INFO_SHOW_BADGE).get(); + isShowBadge_ = (showBadge == CONST_ENABLE_INT); + } + if (jsonObject.contains(BUNDLE_INFO_ENABLE_NOTIFICATION) && + jsonObject[BUNDLE_INFO_ENABLE_NOTIFICATION].is_number()) { + int32_t enabledNotification = jsonObject.at(BUNDLE_INFO_ENABLE_NOTIFICATION).get(); + isEnabledNotification_ = (enabledNotification == CONST_ENABLE_INT); + } + SlotsFromJson(jsonObject); +} +std::string NotificationCloneBundleInfo::SlotInfo::Dump() const +{ + return "type: " + std::to_string(slotType_) + " " + std::to_string(enable_) + " " + + std::to_string(isForceControl_); +} + +std::string NotificationCloneBundleInfo::Dump() const +{ + std::string slotDump = "{"; + for (auto& slot : slotsInfo_) { + slotDump += slot.Dump(); + slotDump += ","; + } + slotDump += "}"; + return "CloneBundle{ name = " + bundleName_ + + ", index = " + std::to_string(appIndex_) + + ", uid = " + std::to_string(uid_) + + ", slotFlags = " + std::to_string(slotFlags_) + + ", ShowBadge = " + std::to_string(isShowBadge_) + + ", isEnabled = " + std::to_string(isEnabledNotification_) + + ", slotsInfo = " + slotDump + + " }"; +} +} +} diff --git a/services/ans/src/clone/notification_clone_bundle_service.cpp b/services/ans/src/clone/notification_clone_bundle_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3511ce3a0c6e41cbdca62120c3d2be0aa0a0106f --- /dev/null +++ b/services/ans/src/clone/notification_clone_bundle_service.cpp @@ -0,0 +1,155 @@ +/* +* Copyright (c) 2024-2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "notification_clone_bundle_service.h" + +#include "ans_log_wrapper.h" +#include "notification_preferences.h" +#include "notification_clone_util.h" +#include "notification_clone_bundle_info.h" +#include "os_account_manager_helper.h" + +namespace OHOS { +namespace Notification { +std::shared_ptr NotificationCloneBundle::GetInstance() +{ + static std::shared_ptr instance = + std::make_shared(); + return instance; +} + +NotificationCloneBundle::NotificationCloneBundle() +{ + cloneBundleQueue_ = std::make_shared("NotificationCloneBundleQueue"); + if (!cloneBundleQueue_) { + ANS_LOGE("ffrt create failed!"); + return; + } +} + +NotificationCloneBundle::~NotificationCloneBundle() +{ +} + +ErrCode NotificationCloneBundle::OnBackup(nlohmann::json &jsonObject) +{ + ANS_LOGI("Notification bundle backup."); + int32_t userId = NotificationCloneUtil::GetActiveUserId(); + std::vector cloneBundles; + NotificationPreferences::GetInstance()->GetAllCLoneBundlesInfo(userId, cloneBundles); + + if (cloneBundles.empty()) { + ANS_LOGI("Notification bundle list is empty."); + return ERR_OK; + } + jsonObject = nlohmann::json::array(); + for (size_t index = 0; index < cloneBundles.size(); index++) { + nlohmann::json jsonNode; + cloneBundles[index].ToJson(jsonNode); + jsonObject.emplace_back(jsonNode); + ANS_LOGD("Event bundle backup %{public}s.", cloneBundles[index].Dump().c_str()); + } + ANS_LOGD("Notification bundle list %{public}s", jsonObject.dump().c_str()); + return ERR_OK; +} + +void NotificationCloneBundle::OnRestore(const nlohmann::json &jsonObject) +{ + ANS_LOGI("Notification bundle list on restore."); + if (jsonObject.is_null() || !jsonObject.is_array()) { + ANS_LOGI("Notification disturb profile list is null or not array."); + return; + } + + int32_t userId = NotificationCloneUtil::GetActiveUserId(); + std::unique_lock lock(lock_); + bundlesInfo_.clear(); + for (const auto &profile : jsonObject) { + NotificationCloneBundleInfo cloneBundleInfo;; + cloneBundleInfo.FromJson(profile); + bundlesInfo_.emplace_back(cloneBundleInfo); + } + ANS_LOGI("Notification bundle list size %{public}zu.", bundlesInfo_.size()); + if (cloneBundleQueue_ == nullptr || bundlesInfo_.empty()) { + ANS_LOGE("Clone bundle is invalidated or empty."); + return; + } + + for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end();) { + int32_t uid = NotificationCloneUtil::GetBundleUid(bundle->GetBundleName(), + userId, bundle->GetAppIndex()); + if (uid == -1) { + bundle++; + continue; + } + bundle->SetUid(uid); + NotificationPreferences::GetInstance()->UpdateCloneBundleInfo(userId, *bundle); + bundle = bundlesInfo_.erase(bundle); + } + + for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end(); bundle++) { + ANS_LOGI("Event bundle left %{public}s.", bundle->Dump().c_str()); + } + ANS_LOGI("Notification bundle list on restore end."); +} + +void NotificationCloneBundle::OnBundleDataAdd(const sptr &bundleOption) +{ + HandleBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneBundle::OnBundleDataUpdate(const sptr &bundleOption) +{ + HandleBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneBundle::HandleBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid) +{ + ANS_LOGI("Handle bundle event %{public}s %{public}d %{public}d %{public}zu.", + bundleName.c_str(), appIndex, uid, bundlesInfo_.size()); + if (bundlesInfo_.empty()) { + return; + } + + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId); + std::unique_lock lcck(lock_); + for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end();) { + if (bundle->GetBundleName() == bundleName && bundle->GetAppIndex() == appIndex) { + bundle->SetUid(uid); + NotificationPreferences::GetInstance()->UpdateCloneBundleInfo(userId, *bundle); + bundle = bundlesInfo_.erase(bundle); + break; + } + bundle++; + } + ANS_LOGI("Event bundle left %{public}zu.", bundlesInfo_.size()); +} + +void NotificationCloneBundle::OnUserSwitch(int32_t userId) +{ + ANS_LOGI("Handler user switch %{public}d", userId); + if (cloneBundleQueue_ == nullptr) { + ANS_LOGW("Clone bundle queue is null."); + return; + } + cloneBundleQueue_->submit_h(std::bind([&]() { + std::unique_lock lock(lock_); + bundlesInfo_.clear(); + })); +} + +} +} diff --git a/services/ans/src/clone/notification_clone_disturb_service.cpp b/services/ans/src/clone/notification_clone_disturb_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ec7c846658f1c333f310d690c75c02127e4f4ce --- /dev/null +++ b/services/ans/src/clone/notification_clone_disturb_service.cpp @@ -0,0 +1,219 @@ +/* +* Copyright (c) 2021-2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "notification_clone_disturb_service.h" + +#include "ans_log_wrapper.h" +#include "notification_preferences.h" +#include "notification_clone_util.h" + +namespace OHOS { +namespace Notification { +std::shared_ptr NotificationCloneDisturb::GetInstance() +{ + static std::shared_ptr instance = + std::make_shared(); + return instance; +} + +NotificationCloneDisturb::NotificationCloneDisturb() +{ + cloneDisturbQueue_ = std::make_shared("NotificationCloneDisturbQueue"); + if (!cloneDisturbQueue_) { + ANS_LOGE("ffrt create failed!"); + return; + } +} + +NotificationCloneDisturb::~NotificationCloneDisturb() +{ +} + +ErrCode NotificationCloneDisturb::OnBackup(nlohmann::json &jsonObject) +{ + int32_t userId = NotificationCloneUtil::GetActiveUserId(); + std::vector> profiles; + NotificationPreferences::GetInstance()->GetDoNotDisturbProfileListByUserId(userId, profiles); + + if (profiles.empty()) { + ANS_LOGI("Notification disturb profile list is empty."); + return ERR_OK; + } + jsonObject = nlohmann::json::array(); + for (size_t index = 0; index < profiles.size(); index++) { + nlohmann::json jsonNode; + profiles[index]->GetProfileJson(jsonNode); + jsonObject.emplace_back(jsonNode); + } + ANS_LOGD("Notification disturb profile list %{public}s", jsonObject.dump().c_str()); + return ERR_OK; +} + +void NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) +{ + ANS_LOGI("Notification disturb profile list on restore."); + if (jsonObject.is_null() || !jsonObject.is_array()) { + ANS_LOGI("Notification disturb profile list is null or not array."); + return; + } + + profiles_.clear(); + for (const auto &profile : jsonObject) { + sptr item = new (std::nothrow) NotificationDoNotDisturbProfile(); + item->FromJson(profile.dump()); + profiles_.push_back(item); + } + + if (cloneDisturbQueue_ == nullptr || profiles_.empty()) { + ANS_LOGE("Clone queue is invalidated or empty %{public}zu.", profiles_.size()); + return; + } + + int32_t userId = NotificationCloneUtil::GetActiveUserId(); + cloneDisturbQueue_->submit_h(std::bind([&, userId]() { + ANS_LOGI("Notification disturb profile ffrt start %{public}zu.", profiles_.size()); + int32_t profileId = -1; + std::string name; + std::map uidMap; + for (auto profile = profiles_.begin(); profile != profiles_.end();) { + std::vector exitBunldleList; + std::vector notExitBunldleList; + name = (*profile)->GetProfileName(); + profileId = (*profile)->GetProfileId(); + ANS_LOGI("Notification disturb profile %{public}d, %{public}zu.", profileId, + (*profile)->GetProfileTrustList().size()); + GetProfileUid(userId, uidMap, (*profile)->GetProfileTrustList(), exitBunldleList, notExitBunldleList); + NotificationPreferences::GetInstance()->UpdateDoNotDisturbProfiles(userId, + profileId, name, exitBunldleList); + if (notExitBunldleList.empty()) { + profile = profiles_.erase(profile); + } else { + (*profile)->SetProfileTrustList(notExitBunldleList); + profile++; + } + name.clear(); + profileId = -1; + } + + for (auto profile = profiles_.begin(); profile != profiles_.end(); profile++) { + ANS_LOGI("Clone queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), + (*profile)->GetProfileTrustList().size()); + } + ANS_LOGI("Notification disturb profile list on restore end."); + })); +} + +void NotificationCloneDisturb::GetProfileUid(int32_t userId, std::map& uidMap, + std::vector trustList, std::vector& exitBunldleList, + std::vector& notExitBunldleList) +{ + // get application uid with bundle name and appindex. + for (auto& bundle : trustList) { + std::string key = bundle.GetBundleName() + std::to_string(bundle.GetAppIndex()); + if (uidMap.find(key) != uidMap.end()) { + bundle.SetUid(uidMap[key]); + } else { + int32_t uid = NotificationCloneUtil::GetBundleUid(bundle.GetBundleName(), userId, bundle.GetAppIndex()); + ANS_LOGW("Notification get uid %{public}d %{public}d %{public}s.", uid, bundle.GetAppIndex(), + bundle.GetBundleName().c_str()); + bundle.SetUid(uid); + uidMap[key] = uid; + } + if (bundle.GetUid() == -1) { + notExitBunldleList.push_back(bundle); + } else { + exitBunldleList.push_back(bundle); + } + } +} + +void NotificationCloneDisturb::OnBundleDataAdd(const sptr &bundleOption) +{ + HandlerBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneDisturb::OnBundleDataUpdate(const sptr &bundleOption) +{ + HandlerBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneDisturb::OnUserSwitch(int32_t userId) +{ + ANS_LOGI("Handler user switch %{public}d", userId); + if (cloneDisturbQueue_ == nullptr) { + ANS_LOGW("Clone disturb queue is null."); + return; + } + cloneDisturbQueue_->submit_h(std::bind([&]() { + profiles_.clear(); + })); +} + +void NotificationCloneDisturb::HandlerBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid) +{ + ANS_LOGI("Handler bundle event %{public}s %{public}d %{public}d %{public}zu.", + bundleName.c_str(), appIndex, uid, profiles_.size()); + if (profiles_.empty()) { + return; + } + + int32_t userId = NotificationCloneUtil::GetActiveUserId(); + NotificationBundleOption bundle(bundleName, uid); + bundle.SetAppIndex(appIndex); + if (cloneDisturbQueue_ == nullptr) { + ANS_LOGW("Clone disturb queue is null."); + return; + } + cloneDisturbQueue_->submit_h(std::bind([&, bundle, userId]() { + int32_t profileId = -1; + std::string name; + for (auto profile = profiles_.begin(); profile != profiles_.end();) { + name = (*profile)->GetProfileName(); + profileId = (*profile)->GetProfileId(); + std::vector bundleList; + auto trustList = (*profile)->GetProfileTrustList(); + CheckBundleInfo(trustList, bundleList, bundle); + NotificationPreferences::GetInstance()->UpdateDoNotDisturbProfiles(userId, + profileId, name, bundleList); + if (trustList.empty()) { + profile = profiles_.erase(profile); + } else { + (*profile)->SetProfileTrustList(trustList); + profile++; + } + name.clear(); + profileId = -1; + } + for (auto profile = profiles_.begin(); profile != profiles_.end(); profile++) { + ANS_LOGI("Event queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), + (*profile)->GetProfileTrustList().size()); + } + })); +} + +void NotificationCloneDisturb::CheckBundleInfo(std::vector& trustList, + std::vector& bundleList, const NotificationBundleOption& bundle) +{ + for (auto bundleItem = trustList.begin(); bundleItem != trustList.end(); bundleItem++) { + if (bundleItem->GetBundleName() == bundle.GetBundleName() && + bundleItem->GetAppIndex() == bundle.GetAppIndex()) { + bundleList.push_back(bundle); + trustList.erase(bundleItem); + break; + } + } +} +} +} diff --git a/services/ans/src/clone/notification_clone_manager.cpp b/services/ans/src/clone/notification_clone_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae65acf2b34065f235c36420911fd5fe30eb4817 --- /dev/null +++ b/services/ans/src/clone/notification_clone_manager.cpp @@ -0,0 +1,189 @@ +/* +* Copyright (c) 2021-2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "notification_clone_manager.h" + +#include +#include +#include +#include +#include +#include + +#include "ans_log_wrapper.h" +#include "nlohmann/json.hpp" +#include "notification_clone_disturb_service.h" +#include "notification_clone_bundle_service.h" + +namespace OHOS { +namespace Notification { + +const int ANS_CLONE_ERROR = -1; +constexpr const char *CLONE_ITEM_BUNDLE_INFO = "notificationBundle"; +constexpr const char *CLONE_ITEM_DISTURB = "notificationDisturb"; +constexpr const char *BACKUP_CONFIG_FILE_PATH = "/data/service/el1/public/notification/backup_config.conf"; + +NotificationCloneManager& NotificationCloneManager::GetInstance() +{ + static NotificationCloneManager notificationCloneManager; + return notificationCloneManager; +} + +int32_t NotificationCloneManager::OnBackup(MessageParcel& data, MessageParcel& reply) +{ + if (cloneTemplates.empty()) { + ANS_LOGI("Notification no need Backup."); + return ERR_OK; + } + + nlohmann::json jsonObject; + for (auto iter = cloneTemplates.begin(); iter != cloneTemplates.end(); ++iter) { + nlohmann::json jsonItem; + auto cloneTemplate = iter->second; + if (cloneTemplate == nullptr) { + ANS_LOGW("Notification OnBackup %{public}s funtion is null.", iter->first.c_str()); + continue; + } + if (iter->second->OnBackup(jsonItem) != ERR_OK) { + ANS_LOGW("Notification OnBackup %{public}s failed.", iter->first.c_str()); + continue; + } + jsonObject[iter->first] = jsonItem; + } + + if (SaveConfig(jsonObject.dump()) != ERR_OK) { + return ANS_CLONE_ERROR; + } + + UniqueFd fd = UniqueFd(open(BACKUP_CONFIG_FILE_PATH, O_RDONLY)); + if (fd.Get() < 0) { + ANS_LOGW("Notification open file failed."); + return ANS_CLONE_ERROR; + } + + if (reply.WriteFileDescriptor(fd) == false) { + close(fd.Release()); + ANS_LOGW("Notification write file descriptor failed!"); + return ANS_CLONE_ERROR; + } + + ANS_LOGI("Notification OnBackup end fd: %{public}d.", fd.Get()); + close(fd.Release()); + return ERR_OK; +} + +int32_t NotificationCloneManager::OnRestore(MessageParcel& data, MessageParcel& reply) +{ + std::string storeMessage; + UniqueFd fd(data.ReadFileDescriptor()); + if (LoadConfig(fd, storeMessage) != ERR_OK) { + close(fd.Release()); + RemoveBackUpFile(); + return ANS_CLONE_ERROR; + } + + RemoveBackUpFile(); + nlohmann::json jsonObject = nlohmann::json::parse(storeMessage, nullptr, false); + if (jsonObject.is_null() || !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return ANS_CLONE_ERROR; + } + for (auto iter = cloneTemplates.begin(); iter != cloneTemplates.end(); ++iter) { + if (jsonObject.contains(iter->first) && iter->second != nullptr) { + iter->second->OnRestore(jsonObject.at(iter->first)); + } + } + return ERR_OK; +} + +NotificationCloneManager::NotificationCloneManager() +{ + ANS_LOGI("Notification clone manager init."); + cloneTemplates.insert_or_assign(CLONE_ITEM_BUNDLE_INFO, NotificationCloneBundle::GetInstance()); + cloneTemplates.insert_or_assign(CLONE_ITEM_DISTURB, NotificationCloneDisturb::GetInstance()); +} + +NotificationCloneManager::~NotificationCloneManager() +{ + ANS_LOGI("Notification clone manager destory."); +} + +ErrCode NotificationCloneManager::LoadConfig(UniqueFd &fd, std::string& config) +{ + ANS_LOGI("Load notification config."); + struct stat statBuf; + if (fstat(fd.Get(), &statBuf) < 0) { + ANS_LOGW("LoadConfig fstat fd fail %{public}d.", fd.Get()); + return ANS_CLONE_ERROR; + } + int destFd = open(BACKUP_CONFIG_FILE_PATH, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); + if (destFd < 0) { + ANS_LOGW("LoadConfig open file fail."); + return ANS_CLONE_ERROR; + } + if (sendfile(destFd, fd.Get(), nullptr, statBuf.st_size) < 0) { + ANS_LOGW("LoadConfig fd sendfile(size: %{public}d) to destFd fail.", static_cast(statBuf.st_size)); + close(destFd); + return ANS_CLONE_ERROR; + } + close(destFd); + std::ifstream fs(BACKUP_CONFIG_FILE_PATH); + if (!fs.is_open()) { + ANS_LOGW("Loading config file%{public}s is_open() failed!", BACKUP_CONFIG_FILE_PATH); + return ANS_CLONE_ERROR; + } + config.clear(); + std::string line; + while (std::getline(fs, line)) { + config.append(line); + } + fs.close(); + return ERR_OK; +} + +ErrCode NotificationCloneManager::SaveConfig(const std::string& config) +{ + ANS_LOGD("Save config file %{public}s", config.c_str()); + RemoveBackUpFile(); + FILE* fp = fopen(BACKUP_CONFIG_FILE_PATH, "w"); + if (!fp) { + ANS_LOGW("Save config file: %{public}s, fopen() failed!", BACKUP_CONFIG_FILE_PATH); + return ANS_CLONE_ERROR; + } + + int ret = fwrite(config.c_str(), 1, config.length(), fp); + if (ret != (int)config.length()) { + ANS_LOGW("Save config file: %{public}s, fwrite %{public}d failed!", BACKUP_CONFIG_FILE_PATH, ret); + } + (void)fflush(fp); + (void)fsync(fileno(fp)); + (void)fclose(fp); + ANS_LOGI("Save config file %{public}zu", config.size()); + return ERR_OK; +} + +void NotificationCloneManager::RemoveBackUpFile() +{ + remove(BACKUP_CONFIG_FILE_PATH); +} + +void NotificationCloneManager::OnUserSwitch(int32_t userId) +{ + for (auto iter = cloneTemplates.begin(); iter != cloneTemplates.end(); ++iter) { + iter->second->OnUserSwitch(userId); + } +} +} +} diff --git a/services/ans/src/clone/notification_clone_util.cpp b/services/ans/src/clone/notification_clone_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38590b55d87f0f60baaf9757f74e1a563e07d264 --- /dev/null +++ b/services/ans/src/clone/notification_clone_util.cpp @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2024-2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "notification_clone_util.h" + +#include "bundle_manager_helper.h" +#include "os_account_manager.h" +#include "os_account_manager_helper.h" + +namespace OHOS { +namespace Notification { + +constexpr int32_t MAIN_USER_ID = 100; +int32_t NotificationCloneUtil::GetActiveUserId() +{ + int32_t userId = MAIN_USER_ID; + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId); + return userId; +} + +int32_t NotificationCloneUtil::GetBundleUid(const std::string bundleName, int32_t userId, int32_t appIndex) +{ + if (appIndex == -1) { + return BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId); + } + return BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId, appIndex); +} +} +} diff --git a/services/ans/src/common/aes_gcm_helper.cpp b/services/ans/src/common/aes_gcm_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05ba3e53939ef28d03ed46879014c8f5001f585e --- /dev/null +++ b/services/ans/src/common/aes_gcm_helper.cpp @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "openssl/evp.h" +#include "openssl/rand.h" + +#include "aes_gcm_helper.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { + static const uint32_t G_AES_GCM_KEY_LEN{32}; +static const uint32_t G_AES_GCM_IV_LEN{12}; +static const uint32_t G_AES_GCM_TAG_LEN{16}; +static const std::string G_DIR_PATH{"/data/service/el1/public/database/notification_service/keyfile"}; +static const std::string G_KEY_PATH{"/data/service/el1/public/database/notification_service"}; +static const int STEP = 2; +static const int OFFSET = 4; +static const int HEX_OF_A = 10; +static const int WIDTH_PER_BYTE = 2; +static inline std::mutex g_generateKeyMutex{}; + +std::string AesGcmHelper::Byte2Hex(const std::string &bytes) +{ + std::ostringstream oss; + for (const unsigned char byte : bytes) { + oss << std::hex << std::setw(WIDTH_PER_BYTE) << std::setfill('0') << static_cast(byte); + } + return oss.str(); +} + +unsigned char AesGcmHelper::HexChar2Byte(const char &hexCh) +{ + if (hexCh >= '0' && hexCh <= '9') { + return hexCh - '0'; + } else if (hexCh >= 'A' && hexCh <= 'F') { + return hexCh - 'A' + HEX_OF_A; + } else if (hexCh >= 'a' && hexCh <= 'f') { + return hexCh - 'a' + HEX_OF_A; + } else { + ANS_LOGE("Invalid hex char: %{public}c.", hexCh); + return 0; + } +} + +std::string AesGcmHelper::Hex2Byte(const std::string &hex) +{ + if (hex.length() % STEP != 0) { + ANS_LOGE("Length of hex is not even."); + return 0; + } + std::string bytes; + for (int i = 0; i < static_cast(hex.length()); i += STEP) { + unsigned char high = HexChar2Byte(hex[i]); + unsigned char low = HexChar2Byte(hex[i + 1]); + bytes.push_back(static_cast((high << OFFSET) | low)); + } + return bytes; +} + +bool AesGcmHelper::GenerateKey(std::string &key) +{ + std::lock_guard lck(g_generateKeyMutex); + const char *keyPathPtr = G_KEY_PATH.c_str(); + char *resolvedPath = (char *)malloc(PATH_MAX); + if (resolvedPath != nullptr) { + if (realpath(keyPathPtr, resolvedPath) == NULL) { + free(resolvedPath); + ANS_LOGE("Fail to resolve the key path"); + return false; + } + free(resolvedPath); + } + std::string keyDir = G_DIR_PATH; + const char *fileNamePtr = keyDir.c_str(); + std::filesystem::path keyPath(keyDir); + if (std::filesystem::exists(keyPath)) { + std::ifstream keyFile(keyDir); + if (keyFile.is_open()) { + std::string keyHex; + std::getline(keyFile, keyHex); + key = Hex2Byte(keyHex); + keyFile.close(); + return true; + } + } + unsigned char aes_key[G_AES_GCM_KEY_LEN]; + if (!RAND_bytes(aes_key, G_AES_GCM_KEY_LEN)) { + ANS_LOGE("Fail to randomly generate the key"); + return false; + } + key = std::string(reinterpret_cast(aes_key), G_AES_GCM_KEY_LEN); + std::string keyHex = Byte2Hex(key); + if (!std::filesystem::exists(keyPath.parent_path())) { + ANS_LOGE("Fail to save the key"); + return false; + } + std::ofstream keyFile(keyDir); + if (keyFile.is_open()) { + keyFile << keyHex; + keyFile.close(); + ANS_LOGI("Generate new key."); + } else { + ANS_LOGE("Fail to save the key"); + return false; + } + return true; +} + +ErrCode AesGcmHelper::Encrypt(const std::string &plainText, std::string &cipherText) +{ + if (plainText.empty()) { + ANS_LOGE("Can't encrypt empty plain text."); + return ERR_ANS_INVALID_PARAM; + } + std::string key{""}; + bool ret = GenerateKey(key); + if (!ret) { + ANS_LOGE("Fail to get key while encrypting."); + return ERR_ANS_ENCRYPT_FAIL; + } + ret = EncryptAesGcm(plainText, cipherText, key); + if (!ret) { + ANS_LOGE("Fail to encrypt with AES-GCM."); + return ERR_ANS_ENCRYPT_FAIL; + } + return ERR_OK; +} + +ErrCode AesGcmHelper::Decrypt(std::string &plainText, const std::string &cipherText) +{ + if (cipherText.empty()) { + ANS_LOGE("Can't decrypt empty cipher text."); + return ERR_ANS_INVALID_PARAM; + } + std::string key{""}; + bool ret = GenerateKey(key); + if (!ret) { + ANS_LOGE("Fail to get key while decrypting"); + return ERR_ANS_DECRYPT_FAIL; + } + ret = DecryptAesGcm(plainText, cipherText, key); + if (!ret) { + ANS_LOGE("Fail to decrypt with AES-GCM."); + return ERR_ANS_DECRYPT_FAIL; + } + return ERR_OK; +} + +bool AesGcmHelper::EncryptAesGcm(const std::string &plainText, std::string &cipherText, std::string &key) +{ + const unsigned int bufferLen = plainText.size(); + std::vector buffer(bufferLen); + std::vector iv(G_AES_GCM_IV_LEN); + std::vector tag(G_AES_GCM_TAG_LEN); + EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + if (!ctx) { + ANS_LOGE("EncryptAesGcm ctx error"); + return false; + } + bool ret = true; + do { + if (!RAND_bytes(iv.data(), G_AES_GCM_IV_LEN)) { + ANS_LOGE("EncryptAesGcm RAND_bytes error"); + ret = false; + break; + } + if (!EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, + reinterpret_cast(key.data()), iv.data())) { + ANS_LOGE("EncryptAesGcm EVP_EncryptInit_ex error"); + ret = false; + break; + } + int len; + if (!EVP_EncryptUpdate(ctx, buffer.data(), &len, + reinterpret_cast(plainText.data()), bufferLen)) { + ANS_LOGE("EncryptAesGcm EVP_EncryptUpdate error"); + ret = false; + break; + } + if (!EVP_EncryptFinal_ex(ctx, buffer.data() + len, &len)) { + ANS_LOGE("EncryptAesGcm EVP_EncryptFinal_ex error"); + ret = false; + break; + } + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, G_AES_GCM_TAG_LEN, tag.data())) { + ANS_LOGE("EncryptAesGcm EVP_CIPHER_CTX_ctrl error"); + ret = false; + break; + } + cipherText = std::string(iv.begin(), iv.end()); + cipherText += std::string(buffer.begin(), buffer.end()); + cipherText += std::string(tag.begin(), tag.end()); + cipherText = Byte2Hex(cipherText); + } while (0); + EVP_CIPHER_CTX_free(ctx); + return ret; +} + +bool AesGcmHelper::DecryptAesGcm(std::string &plainText, const std::string &cipherText, std::string &key) +{ + const unsigned int bufferLen = cipherText.size() - G_AES_GCM_IV_LEN - G_AES_GCM_TAG_LEN; + std::vector buffer(bufferLen); + std::vector iv(G_AES_GCM_IV_LEN); + std::vector cipherByte(bufferLen); + std::vector tag(G_AES_GCM_TAG_LEN); + std::string cipherBytes = Hex2Byte(cipherText); + iv.assign(cipherBytes.begin(), cipherBytes.begin() + G_AES_GCM_IV_LEN); + cipherByte.assign(cipherBytes.begin() + G_AES_GCM_IV_LEN, cipherBytes.end() - G_AES_GCM_TAG_LEN); + tag.assign(cipherBytes.end() - G_AES_GCM_TAG_LEN, cipherBytes.end()); + EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + if (!ctx) { + ANS_LOGE("DecryptAesGcm ctx error"); + return false; + } + bool ret = true; + do { + if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, + reinterpret_cast(key.data()), iv.data())) { + ANS_LOGE("DecryptAesGcm EVP_DecryptInit_ex error"); + ret = false; + break; + } + int len; + if (!EVP_DecryptUpdate(ctx, buffer.data(), &len, cipherByte.data(), cipherByte.size())) { + ANS_LOGE("DecryptAesGcm EVP_DecryptUpdate error"); + ret = false; + break; + } + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, G_AES_GCM_TAG_LEN, tag.data())) { + ANS_LOGE("DecryptAesGcm EVP_CIPHER_CTX_ctrl error"); + ret = false; + break; + } + if (EVP_DecryptFinal_ex(ctx, buffer.data() + len, &len) <= 0) { + ANS_LOGE("DecryptAesGcm EVP_DecryptFinal_ex error"); + ret = false; + break; + } + plainText = std::string(buffer.begin(), buffer.end()); + } while (0); + EVP_CIPHER_CTX_free(ctx); + return ret; +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/common/file_utils.cpp b/services/ans/src/common/file_utils.cpp index e6cdd327ada293038f28dc9e85f6d9cd29bb4e31..c122deac90840cbb14ded709da28115cf1b48c24 100644 --- a/services/ans/src/common/file_utils.cpp +++ b/services/ans/src/common/file_utils.cpp @@ -63,7 +63,7 @@ bool FileUtils::GetJsonFromFile(const char *path, nlohmann::json &root) { std::ifstream file(path); root = nlohmann::json::parse(file); - if (root.is_null() || root.empty()) { + if (root.is_null() || root.empty() || !root.is_object()) { ANS_LOGE("GetJsonFromFile fail as invalid root."); return false; } diff --git a/services/ans/src/common/notification_analytics_util.cpp b/services/ans/src/common/notification_analytics_util.cpp index a1948cebe5be388ba0409b420f35f176408436e2..5f9f2f0c9342b1fb620620bc0200730548159525 100644 --- a/services/ans/src/common/notification_analytics_util.cpp +++ b/services/ans/src/common/notification_analytics_util.cpp @@ -23,13 +23,38 @@ #include "ans_convert_enum.h" #include "ans_permission_def.h" #include "in_process_call_wrapper.h" +#include "report_timer_info.h" +#include "time_service_client.h" +#include "nlohmann/json.hpp" +#include "bundle_manager_helper.h" namespace OHOS { namespace Notification { constexpr char MESSAGE_DELIMITER = '#'; constexpr const int32_t PUBLISH_ERROR_EVENT_CODE = 0; constexpr const int32_t DELETE_ERROR_EVENT_CODE = 5; constexpr const int32_t MODIFY_ERROR_EVENT_CODE = 6; + +constexpr const int32_t DEFAULT_ERROR_EVENT_COUNT = 5; +constexpr const int32_t DEFAULT_ERROR_EVENT_TIME = 60; +constexpr const int32_t MODIFY_ERROR_EVENT_COUNT = 6; +constexpr const int32_t MODIFY_ERROR_EVENT_TIME = 60; + +constexpr const int32_t REPORT_CACHE_MAX_SIZE = 50; +constexpr const int32_t REPORT_CACHE_INTERVAL_TIME = 30; +constexpr const int32_t REASON_MAX_LENGTH = 127; const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT"; +static std::mutex reportFlowControlMutex_; +static std::map> flowControlTimestampMap_ = { + {MODIFY_ERROR_EVENT_CODE, {}}, + {PUBLISH_ERROR_EVENT_CODE, {}}, + {DELETE_ERROR_EVENT_CODE, {}}, +}; + +static std::mutex reportCacheMutex_; +static uint64_t reportTimerId = 0; +static std::list reportCacheList; +static bool g_reportFlag = false; +static std::shared_ptr reportTimeInfo = std::make_shared(); HaMetaMessage::HaMetaMessage(uint32_t sceneId, uint32_t branchId) : sceneId_(sceneId), branchId_(branchId) @@ -71,6 +96,11 @@ HaMetaMessage& HaMetaMessage::Message(const std::string& message, bool print) return *this; } +HaMetaMessage& HaMetaMessage::Append(const std::string& message) +{ + message_+=message; + return *this; +} HaMetaMessage& HaMetaMessage::Checkfailed(bool checkfailed) { checkfailed_ = checkfailed; @@ -108,7 +138,7 @@ std::string HaMetaMessage::GetMessage() const HaMetaMessage& HaMetaMessage::SlotType(int32_t slotType) { - slotType_ = slotType; + slotType_ = static_cast(slotType); return *this; } @@ -139,7 +169,6 @@ void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const sptr& request, @@ -149,8 +178,16 @@ void NotificationAnalyticsUtil::CommonNotificationEvent(const sptr& request, EventFwk::Want want, int32_t eventCode, const std::string& reason) { - std::shared_ptr extraInfo = std::make_shared(); - if (request->GetFlags() == nullptr) { - extraInfo->SetParam("reason", AAFwk::String::Box(reason)); - } else { - std::string reasons = reason + std::to_string(request->GetFlags()->GetReminderFlags()); - extraInfo->SetParam("reason", AAFwk::String::Box(reasons)); - } - AAFwk::WantParamWrapper wWrapper(*extraInfo); - std::string extraContent = wWrapper.ToString(); - NotificationNapi::SlotType slotType; + NotificationNapi::AnsEnumUtil::SlotTypeCToJS( + static_cast(request->GetSlotType()), slotType); NotificationNapi::ContentType contentType; NotificationNapi::AnsEnumUtil::ContentTypeCToJS( static_cast(request->GetNotificationType()), contentType); - NotificationNapi::AnsEnumUtil::SlotTypeCToJS( - static_cast(request->GetSlotType()), slotType); want.SetParam("id", request->GetNotificationId()); + want.SetParam("uid", request->GetOwnerUid()); want.SetParam("slotType", static_cast(slotType)); want.SetParam("contentType", std::to_string(static_cast(contentType))); - want.SetParam("extraInfo", extraContent); + if (!request->GetCreatorBundleName().empty()) { - want.SetBundle(request->GetCreatorBundleName()); + want.SetParam("agentBundleName", request->GetCreatorBundleName()); } if (!request->GetOwnerBundleName().empty()) { - want.SetParam("agentBundleName", request->GetOwnerBundleName()); - } - want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT); - EventFwk::CommonEventPublishInfo publishInfo; - publishInfo.SetSubscriberPermissions({OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER}); - EventFwk::CommonEventData commonData {want, eventCode, ""}; - ANS_LOGD("Publish event success %{public}d, %{public}s", eventCode, reason.c_str()); - if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData, publishInfo)) { - ANS_LOGE("Publish event failed %{public}d, %{public}s", eventCode, reason.c_str()); + want.SetBundle(request->GetOwnerBundleName()); } + IN_PROCESS_CALL_WITHOUT_RET(AddListCache(want, eventCode)); } void NotificationAnalyticsUtil::ReportModifyEvent(const HaMetaMessage& message) { - std::shared_ptr extraInfo = std::make_shared(); - std::string reason = std::to_string(message.sceneId_) + MESSAGE_DELIMITER + - std::to_string(message.branchId_) + MESSAGE_DELIMITER + message.GetMessage(); - extraInfo->SetParam("reason", AAFwk::String::Box(reason)); - AAFwk::WantParamWrapper wWrapper(*extraInfo); - std::string extraContent = wWrapper.ToString(); - + if (!ReportFlowControl(MODIFY_ERROR_EVENT_CODE)) { + ANS_LOGI("Publish event failed, reason:%{public}s", message.Build().c_str()); + return; + } EventFwk::Want want; - want.SetBundle(message.bundleName_); + std::string extraInfo = NotificationAnalyticsUtil::BuildExtraInfo(message); + NotificationAnalyticsUtil::SetCommonWant(want, message, extraInfo); + + std::string bundle; + int32_t callingUid = IPCSkeleton::GetCallingUid(); + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager != nullptr) { + bundle = bundleManager->GetBundleNameByUid(callingUid); + } + want.SetBundle(bundle + "_" + std::to_string(callingUid)); want.SetParam("slotType", static_cast(message.slotType_)); - want.SetParam("extraInfo", extraContent); - IN_PROCESS_CALL_WITHOUT_RET(ReportNotificationEvent(want, MODIFY_ERROR_EVENT_CODE, - message.Build())); + IN_PROCESS_CALL_WITHOUT_RET(AddListCache(want, MODIFY_ERROR_EVENT_CODE)); } void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const HaMetaMessage& message) { - std::shared_ptr extraInfo = std::make_shared(); - std::string reason = message.Build(); - extraInfo->SetParam("reason", AAFwk::String::Box(reason)); - AAFwk::WantParamWrapper wWrapper(*extraInfo); - std::string extraContent = wWrapper.ToString(); - + if (!ReportFlowControl(DELETE_ERROR_EVENT_CODE)) { + ANS_LOGI("Publish event failed, reason:%{public}s", message.Build().c_str()); + return; + } EventFwk::Want want; + std::string extraInfo = NotificationAnalyticsUtil::BuildExtraInfo(message); + NotificationAnalyticsUtil::SetCommonWant(want, message, extraInfo); + want.SetParam("agentBundleName", message.agentBundleName_); - want.SetBundle(message.bundleName_); want.SetParam("typeCode", message.typeCode_); want.SetParam("id", message.notificationId_); - want.SetParam("extraInfo", extraContent); - IN_PROCESS_CALL_WITHOUT_RET(ReportNotificationEvent( - want, DELETE_ERROR_EVENT_CODE, message.Build())); + + IN_PROCESS_CALL_WITHOUT_RET(AddListCache(want, DELETE_ERROR_EVENT_CODE)); } void NotificationAnalyticsUtil::ReportNotificationEvent(EventFwk::Want want, int32_t eventCode, const std::string& reason) { - want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT); EventFwk::CommonEventPublishInfo publishInfo; publishInfo.SetSubscriberPermissions({OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER}); EventFwk::CommonEventData commonData {want, eventCode, ""}; @@ -242,5 +265,220 @@ void NotificationAnalyticsUtil::ReportNotificationEvent(EventFwk::Want want, ANS_LOGE("Publish event failed %{public}d, %{public}s", eventCode, reason.c_str()); } } + +bool NotificationAnalyticsUtil::ReportFlowControl(const int32_t reportType) +{ + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + std::lock_guard lock(reportFlowControlMutex_); + auto iter = flowControlTimestampMap_.find(reportType); + if (iter == flowControlTimestampMap_.end()) { + return false; + } + auto& list = iter->second; + FlowControllerOption option = GetFlowOptionByType(reportType); + RemoveExpired(list, now, option.time); + int32_t size = list.size(); + int32_t count = option.count; + if (size >= count) { + return false; + } + list.push_back(now); + return true; +} + +void NotificationAnalyticsUtil::RemoveExpired(std::list &list, + const std::chrono::system_clock::time_point &now, int32_t time) +{ + auto iter = list.begin(); + while (iter != list.end()) { + if (abs(now - *iter) > std::chrono::seconds(time)) { + iter = list.erase(iter); + } else { + break; + } + } +} + +FlowControllerOption NotificationAnalyticsUtil::GetFlowOptionByType(const int32_t reportType) +{ + FlowControllerOption option; + switch (reportType) { + case MODIFY_ERROR_EVENT_CODE: + option.count = MODIFY_ERROR_EVENT_COUNT; + option.time = MODIFY_ERROR_EVENT_TIME; + break; + default: + option.count = DEFAULT_ERROR_EVENT_COUNT; + option.time = DEFAULT_ERROR_EVENT_TIME; + break; + } + return option; +} + +std::string NotificationAnalyticsUtil::BuildExtraInfo(const HaMetaMessage& message) +{ + nlohmann::json reason; + reason["scene"] = message.sceneId_; + reason["branch"] = message.branchId_; + reason["innerErr"] = message.errorCode_; + reason["detail"] = message.message_; + + auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + reason["time"] = now; + + std::shared_ptr extraInfo = std::make_shared(); + + reason["detail"] = ""; + int32_t reasonFixedSize = + static_cast(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace).size()); + int32_t leftSpace = REASON_MAX_LENGTH - reasonFixedSize; + if (leftSpace < 0) { + std::string basicInfo = std::to_string(message.sceneId_) + MESSAGE_DELIMITER + + std::to_string(message.branchId_) + MESSAGE_DELIMITER + + std::to_string(message.errorCode_) + MESSAGE_DELIMITER + + std::to_string(now) + " Reason fixed size exceeds limit"; + extraInfo->SetParam("reason", AAFwk::String::Box(basicInfo)); + ANS_LOGI("%{public}s", basicInfo.c_str()); + } else { + reason["detail"] = message.message_.substr(0, leftSpace); + extraInfo->SetParam("reason", + AAFwk::String::Box(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace))); + } + + AAFwk::WantParamWrapper wWrapper(*extraInfo); + + return wWrapper.ToString(); +} + +std::string NotificationAnalyticsUtil::BuildExtraInfoWithReq(const HaMetaMessage& message, + const sptr& request) +{ + NotificationNapi::ContentType contentType; + NotificationNapi::AnsEnumUtil::ContentTypeCToJS( + static_cast(request->GetNotificationType()), contentType); + nlohmann::json reason; + if (contentType == NotificationNapi::ContentType::NOTIFICATION_CONTENT_LIVE_VIEW) { + auto content = request->GetContent()->GetNotificationContent(); + auto liveViewContent = std::static_pointer_cast(content); + reason["status"] = static_cast(liveViewContent->GetLiveViewStatus()); + } + + reason["scene"] = message.sceneId_; + reason["branch"] = message.branchId_; + reason["innerErr"] = message.errorCode_; + reason["detail"] = message.message_; + + auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + reason["time"] = now; + + std::shared_ptr extraInfo = nullptr; + if (request->GetUnifiedGroupInfo() != nullptr && + request->GetUnifiedGroupInfo()->GetExtraInfo() != nullptr) { + extraInfo = request->GetUnifiedGroupInfo()->GetExtraInfo(); + } else { + extraInfo = std::make_shared(); + } + + reason["detail"] = ""; + int32_t reasonFixedSize = + static_cast(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace).size()); + int32_t leftSpace = REASON_MAX_LENGTH - reasonFixedSize; + if (leftSpace < 0) { + std::string basicInfo = std::to_string(message.sceneId_) + MESSAGE_DELIMITER + + std::to_string(message.branchId_) + MESSAGE_DELIMITER + + std::to_string(message.errorCode_) + MESSAGE_DELIMITER + + std::to_string(now) + " Reason fixed size exceeds limit"; + extraInfo->SetParam("reason", AAFwk::String::Box(basicInfo)); + ANS_LOGI("%{public}s", basicInfo.c_str()); + } else { + reason["detail"] = message.message_.substr(0, leftSpace); + extraInfo->SetParam("reason", + AAFwk::String::Box(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace))); + } + + AAFwk::WantParamWrapper wWrapper(*extraInfo); + + return wWrapper.ToString(); +} + +void NotificationAnalyticsUtil::SetCommonWant(EventFwk::Want& want, const HaMetaMessage& message, + std::string& extraInfo) +{ + want.SetBundle(message.bundleName_); + want.SetParam("extraInfo", extraInfo); + want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT); +} + +void NotificationAnalyticsUtil::AddListCache(EventFwk::Want& want, int32_t eventCode) +{ + std::lock_guard lock(reportCacheMutex_); + int32_t size = static_cast(reportCacheList.size()); + if (size >= REPORT_CACHE_MAX_SIZE) { + ANS_LOGW("list size is max"); + return; + } + + if (reportTimerId == 0) { + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr) { + ANS_LOGE("Failed to start timer due to get TimeServiceClient is null."); + return; + } + reportTimerId = timer->CreateTimer(reportTimeInfo); + } + + ReportCache reportCache; + reportCache.want = want; + reportCache.eventCode = eventCode; + reportCacheList.push_back(reportCache); + if (!g_reportFlag) { + ExecuteCacheList(); + } +} + +void NotificationAnalyticsUtil::ExecuteCacheList() +{ + if (reportCacheList.empty()) { + g_reportFlag = false; + ANS_LOGI("reportCacheList is end"); + return; + } + auto reportCache = reportCacheList.front(); + ReportCommonEvent(reportCache); + auto triggerFunc = [] { + std::lock_guard lock(reportCacheMutex_); + NotificationAnalyticsUtil::ExecuteCacheList(); + }; + reportCacheList.pop_front(); + reportTimeInfo->SetCallbackInfo(triggerFunc); + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr || reportTimerId == 0) { + g_reportFlag = false; + ANS_LOGE("Failed to start timer due to get TimeServiceClient is null."); + return; + } + timer->StartTimer(reportTimerId, NotificationAnalyticsUtil::GetCurrentTime() + + REPORT_CACHE_INTERVAL_TIME * NotificationConstant::SECOND_TO_MS); + g_reportFlag = true; +} + +void NotificationAnalyticsUtil::ReportCommonEvent(const ReportCache& reportCache) +{ + EventFwk::CommonEventPublishInfo publishInfo; + publishInfo.SetSubscriberPermissions({OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER}); + EventFwk::CommonEventData commonData {reportCache.want, reportCache.eventCode, ""}; + if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData, publishInfo)) { + ANS_LOGE("Publish event failed %{public}d", reportCache.eventCode); + } +} + +int64_t NotificationAnalyticsUtil::GetCurrentTime() +{ + auto now = std::chrono::system_clock::now(); + auto duration = std::chrono::duration_cast(now.time_since_epoch()); + return duration.count(); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/common/notification_config_parse.cpp b/services/ans/src/common/notification_config_parse.cpp index 1bf1ce77c62da82b80c45d157e5ce935135faa9b..3804b084e97c57ef5d6b510ad23a6a06dec6a921 100644 --- a/services/ans/src/common/notification_config_parse.cpp +++ b/services/ans/src/common/notification_config_parse.cpp @@ -18,6 +18,7 @@ #include "notification_config_parse.h" #include "ans_log_wrapper.h" +#include "notification_trust_list.h" #include "notification_slot.h" #include "file_utils.h" @@ -133,5 +134,52 @@ uint32_t NotificationConfigParse::GetConfigSlotReminderModeByType(NotificationCo return 0; } + +uint32_t NotificationConfigParse::GetConfigSlotReminderModeByType(NotificationConstant::SlotType slotType, + const sptr &bundleOption) const +{ + uint32_t reminderFlags = GetConfigSlotReminderModeByType(slotType); + if (DelayedSingleton::GetInstance()->IsSlotFlagsTrustlistAsBundle(bundleOption)) { + return reminderFlags & 0b111111; + } + return reminderFlags; +} + +void NotificationConfigParse::GetFlowCtrlConfigFromCCM(FlowControlThreshold &threshold) +{ + nlohmann::json root; + std::string JsonPoint = "/"; + JsonPoint.append(CFG_KEY_NOTIFICATION_SERVICE); + if (!GetConfigJson(JsonPoint, root)) { + ANS_LOGE("Failed to get JsonPoint CCM config file"); + return; + } + if (!root.contains(CFG_KEY_NOTIFICATION_SERVICE)) { + ANS_LOGW("GetFlowCtrlConfigFromCCM not found jsonKey"); + return; + } + nlohmann::json affects = root[CFG_KEY_NOTIFICATION_SERVICE]; + if (affects.is_null() || affects.empty()) { + ANS_LOGE("GetFlowCtrlConfigFromCCM failed as invalid ccmFlowCtrlConfig json"); + return; + } + if (affects.contains(CFG_KEY_MAX_CREATE_NUM_PERSECOND)) { + threshold.maxCreateNumPerSecond = affects[CFG_KEY_MAX_CREATE_NUM_PERSECOND]; + } + + if (affects.contains(CFG_KEY_MAX_UPDATE_NUM_PERSECOND)) { + threshold.maxUpdateNumPerSecond = affects[CFG_KEY_MAX_UPDATE_NUM_PERSECOND]; + } + + if (affects.contains(CFG_KEY_MAX_CREATE_NUM_PERSECOND_PERAPP)) { + threshold.maxCreateNumPerSecondPerApp = affects[CFG_KEY_MAX_CREATE_NUM_PERSECOND_PERAPP]; + } + + if (affects.contains(CFG_KEY_MAX_UPDATE_NUM_PERSECOND_PERAPP)) { + threshold.maxUpdateNumPerSecondPerApp = affects[CFG_KEY_MAX_UPDATE_NUM_PERSECOND_PERAPP]; + } + + ANS_LOGI("GetFlowCtrlConfigFromCCM success"); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_dialog.cpp b/services/ans/src/notification_dialog.cpp index 1198bf819e26d7e161858e4103b6c38ea823aab3..8b635cf9f1112fcf978d5d55f6f5d89b59519d9b 100644 --- a/services/ans/src/notification_dialog.cpp +++ b/services/ans/src/notification_dialog.cpp @@ -21,32 +21,18 @@ #include "bundle_manager_helper.h" #include "in_process_call_wrapper.h" #include "os_account_manager.h" +#include "os_account_manager_helper.h" #include "system_dialog_connect_stb.h" #include "extension_manager_client.h" namespace OHOS { namespace Notification { constexpr int32_t DEFAULT_VALUE = -1; -int32_t NotificationDialog::GetActiveUserId() -{ - std::vector activeUserId; - auto errCode = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); - if (errCode != ERR_OK) { - ANS_LOGE("Query active accountIds failed with %{public}d.", errCode); - return AppExecFwk::Constants::ANY_USERID; - } - - if (activeUserId.empty()) { - ANS_LOGE("Active accountIds is empty."); - return AppExecFwk::Constants::ANY_USERID; - } - - return activeUserId.front(); -} int32_t NotificationDialog::GetUidByBundleName(const std::string &bundleName) { - auto userId = NotificationDialog::GetActiveUserId(); + int32_t userId = AppExecFwk::Constants::ANY_USERID; + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId); return IN_PROCESS_CALL(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId)); } @@ -61,8 +47,8 @@ ErrCode NotificationDialog::StartEnableNotificationDialogAbility( auto topBundleName = IN_PROCESS_CALL(AAFwk::AbilityManagerClient::GetInstance()->GetTopAbility().GetBundleName()); auto topUid = NotificationDialog::GetUidByBundleName(topBundleName); - if (topUid != uid) { - ANS_LOGE("Current application isn't in foreground, top is %{private}s.", topBundleName.c_str()); + if (topBundleName != appBundleName) { + ANS_LOGE("Current application isn't in foreground, top is %{public}s.", topBundleName.c_str()); return ERR_ANS_INVALID_BUNDLE; } diff --git a/services/ans/src/notification_dialog_manager.cpp b/services/ans/src/notification_dialog_manager.cpp index ad69e94423175369dce95fd121d0443020ee0a2e..29e4bde4f149bec2d01f666e8dd8b16149967897 100644 --- a/services/ans/src/notification_dialog_manager.cpp +++ b/services/ans/src/notification_dialog_manager.cpp @@ -94,8 +94,7 @@ ErrCode NotificationDialogManager::RequestEnableNotificationDailog( return ERROR_INTERNAL_ERROR; } if (!AddDialogInfoIfNotExist(bundle, callback)) { - ANS_LOGE("AddDialogIfNotExist failed. Dialog already exists. bundle = %{public}s", - bundle->GetBundleName().c_str()); + ANS_LOGE("AddDialogIfNotExist failed. Dialog already exists."); return ERR_ANS_DIALOG_IS_POPPING; } ErrCode result = NotificationDialog::StartEnableNotificationDialogAbility( diff --git a/services/ans/src/notification_extension_wrapper.cpp b/services/ans/src/notification_extension_wrapper.cpp index a0f83b571e247bdc0330caa71ed63d64c3e9e38b..513a39c48299369b16cb232ef8f30664557805e1 100644 --- a/services/ans/src/notification_extension_wrapper.cpp +++ b/services/ans/src/notification_extension_wrapper.cpp @@ -21,9 +21,11 @@ #include "advanced_datashare_observer.h" #include "common_event_manager.h" #include "common_event_support.h" - + #include "common_event_subscriber.h" #include "system_event_observer.h" +#include "interface_system_event.h" +#include "system_event_subscriber.h" namespace OHOS::Notification { const std::string EXTENTION_WRAPPER_PATH = "libans_ext.z.so"; @@ -58,19 +60,11 @@ void ExtensionWrapper::InitExtentionWrapper() } syncAdditionConfig_ = (SYNC_ADDITION_CONFIG)dlsym(extensionWrapperHandle_, "SyncAdditionConfig"); - getUnifiedGroupInfo_ = (GET_UNIFIED_GROUP_INFO)dlsym(extensionWrapperHandle_, "GetUnifiedGroupInfo"); - updateByCancel_ = (UPDATE_BY_CANCEL)dlsym(extensionWrapperHandle_, "UpdateByCancel"); - setLocalSwitch_ = (SET_LOCAL_SWITCH)dlsym(extensionWrapperHandle_, "SetlocalSwitch"); - initSummary_ = (INIT_SUMMARY)dlsym(extensionWrapperHandle_, "InitSummary"); localControl_ = (LOCAL_CONTROL)dlsym(extensionWrapperHandle_, "LocalControl"); - updateByBundle_ = (UPDATE_BY_BUNDLE)dlsym(extensionWrapperHandle_, "UpdateByBundle"); reminderControl_ = (REMINDER_CONTROL)dlsym(extensionWrapperHandle_, "ReminderControl"); - if (syncAdditionConfig_ == nullptr - || getUnifiedGroupInfo_ == nullptr - || updateByCancel_ == nullptr - || initSummary_ == nullptr + bannerControl_ = (BANNER_CONTROL)dlsym(extensionWrapperHandle_, "BannerControl"); + if (syncAdditionConfig_ == nullptr || bannerControl_ == nullptr || localControl_ == nullptr - || updateByBundle_ == nullptr || reminderControl_ == nullptr) { ANS_LOGE("extension wrapper symbol failed, error: %{public}s", dlerror()); return; @@ -85,7 +79,9 @@ void ExtensionWrapper::InitExtentionWrapper() if (!aggregateConfig.empty()) { syncAdditionConfig_("AGGREGATE_CONFIG", aggregateConfig); } - initSummary_(UpdateUnifiedGroupInfo); + if (initSummary_ != nullptr) { + initSummary_(UpdateUnifiedGroupInfo); + } ANS_LOGD("extension wrapper init success"); } @@ -93,7 +89,6 @@ void ExtensionWrapper::CheckIfSetlocalSwitch() { ANS_LOGD("CheckIfSetlocalSwitch enter"); if (extensionWrapperHandle_ == nullptr) { - ANS_LOGE("CheckIfSetlocalSwitch extension wrapper symbol failed"); return; } if (!isRegisterDataSettingObserver) { @@ -108,7 +103,6 @@ void ExtensionWrapper::CheckIfSetlocalSwitch() void ExtensionWrapper::SetlocalSwitch(std::string &enable) { if (setLocalSwitch_ == nullptr) { - ANS_LOGE("SetlocalSwitch wrapper symbol failed"); return; } bool status = (enable == "false" ? false : true); @@ -126,7 +120,7 @@ void ExtensionWrapper::RegisterDataSettingObserver() if (aggregationRoamingObserver == nullptr) { return; } - + Uri dataEnableUri(SETTINGS_DATA_UNIFIED_GROUP_ENABLE_URI); AdvancedDatashareObserver::GetInstance().RegisterSettingsObserver(dataEnableUri, aggregationRoamingObserver); } @@ -143,7 +137,6 @@ ErrCode ExtensionWrapper::SyncAdditionConfig(const std::string& key, const std:: void ExtensionWrapper::UpdateByCancel(const std::vector>& notifications, int deleteReason) { if (updateByCancel_ == nullptr) { - ANS_LOGE("updateUnifiedGroupByCancel wrapper symbol failed"); return; } int32_t deleteType = convertToDelType(deleteReason); @@ -153,7 +146,6 @@ void ExtensionWrapper::UpdateByCancel(const std::vector>& not ErrCode ExtensionWrapper::GetUnifiedGroupInfo(const sptr &request) { if (getUnifiedGroupInfo_ == nullptr) { - ANS_LOGE("getUnifiedGroupInfo wrapper symbol failed"); return 0; } return getUnifiedGroupInfo_(request); @@ -168,7 +160,16 @@ int32_t ExtensionWrapper::ReminderControl(const std::string &bundleName) return reminderControl_(bundleName); } -int32_t ExtensionWrapper::LocalControl(const sptr &request) +int32_t ExtensionWrapper::BannerControl(const std::string &bundleName) +{ + if (bannerControl_ == nullptr) { + ANS_LOGE("ReminderControl wrapper symbol failed"); + return -1; + } + return bannerControl_(bundleName); +} + +__attribute__((no_sanitize("cfi"))) int32_t ExtensionWrapper::LocalControl(const sptr &request) { if (localControl_ == nullptr) { ANS_LOGE("LocalControl wrapper symbol failed"); @@ -180,7 +181,6 @@ int32_t ExtensionWrapper::LocalControl(const sptr &request) void ExtensionWrapper::UpdateByBundle(const std::string bundleName, int deleteReason) { if (updateByBundle_ == nullptr) { - ANS_LOGE("UpdateByBundle wrapper symbol failed"); return; } int32_t deleteType = convertToDelType(deleteReason); diff --git a/services/ans/src/notification_local_live_view_subscriber_manager.cpp b/services/ans/src/notification_local_live_view_subscriber_manager.cpp index d345f091d8b1c6cbf83f5167f352fadf161d10a2..12640235fc6f828c1ff11b2bf7dac31ef90991b2 100644 --- a/services/ans/src/notification_local_live_view_subscriber_manager.cpp +++ b/services/ans/src/notification_local_live_view_subscriber_manager.cpp @@ -156,7 +156,7 @@ void NotificationLocalLiveViewSubscriberManager::OnRemoteDied(const wptr record = FindSubscriberRecord(object); if (record != nullptr) { - ANS_LOGW("subscriber removed."); + ANS_LOGI("subscriber removed . userId = %{public}d", record->userId); AdvancedNotificationService::GetInstance()->RemoveSystemLiveViewNotifications( record->bundleName, record->userId); buttonRecordList_.remove(record); diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 2907cda303f3fdf9912cbfd4e560e6d6f1df2690..13ee4a43afddfa853dc13325f2d785ab5de806f8 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -29,16 +29,24 @@ #include "nlohmann/json.hpp" #include "os_account_manager_helper.h" #include "notification_analytics_util.h" +#include "notification_config_parse.h" namespace OHOS { namespace Notification { - +namespace { +const static std::string KEY_BUNDLE_LABEL = "label_ans_bundle_"; +} std::mutex NotificationPreferences::instanceMutex_; std::shared_ptr NotificationPreferences::instance_; NotificationPreferences::NotificationPreferences() { preferncesDB_ = std::make_unique(); + if (preferncesDB_ == nullptr) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_1) + .Message("preferncesDB is null."); + NotificationAnalyticsUtil::ReportModifyEvent(message); + } InitSettingFromDisturbDB(); } @@ -59,7 +67,7 @@ ErrCode NotificationPreferences::AddNotificationSlots( { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s", __FUNCTION__); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1) + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_6) .BundleName(bundleOption == nullptr ? "" : bundleOption->GetBundleName()); if (bundleOption == nullptr || bundleOption->GetBundleName().empty() || slots.empty()) { message.Message("Invalid param."); @@ -72,9 +80,6 @@ ErrCode NotificationPreferences::AddNotificationSlots( for (auto slot : slots) { result = CheckSlotForCreateSlot(bundleOption, slot, preferencesInfo); if (result != ERR_OK) { - message.SlotType(static_cast(slot->GetType())); - message.Message("Check slot for create failed." + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } } @@ -120,8 +125,9 @@ ErrCode NotificationPreferences::RemoveNotificationSlot( if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1) - .BundleName(bundleOption->GetBundleName()); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_5); + message.Message(bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + + " slotType: " + std::to_string(static_cast(slotType))); message.SlotType(static_cast(slotType)); std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; @@ -129,16 +135,18 @@ ErrCode NotificationPreferences::RemoveNotificationSlot( result = CheckSlotForRemoveSlot(bundleOption, slotType, preferencesInfo); if (result == ERR_OK && (!preferncesDB_->RemoveSlotFromDisturbeDB(GenerateBundleKey(bundleOption), slotType, bundleOption->GetUid()))) { - message.Message("Remove slot failed: " + std::to_string(result)); + message.ErrorCode(result).Append(" Remove slot failed."); NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("%{public}s_%{public}d, remove slot failed.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } - message.Message("Remove slot successful"); - NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGI("%{public}s_%{public}d, Remove slot successful.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); return result; } @@ -148,27 +156,34 @@ ErrCode NotificationPreferences::RemoveNotificationAllSlots(const sptrGetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1) - .BundleName(bundleOption->GetBundleName()); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_3); + message.Message(bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid())); std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) { + if (GetBundleInfo(preferencesInfo, bundleOption, bundleInfo)) { bundleInfo.RemoveAllSlots(); preferencesInfo.SetBundleInfo(bundleInfo); if (!preferncesDB_->RemoveAllSlotsFromDisturbeDB(GenerateBundleKey(bundleOption), bundleOption->GetUid())) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + message.ErrorCode(result).Append(" Db operation failed."); + ANS_LOGE("%{public}s_%{public}d, Db operation failed.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); } } else { result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + message.ErrorCode(result).Append(" Notification bundle not exist."); + ANS_LOGE("%{public}s_%{public}d, Notification bundle not exist.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); } if (result == ERR_OK) { - ANS_LOGD("result is ERR_OK"); preferencesInfo_ = preferencesInfo; + message.ErrorCode(result).Append(" Remove all slot successful."); + ANS_LOGI("%{public}s_%{public}d, Remove all slot successful.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); } - message.Message("Remove all slot: " + std::to_string(result)); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -183,7 +198,8 @@ ErrCode NotificationPreferences::RemoveNotificationForBundle(const sptrRemoveBundleFromDisturbeDB(GenerateBundleKey(bundleOption), bundleOption->GetUid())) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; @@ -245,7 +261,7 @@ ErrCode NotificationPreferences::GetNotificationSlot(const sptr lock(preferenceMutex_); - if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + if (GetBundleInfo(preferencesInfo_, bundleOption, bundleInfo)) { if (!bundleInfo.GetSlot(type, slot)) { result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; } @@ -267,7 +283,7 @@ ErrCode NotificationPreferences::GetNotificationAllSlots( ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; std::lock_guard lock(preferenceMutex_); - if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + if (GetBundleInfo(preferencesInfo_, bundleOption, bundleInfo)) { bundleInfo.GetAllSlots(slots); } else { ANS_LOGW("Notification bundle does not exsit."); @@ -287,7 +303,7 @@ ErrCode NotificationPreferences::GetNotificationSlotsNumForBundle( ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; std::lock_guard lock(preferenceMutex_); - if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + if (GetBundleInfo(preferencesInfo_, bundleOption, bundleInfo)) { num = static_cast(bundleInfo.GetAllSlotsSize()); } else { result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; @@ -305,6 +321,14 @@ ErrCode NotificationPreferences::GetNotificationSlotFlagsForBundle( return GetBundleProperty(bundleOption, BundleType::BUNDLE_SLOTFLGS_TYPE, slotFlags); } +bool NotificationPreferences::IsNotificationSlotFlagsExists( + const sptr &bundleOption) +{ + if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { + return false; + } + return preferncesDB_->IsNotificationSlotFlagsExists(bundleOption); +} ErrCode NotificationPreferences::SetNotificationSlotFlagsForBundle( const sptr &bundleOption, uint32_t slotFlags) @@ -535,6 +559,14 @@ ErrCode NotificationPreferences::AddDoNotDisturbProfiles( if (!CheckDoNotDisturbProfileID(profile->GetProfileId())) { return ERR_ANS_INVALID_PARAM; } + auto trustList = profile->GetProfileTrustList(); + for (auto& bundleInfo : trustList) { + int32_t index = BundleManagerHelper::GetInstance()->GetAppIndexByUid(bundleInfo.GetUid()); + bundleInfo.SetAppIndex(index); + ANS_LOGI("Get app index by uid %{public}d %{public}s %{public}d", bundleInfo.GetUid(), + bundleInfo.GetBundleName().c_str(), index); + } + profile->SetProfileTrustList(trustList); } std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; @@ -550,10 +582,22 @@ ErrCode NotificationPreferences::AddDoNotDisturbProfiles( return ERR_OK; } +bool NotificationPreferences::GetBundleInfo(NotificationPreferencesInfo &preferencesInfo, + const sptr &bundleOption, NotificationPreferencesInfo::BundleInfo &info) const +{ + if (preferencesInfo.GetBundleInfo(bundleOption, info)) { + return true; + } else if (preferncesDB_->GetBundleInfo(bundleOption, info)) { + preferencesInfo.SetBundleInfo(info); + return true; + } + return false; +} + ErrCode NotificationPreferences::RemoveDoNotDisturbProfiles( int32_t userId, const std::vector> profiles) { - ANS_LOGE("Called."); + ANS_LOGD("Called."); for (auto profile : profiles) { if (profile == nullptr) { ANS_LOGE("The profile is nullptr."); @@ -577,21 +621,140 @@ ErrCode NotificationPreferences::RemoveDoNotDisturbProfiles( return ERR_OK; } -ErrCode NotificationPreferences::GetAllNotificationEnabledBundles(std::vector &bundleOption) +void NotificationPreferences::UpdateProfilesUtil(std::vector& trustList, + const std::vector bundleList) { - ANS_LOGD("Called."); + for (auto& item : bundleList) { + bool exit = false; + for (auto& bundle: trustList) { + if (item.GetUid() == bundle.GetUid()) { + exit = true; + break; + } + } + if (!exit) { + trustList.push_back(item); + } + } +} + +ErrCode NotificationPreferences::UpdateDoNotDisturbProfiles(int32_t userId, int32_t profileId, + const std::string& name, const std::vector& bundleList) +{ + ANS_LOGI("Called update Profile %{public}d %{public}d %{public}zu.", userId, profileId, bundleList.size()); + if (!CheckDoNotDisturbProfileID(profileId) || bundleList.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = ERR_OK; + if (preferencesInfo.GetDoNotDisturbProfiles(profileId, userId, profile)) { + auto trustList = profile->GetProfileTrustList(); + UpdateProfilesUtil(trustList, bundleList); + profile->SetProfileTrustList(trustList); + } else { + profile->SetProfileId(profileId); + profile->SetProfileName(name); + profile->SetProfileTrustList(bundleList); + } + ANS_LOGI("Update profile %{public}d %{public}d %{public}zu", userId, profile->GetProfileId(), + profile->GetProfileTrustList().size()); + preferencesInfo.AddDoNotDisturbProfiles(userId, {profile}); if (preferncesDB_ == nullptr) { + ANS_LOGE("The prefernces db is nullptr."); return ERR_ANS_SERVICE_NOT_READY; } - if (preferncesDB_->GetAllNotificationEnabledBundles(bundleOption)) { + if (!preferncesDB_->AddDoNotDisturbProfiles(userId, {profile})) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + preferencesInfo_ = preferencesInfo; + return ERR_OK; +} + +void NotificationPreferences::UpdateCloneBundleInfo(int32_t userId, + const NotificationCloneBundleInfo& cloneBundleInfo) +{ + ANS_LOGI("Event bundle update %{public}s.", cloneBundleInfo.Dump().c_str()); + NotificationPreferencesInfo::BundleInfo bundleInfo; + sptr bundleOption = new NotificationBundleOption(); + bundleOption->SetBundleName(cloneBundleInfo.GetBundleName()); + bundleOption->SetUid(cloneBundleInfo.GetUid()); + std::lock_guard lock(preferenceMutex_); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + if (!GetBundleInfo(preferencesInfo, bundleOption, bundleInfo)) { + bundleInfo.SetBundleName(cloneBundleInfo.GetBundleName()); + bundleInfo.SetBundleUid(cloneBundleInfo.GetUid()); + } + + /* after clone, override these witch */ + bundleInfo.SetSlotFlags(cloneBundleInfo.GetSlotFlags()); + bundleInfo.SetIsShowBadge(cloneBundleInfo.GetIsShowBadge()); + bundleInfo.SetEnableNotification(cloneBundleInfo.GetEnableNotification()); + /* update property to db */ + if (!preferncesDB_->UpdateBundlePropertyToDisturbeDB(userId, bundleInfo)) { + ANS_LOGW("Clone bundle info failed %{public}s.", cloneBundleInfo.Dump().c_str()); + return; + } + preferencesInfo.SetBundleInfo(bundleInfo); + + /* update slot info */ + std::vector> slots; + for (auto& cloneSlot : cloneBundleInfo.GetSlotInfo()) { + sptr slotInfo = new (std::nothrow) NotificationSlot(cloneSlot.slotType_); + uint32_t slotFlags = bundleInfo.GetSlotFlags(); + auto configSlotReminderMode = DelayedSingleton::GetInstance()-> + GetConfigSlotReminderModeByType(slotInfo->GetType(), bundleOption); + slotInfo->SetReminderMode(configSlotReminderMode & slotFlags); + slotInfo->SetEnable(cloneSlot.enable_); + slotInfo->SetForceControl(cloneSlot.isForceControl_); + slotInfo->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED); + slots.push_back(slotInfo); + bundleInfo.SetSlot(slotInfo); + } + + if (!preferncesDB_->UpdateBundleSlotToDisturbeDB(userId, cloneBundleInfo.GetBundleName(), + cloneBundleInfo.GetUid(), slots)) { + ANS_LOGW("Clone bundle slot failed %{public}s.", cloneBundleInfo.Dump().c_str()); preferencesInfo_ = preferencesInfo; - } else { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + return; } - return result; + preferencesInfo.SetBundleInfo(bundleInfo); + preferencesInfo_ = preferencesInfo; +} + +void NotificationPreferences::GetAllCLoneBundlesInfo(int32_t userId, + std::vector &cloneBundles) +{ + std::lock_guard lock(preferenceMutex_); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + std::unordered_map bundlesMap; + if (GetBatchKvsFromDb(KEY_BUNDLE_LABEL, bundlesMap, userId) != ERR_OK) { + ANS_LOGE("Get bundle map info failed."); + return; + } + preferencesInfo.GetAllCLoneBundlesInfo(userId, bundlesMap, cloneBundles); + preferencesInfo_ = preferencesInfo; +} + +void NotificationPreferences::GetDoNotDisturbProfileListByUserId(int32_t userId, + std::vector> &profiles) +{ + std::lock_guard lock(preferenceMutex_); + preferencesInfo_.GetAllDoNotDisturbProfiles(userId, profiles); +} + +ErrCode NotificationPreferences::GetAllNotificationEnabledBundles(std::vector &bundleOption) +{ + ANS_LOGD("Called."); + std::lock_guard lock(preferenceMutex_); + if (preferncesDB_ == nullptr) { + return ERR_ANS_SERVICE_NOT_READY; + } + if (!preferncesDB_->GetAllNotificationEnabledBundles(bundleOption)) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + return ERR_OK; } ErrCode NotificationPreferences::ClearNotificationInRestoreFactorySettings() @@ -615,9 +778,8 @@ ErrCode NotificationPreferences::GetDoNotDisturbProfile( return ERR_ANS_INVALID_PARAM; } std::lock_guard lock(preferenceMutex_); - NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - if (!preferencesInfo.GetDoNotDisturbProfiles(profileId, userId, profile)) { - return ERR_ANS_INVALID_PARAM; + if (!preferencesInfo_.GetDoNotDisturbProfiles(profileId, userId, profile)) { + return ERR_ANS_NO_PROFILE_TEMPLATE; } return ERR_OK; } @@ -629,8 +791,10 @@ void NotificationPreferences::RemoveDoNotDisturbProfileTrustList( ANS_LOGE("The bundle option is nullptr."); return; } + int32_t uid = bundleOption->GetUid(); + int32_t appIndex = bundleOption->GetAppIndex(); auto bundleName = bundleOption->GetBundleName(); - ANS_LOGD("Called, bundle name is %{public}s.", bundleName.c_str()); + ANS_LOGI("Remove %{public}s %{public}d %{public}d.", bundleName.c_str(), uid, appIndex); std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; @@ -643,7 +807,7 @@ void NotificationPreferences::RemoveDoNotDisturbProfileTrustList( } auto trustList = profile->GetProfileTrustList(); for (auto it = trustList.begin(); it != trustList.end(); it++) { - if (it->GetBundleName() == bundleName) { + if (it->GetUid() == uid) { trustList.erase(it); break; } @@ -670,7 +834,7 @@ ErrCode NotificationPreferences::CheckSlotForCreateSlot(const sptrGetBundleName()); bundleInfo.SetBundleUid(bundleOption->GetUid()); bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption)); @@ -686,7 +850,7 @@ ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const sptrGetType())) { bundleInfo.SetBundleName(bundleOption->GetBundleName()); bundleInfo.SetBundleUid(bundleOption->GetUid()); @@ -735,13 +899,15 @@ ErrCode NotificationPreferences::SetBundleProperty(NotificationPreferencesInfo & { ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (!preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + if (!GetBundleInfo(preferencesInfo_, bundleOption, bundleInfo)) { bundleInfo.SetBundleName(bundleOption->GetBundleName()); bundleInfo.SetBundleUid(bundleOption->GetUid()); bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption)); } result = SaveBundleProperty(bundleInfo, bundleOption, type, value); - preferencesInfo.SetBundleInfo(bundleInfo); + if (result == ERR_OK) { + preferencesInfo.SetBundleInfo(bundleInfo); + } return result; } @@ -750,7 +916,6 @@ template ErrCode NotificationPreferences::SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, const sptr &bundleOption, const BundleType &type, const T &value) { - HaMetaMessage message = HaMetaMessage().BundleName(bundleInfo.GetBundleName()); bool storeDBResult = true; switch (type) { case BundleType::BUNDLE_IMPORTANCE_TYPE: @@ -770,21 +935,18 @@ ErrCode NotificationPreferences::SaveBundleProperty(NotificationPreferencesInfo: storeDBResult = preferncesDB_->PutNotificationsEnabledForBundle(bundleInfo, value); break; case BundleType::BUNDLE_POPPED_DIALOG_TYPE: - ANS_LOGD("Into BUNDLE_POPPED_DIALOG_TYPE:SetHasPoppedDialog."); + ANS_LOGI("Into BUNDLE_POPPED_DIALOG_TYPE:SetHasPoppedDialog."); bundleInfo.SetHasPoppedDialog(value); storeDBResult = preferncesDB_->PutHasPoppedDialog(bundleInfo, value); break; case BundleType::BUNDLE_SLOTFLGS_TYPE: - ANS_LOGD("Into BUNDLE_SLOTFLGS_TYPE:SetSlotFlags."); + ANS_LOGI("Into BUNDLE_SLOTFLGS_TYPE:SetSlotFlags."); bundleInfo.SetSlotFlags(value); storeDBResult = preferncesDB_->PutSlotFlags(bundleInfo, value); break; default: break; } - message.Message("Save:" + std::to_string(static_cast(type)) + - " : " + std::to_string(value) + " : " + std::to_string(storeDBResult)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return storeDBResult ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -795,7 +957,7 @@ ErrCode NotificationPreferences::GetBundleProperty( ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; std::lock_guard lock(preferenceMutex_); - if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + if (GetBundleInfo(preferencesInfo_, bundleOption, bundleInfo)) { switch (type) { case BundleType::BUNDLE_IMPORTANCE_TYPE: value = bundleInfo.GetImportance(); @@ -849,6 +1011,10 @@ ErrCode NotificationPreferences::GetTemplateSupported(const std::string& templat nlohmann::json jsonObj; inFile >> jsonObj; + if (jsonObj.is_null() || !jsonObj.is_object()) { + ANS_LOGE("Invalid JSON object"); + return ERR_ANS_PREFERENCES_NOTIFICATION_READ_TEMPLATE_CONFIG_FAILED; + } if (jsonObj.is_discarded()) { ANS_LOGE("template json discarded error."); inFile.close(); @@ -926,25 +1092,21 @@ ErrCode NotificationPreferences::IsSmartReminderEnabled(const std::string &devic return storeDBResult ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } -void NotificationPreferences::InitSettingFromDisturbDB() +void NotificationPreferences::InitSettingFromDisturbDB(int32_t userId) { - ANS_LOGD("%{public}s", __FUNCTION__); + ANS_LOGI("%{public}s userId is %{public}d", __FUNCTION__, userId); std::lock_guard lock(preferenceMutex_); if (preferncesDB_ != nullptr) { - preferncesDB_->ParseFromDisturbeDB(preferencesInfo_); + preferncesDB_->ParseFromDisturbeDB(preferencesInfo_, userId); } } void NotificationPreferences::RemoveSettings(int32_t userId) { ANS_LOGD("%{public}s", __FUNCTION__); - - { - std::lock_guard lock(preferenceMutex_); - preferencesInfo_.RemoveNotificationEnable(userId); - preferencesInfo_.RemoveDoNotDisturbDate(userId); - } - + std::lock_guard lock(preferenceMutex_); + preferencesInfo_.RemoveNotificationEnable(userId); + preferencesInfo_.RemoveDoNotDisturbDate(userId); if (preferncesDB_ != nullptr) { preferncesDB_->RemoveNotificationEnable(userId); preferncesDB_->RemoveDoNotDisturbDate(userId); @@ -992,6 +1154,10 @@ bool NotificationPreferences::GetBundleSoundPermission(bool &allPackage, std::se ANS_LOGD("The bundle permission is :%{public}s.", value.c_str()); nlohmann::json jsonPermission = nlohmann::json::parse(value, nullptr, false); + if (jsonPermission.is_null() || jsonPermission.empty()) { + ANS_LOGE("Invalid JSON object"); + return false; + } if (jsonPermission.is_discarded() || !jsonPermission.is_array()) { ANS_LOGE("Parse bundle permission failed due to data is discarded or not array"); return false; @@ -1059,6 +1225,14 @@ int32_t NotificationPreferences::DeleteKvFromDb(const std::string &key, const in return preferncesDB_->DeleteKvFromDb(key, userId); } +int32_t NotificationPreferences::DeleteBatchKvFromDb(const std::vector &keys, const int32_t &userId) +{ + if (preferncesDB_ == nullptr) { + return ERR_ANS_SERVICE_NOT_READY; + } + return preferncesDB_->DeleteBatchKvFromDb(keys, userId); +} + bool NotificationPreferences::IsAgentRelationship(const std::string &agentBundleName, const std::string &sourceBundleName) { diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index e805416323a5d21b30a5128c91d78ddb532e94e8..b0ba16893c4bd2c2cb19b388135d591657ab4cf8 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -25,7 +25,8 @@ #include "hitrace_meter_adapter.h" #include "os_account_manager.h" #include "ipc_skeleton.h" - +#include "bundle_manager_helper.h" +#include "notification_analytics_util.h" #include "uri.h" namespace OHOS { namespace Notification { @@ -102,7 +103,7 @@ const static std::string KEY_BUNDLE_ENABLE_NOTIFICATION = "enabledNotification"; /** * Indicates that disturbe key which bundle enable notification. */ -const static std::string KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION = "enabledNotificationDistributed"; +const static std::string KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION = "enabledDistributedNotification"; /** * Indicates that disturbe key which bundle enable notification. @@ -434,6 +435,20 @@ bool NotificationPreferencesDatabase::PutHasPoppedDialog( return (result == NativeRdb::E_OK); } +bool NotificationPreferencesDatabase::IsNotificationSlotFlagsExists(const sptr &bundleOption) +{ + if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { + return false; + } + std::string bundleKey = bundleOption->GetBundleName().append(std::to_string(bundleOption->GetUid())); + std::string key = GenerateBundleKey(bundleKey, KEY_BUNDLE_SLOTFLGS_TYPE); + std::string value; + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); + int32_t result = rdbDataManager_->QueryData(key, value, userId); + return (result == NativeRdb::E_OK) || (!value.empty()); +} + bool NotificationPreferencesDatabase::PutDoNotDisturbDate( const int32_t &userId, const sptr &date) { @@ -595,6 +610,7 @@ bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleName, NotificationPreferencesInfo::BundleInfo bundleInfo; bundleInfo.SetBundleName(bundleName); bundleInfo.SetBundleUid(bundleUid); + bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleName, bundleUid)); result = PutBundleToDisturbeDB(bundleKeyStr, bundleInfo); break; } @@ -644,7 +660,7 @@ bool NotificationPreferencesDatabase::PutBundlePropertyValueToDisturbeDB( return true; } -bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreferencesInfo &info) +bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreferencesInfo &info, int32_t userId) { ANS_LOGD("%{public}s", __FUNCTION__); if (!CheckRdbStore()) { @@ -652,23 +668,58 @@ bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreference return false; } std::vector activeUserId; - OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(activeUserId); + if (userId == -1) { + OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(activeUserId); + } else { + activeUserId.push_back(userId); + } + for (auto iter : activeUserId) { GetDoNotDisturbType(info, iter); GetDoNotDisturbBeginDate(info, iter); GetDoNotDisturbEndDate(info, iter); GetEnableAllNotification(info, iter); GetDoNotDisturbProfile(info, iter); + } - std::unordered_map values; - int32_t result = rdbDataManager_->QueryDataBeginWithKey(KEY_BUNDLE_LABEL, values, iter); - if (result == NativeRdb::E_ERROR) { - ANS_LOGE("Get Bundle Info failed."); - continue; + return true; +} + + +bool NotificationPreferencesDatabase::GetBundleInfo(const sptr &bundleOption, + NotificationPreferencesInfo::BundleInfo &bundleInfo) +{ + std::string bundleDBKey = KEY_BUNDLE_LABEL + bundleOption->GetBundleName() + + std::to_string(bundleOption->GetUid()); + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); + std::string bundleKey; + int32_t result = rdbDataManager_->QueryData(bundleDBKey, bundleKey, userId); + if (result != NativeRdb::E_OK) { + ANS_LOGE("Get Bundle Info failed."); + return false; + } + ANS_LOGD("Bundle name is %{public}s.", bundleKey.c_str()); + std::unordered_map bundleEntries; + rdbDataManager_->QueryDataBeginWithKey((GenerateBundleKey(bundleKey)), bundleEntries, userId); + ANS_LOGD("Bundle key is %{public}s.", GenerateBundleKey(bundleKey).c_str()); + std::string keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_SHOW_BADGE); + bool badgeEnableExist = false; + for (auto bundleEntry : bundleEntries) { + if (IsSlotKey(GenerateBundleKey(bundleKey), bundleEntry.first)) { + ParseSlotFromDisturbeDB(bundleInfo, bundleKey, bundleEntry, userId); + } else { + ParseBundlePropertyFromDisturbeDB(bundleInfo, bundleKey, bundleEntry); } - ParseBundleFromDistureDB(info, values, iter); + + if (keyStr.compare(bundleEntry.first) == 0) { + badgeEnableExist = true; + } + } + + if (!badgeEnableExist) { + bundleInfo.SetIsShowBadge(static_cast(true)); } - return true; } @@ -781,9 +832,9 @@ bool NotificationPreferencesDatabase::HandleDataBaseMap( { std::regex matchBundlenamePattern("^ans_bundle_(.*)_name$"); std::smatch match; - std::vector ids; + int32_t currentUserId = SUBSCRIBE_USER_INIT; ErrCode result = ERR_OK; - result = OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids); + result = OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(currentUserId); if (result != ERR_OK) { ANS_LOGE("Get account id fail"); return false; @@ -808,13 +859,12 @@ bool NotificationPreferencesDatabase::HandleDataBaseMap( continue; } int userid = -1; - constexpr int FIRST_USERID = 0; result = - OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(StringToInt(uidItem->second), userid); + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(StringToInt(uidItem->second), userid); if (result != ERR_OK) { return false; } - if (userid != ids[FIRST_USERID]) { + if (userid != currentUserId) { continue; } NotificationBundleOption obj(value, StringToInt(uidItem->second)); @@ -1170,7 +1220,7 @@ int32_t NotificationPreferencesDatabase::StringToInt(const std::string &str) con { int32_t value = 0; if (!str.empty()) { - value = stoi(str, nullptr); + value = atoi(str.c_str()); } return value; } @@ -1179,7 +1229,7 @@ int64_t NotificationPreferencesDatabase::StringToInt64(const std::string &str) c { int64_t value = 0; if (!str.empty()) { - value = stoll(str, nullptr); + value = atoll(str.c_str()); } return value; } @@ -1647,7 +1697,7 @@ bool NotificationPreferencesDatabase::RemoveEnabledDbByBundleName(std::string bu } int32_t userId = -1; OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleUid, userId); - std::string key = std::string(KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION).append( + std::string key = std::string(KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION).append( KEY_MIDDLE_LINE).append(std::string(bundleName).append(KEY_MIDDLE_LINE)); ANS_LOGD("key is %{public}s", key.c_str()); int32_t result = NativeRdb::E_OK; @@ -1678,12 +1728,17 @@ bool NotificationPreferencesDatabase::RemoveEnabledDbByBundleName(std::string bu int32_t NotificationPreferencesDatabase::SetKvToDb( const std::string &key, const std::string &value, const int32_t &userId) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_2); if (!CheckRdbStore()) { ANS_LOGE("RdbStore is nullptr."); + message.Message("RdbStore is nullptr."); + NotificationAnalyticsUtil::ReportModifyEvent(message); return NativeRdb::E_ERROR; } int32_t result = rdbDataManager_->InsertData(key, value, userId); if (result != NativeRdb::E_OK) { + message.Message("Set key failed: " + key); + NotificationAnalyticsUtil::ReportModifyEvent(message); ANS_LOGE("Set key: %{public}s failed, result %{public}d.", key.c_str(), result); return NativeRdb::E_ERROR; } @@ -1696,12 +1751,17 @@ int32_t NotificationPreferencesDatabase::SetKvToDb( int32_t NotificationPreferencesDatabase::SetByteToDb( const std::string &key, const std::vector &value, const int32_t &userId) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_2); if (!CheckRdbStore()) { + message.Message("RdbStore is nullptr."); + NotificationAnalyticsUtil::ReportModifyEvent(message); ANS_LOGE("RdbStore is nullptr."); return NativeRdb::E_ERROR; } int32_t result = rdbDataManager_->InsertData(key, value, userId); if (result != NativeRdb::E_OK) { + message.Message("Set key failed: " + key); + NotificationAnalyticsUtil::ReportModifyEvent(message); ANS_LOGE("Set key: %{public}s failed, result %{public}d.", key.c_str(), result); return NativeRdb::E_ERROR; } @@ -1780,6 +1840,23 @@ int32_t NotificationPreferencesDatabase::DeleteKvFromDb(const std::string &key, return NativeRdb::E_OK; } +int32_t NotificationPreferencesDatabase::DeleteBatchKvFromDb(const std::vector &keys, + const int32_t &userId) +{ + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return NativeRdb::E_ERROR; + } + + int32_t result = rdbDataManager_->DeleteBathchData(keys, userId); + if (result != NativeRdb::E_OK) { + ANS_LOGE("Delete key-value failed, result %{public}d.", result); + return NativeRdb::E_ERROR; + } + + return NativeRdb::E_OK; +} + int32_t NotificationPreferencesDatabase::DropUserTable(const int32_t userId) { if (!CheckRdbStore()) { @@ -1810,6 +1887,10 @@ bool NotificationPreferencesDatabase::IsAgentRelationship(const std::string &age } ANS_LOGD("The agent relationship is :%{public}s.", agentShip.c_str()); nlohmann::json jsonAgentShip = nlohmann::json::parse(agentShip, nullptr, false); + if (jsonAgentShip.is_null() || jsonAgentShip.empty()) { + ANS_LOGE("Invalid JSON object"); + return false; + } if (jsonAgentShip.is_discarded() || !jsonAgentShip.is_array()) { ANS_LOGE("Parse agent ship failed due to data is discarded or not array"); return false; @@ -1849,7 +1930,7 @@ bool NotificationPreferencesDatabase::PutDistributedEnabledForBundle(const std:: std::string NotificationPreferencesDatabase::GenerateBundleLablel( const NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &deviceType) const { - return std::string(KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION).append(KEY_MIDDLE_LINE).append( + return std::string(KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION).append(KEY_MIDDLE_LINE).append( std::string(bundleInfo.GetBundleName()).append(KEY_MIDDLE_LINE).append(std::to_string( bundleInfo.GetBundleUid())).append(KEY_MIDDLE_LINE).append(deviceType)); } @@ -1973,5 +2054,69 @@ std::string NotificationPreferencesDatabase::GetAdditionalConfig(const std::stri ANS_LOGD("The additional config key is :%{public}s, value is :%{public}s.", key.c_str(), configValue.c_str()); return configValue; } + +bool NotificationPreferencesDatabase::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager == nullptr) { + return false; + } + return bundleManager->CheckApiCompatibility(bundleName, uid); +} + +bool NotificationPreferencesDatabase::UpdateBundlePropertyToDisturbeDB(int32_t userId, + const NotificationPreferencesInfo::BundleInfo &bundleInfo) +{ + if (bundleInfo.GetBundleName().empty()) { + ANS_LOGE("Bundle name is null."); + return false; + } + + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + std::string value; + std::string bundleLabelKey = KEY_BUNDLE_LABEL + GenerateBundleLablel(bundleInfo); + int32_t result = rdbDataManager_->QueryData(bundleLabelKey, value, userId); + if (result == NativeRdb::E_EMPTY_VALUES_BUCKET) { + if (rdbDataManager_->InsertData(bundleLabelKey, GenerateBundleLablel(bundleInfo), userId) + != NativeRdb::E_OK) { + ANS_LOGE("Store bundle name %{public}s to db is failed.", bundleLabelKey.c_str()); + return false; + } + } + if (result == NativeRdb::E_EMPTY_VALUES_BUCKET || result == NativeRdb::E_OK) { + return PutBundlePropertyValueToDisturbeDB(bundleInfo); + } + ANS_LOGW("Query bundle name %{public}s failed %{public}d.", bundleLabelKey.c_str(), result); + return false; +} + +bool NotificationPreferencesDatabase::UpdateBundleSlotToDisturbeDB(int32_t userId, const std::string &bundleName, + const int32_t &bundleUid, const std::vector> &slots) +{ + if (bundleName.empty()) { + ANS_LOGE("Bundle name is null."); + return false; + } + if (slots.empty()) { + ANS_LOGI("Slot is empty."); + return true; + } + + std::string bundleKey = bundleName + std::to_string(bundleUid); + std::unordered_map values; + for (auto& slot : slots) { + GenerateSlotEntry(bundleKey, slot, values); + } + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + int32_t result = rdbDataManager_->InsertBatchData(values, userId); + return (result == NativeRdb::E_OK); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index d32f07b60e2a9f721bd31c34fdca832ff5aab5c2..e77bc6e85e75d1a85b54919f425b2de78a542038 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -16,12 +16,14 @@ #include "ans_log_wrapper.h" #include "notification_constant.h" +#include "bundle_manager_helper.h" namespace OHOS { namespace Notification { namespace { const static std::string KEY_UNDER_LINE = "_"; } // namespace + NotificationPreferencesInfo::BundleInfo::BundleInfo() { } @@ -334,6 +336,38 @@ void NotificationPreferencesInfo::GetAllDoNotDisturbProfiles( } } +void NotificationPreferencesInfo::GetAllCLoneBundlesInfo(const int32_t &userId, + const std::unordered_map &bunlesMap, + std::vector &cloneBundles) +{ + for (const auto& bundleItem : bunlesMap) { + auto iter = infos_.find(bundleItem.second); + if (iter == infos_.end()) { + ANS_LOGI("No finde bundle info %{public}s.", bundleItem.second.c_str()); + continue; + } + + std::vector> slots; + NotificationCloneBundleInfo cloneBundleInfo; + int32_t index = BundleManagerHelper::GetInstance()->GetAppIndexByUid(iter->second.GetBundleUid()); + cloneBundleInfo.SetBundleName(iter->second.GetBundleName()); + cloneBundleInfo.SetAppIndex(index); + cloneBundleInfo.SetSlotFlags(iter->second.GetSlotFlags()); + cloneBundleInfo.SetIsShowBadge(iter->second.GetIsShowBadge()); + cloneBundleInfo.SetEnableNotification(iter->second.GetEnableNotification()); + iter->second.GetAllSlots(slots); + for (auto& slot : slots) { + NotificationCloneBundleInfo::SlotInfo slotInfo; + slotInfo.slotType_ = slot->GetType(); + slotInfo.enable_ = slot->GetEnable(); + slotInfo.isForceControl_ = slot->GetForceControl(); + cloneBundleInfo.AddSlotInfo(slotInfo); + } + cloneBundles.emplace_back(cloneBundleInfo); + } + ANS_LOGI("GetAllCLoneBundlesInfo size: %{public}zu.", cloneBundles.size()); +} + bool NotificationPreferencesInfo::GetDoNotDisturbDate(const int32_t &userId, sptr &doNotDisturbDate) const { diff --git a/services/ans/src/notification_rdb_data_mgr.cpp b/services/ans/src/notification_rdb_data_mgr.cpp index 5a9c0998da9ceb64092d87243ef71a741bfbc6a6..7b9d4f7722bf8f9df9dd9df56e39ea24a1063b7e 100644 --- a/services/ans/src/notification_rdb_data_mgr.cpp +++ b/services/ans/src/notification_rdb_data_mgr.cpp @@ -109,6 +109,7 @@ int32_t NotificationDataMgr::Init() notificationRdbConfig_.journalMode, notificationRdbConfig_.syncMode); rdbStoreConfig.SetSecurityLevel(NativeRdb::SecurityLevel::S1); + rdbStoreConfig.SetHaMode(NativeRdb::HAMode::MAIN_REPLICA); RdbStoreDataCallBackNotificationStorage rdbDataCallBack_(notificationRdbConfig_); std::lock_guard lock(createdTableMutex_); { @@ -191,6 +192,9 @@ int32_t NotificationDataMgr::InsertData(const std::string &key, const std::strin valuesBucket.PutString(NOTIFICATION_VALUE, value); ret = rdbStore_->InsertWithConflictResolution(rowId, tableName, valuesBucket, NativeRdb::ConflictResolution::ON_CONFLICT_REPLACE); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGE("Insert operation failed, result: %{public}d, key=%{public}s.", ret, key.c_str()); return NativeRdb::E_ERROR; @@ -219,6 +223,9 @@ int32_t NotificationDataMgr::InsertData(const std::string &key, const std::vecto valuesBucket.PutBlob(NOTIFICATION_VALUE, value); ret = rdbStore_->InsertWithConflictResolution(rowId, tableName, valuesBucket, NativeRdb::ConflictResolution::ON_CONFLICT_REPLACE); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGE("Insert operation failed, result: %{public}d, key=%{public}s.", ret, key.c_str()); return NativeRdb::E_ERROR; @@ -243,16 +250,20 @@ int32_t NotificationDataMgr::InsertBatchData(const std::unordered_map buckets; for (auto &value : values) { NativeRdb::ValuesBucket valuesBucket; valuesBucket.PutString(NOTIFICATION_KEY, value.first); valuesBucket.PutString(NOTIFICATION_VALUE, value.second); - ret = rdbStore_->InsertWithConflictResolution(rowId, tableName, valuesBucket, - NativeRdb::ConflictResolution::ON_CONFLICT_REPLACE); - if (ret != NativeRdb::E_OK) { - ANS_LOGE("Insert batch operation failed, result: %{public}d.", ret); - return NativeRdb::E_ERROR; - } + buckets.emplace_back(valuesBucket); + } + ret = rdbStore_->BatchInsert(rowId, tableName, buckets); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } + if (ret != NativeRdb::E_OK) { + ANS_LOGE("Insert batch operation failed, result: %{public}d.", ret); + return NativeRdb::E_ERROR; } } return NativeRdb::E_OK; @@ -284,6 +295,9 @@ int32_t NotificationDataMgr::DeleteData(const std::string tableName, const std:: NativeRdb::AbsRdbPredicates absRdbPredicates(tableName); absRdbPredicates.EqualTo(NOTIFICATION_KEY, key); int32_t ret = rdbStore_->Delete(rowId, absRdbPredicates); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGW("Delete operation failed from %{public}s, result: %{public}d, key=%{public}s.", tableName.c_str(), ret, key.c_str()); @@ -303,10 +317,11 @@ int32_t NotificationDataMgr::DeleteBathchData(const std::vector &ke ANS_LOGE("notification rdb is null"); return NativeRdb::E_ERROR; } + int32_t ret = NativeRdb::E_OK; int32_t rowId = -1; for (auto key : keys) { for (auto tableName : operatedTables) { - int32_t ret = DeleteData(tableName, key, rowId); + ret = DeleteData(tableName, key, rowId); if (ret != NativeRdb::E_OK) { return ret; } @@ -346,12 +361,18 @@ int32_t NotificationDataMgr::QueryData(const std::string tableName, const std::s } int32_t ret = absSharedResultSet->GoToFirstRow(); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGW("GoToFirstRow failed from %{public}s table. It is empty!, key=%{public}s", tableName.c_str(), key.c_str()); return NativeRdb::E_EMPTY_VALUES_BUCKET; } ret = absSharedResultSet->GetString(NOTIFICATION_VALUE_INDEX, value); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGE("GetString value failed from %{public}s table.", tableName.c_str()); return NativeRdb::E_ERROR; @@ -389,6 +410,9 @@ int32_t NotificationDataMgr::QueryData(const std::string tableName, const std::s } int32_t ret = absSharedResultSet->GoToFirstRow(); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGW("GoToFirstRow failed from %{public}s table. It is empty!, key=%{public}s", tableName.c_str(), key.c_str()); @@ -439,6 +463,9 @@ int32_t NotificationDataMgr::QueryDataBeginWithKey( } int32_t ret = absSharedResultSet->GoToFirstRow(); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGD("GoToFirstRow failed from %{public}s table.It is empty!, key=%{public}s", tableName.c_str(), key.c_str()); @@ -500,6 +527,9 @@ int32_t NotificationDataMgr::QueryAllData( } int32_t ret = absSharedResultSet->GoToFirstRow(); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGD("GoToFirstRow failed from %{public}s table. It is empty!", tableName.c_str()); return NativeRdb::E_EMPTY_VALUES_BUCKET; @@ -600,5 +630,13 @@ std::vector NotificationDataMgr::GenerateOperatedTables(const int32 operatedTables.emplace_back(notificationRdbConfig_.tableName); return operatedTables; } + +int32_t NotificationDataMgr::RestoreForMasterSlaver() +{ + ANS_LOGI("RestoreForMasterSlaver start"); + int32_t result = rdbStore_->Restore(""); + ANS_LOGI("RestoreForMasterSlaver result = %{public}d", result); + return result; +} } } \ No newline at end of file diff --git a/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp b/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp index e1d1365552fa2ee73248c5cbefe22781be5ff85a..8e4b8c8c0a5519c2fe0ebffbfab5c430dfcaf623 100644 --- a/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp +++ b/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp @@ -270,7 +270,7 @@ void SmartReminderCenter::HandleReminderMethods( GetDeviceStatusByType(deviceType, bitStatus); bool enabledAffectedBy = true; if (deviceType.compare(NotificationConstant::CURRENT_DEVICE_TYPE) != 0) { - if (IsNeedSynergy(deviceType, request->GetOwnerBundleName())) { + if (IsNeedSynergy(deviceType, request->GetOwnerBundleName(), request->GetOwnerUid())) { validDevices.insert(deviceType); } else { enabledAffectedBy = false; @@ -295,20 +295,15 @@ void SmartReminderCenter::HandleReminderMethods( } } -bool SmartReminderCenter::IsNeedSynergy(const string &deviceType, const string &ownerBundleName) const +bool SmartReminderCenter::IsNeedSynergy(const string &deviceType, const string &ownerBundleName, int32_t ownerUid) const { bool isEnable = true; if (NotificationPreferences::GetInstance()->IsSmartReminderEnabled(deviceType, isEnable) != ERR_OK || !isEnable) { return false; } - int32_t userId = -1; - int32_t result = - OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId); - if (result != ERR_OK) { - ANS_LOGE("HandleReminderMethods GetOsAccountLocalIdFromUid fail, code = %{public}d.", result); - return false; - } - sptr bundleOption = new (std::nothrow) NotificationBundleOption(ownerBundleName, userId); + + sptr bundleOption = + new (std::nothrow) NotificationBundleOption(ownerBundleName, ownerUid); if (NotificationPreferences::GetInstance()->IsDistributedEnabledByBundle( bundleOption, deviceType, isEnable) != ERR_OK || !isEnable) { return false; diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 6550c583b3502cf8df8c47de20fdd6bc76f74711..9d1ffc4ce654e2dcde562fccaca9c50186d327ce 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -89,10 +89,16 @@ ErrCode NotificationSubscriberManager::AddSubscriber( } } + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_2); + message.Message(GetClientBundleName() + "_" + + " user:" + std::to_string(subInfo->GetAppUserId())); if (subInfo->GetAppUserId() == SUBSCRIBE_USER_INIT) { int32_t userId = SUBSCRIBE_USER_INIT; ErrCode ret = OsAccountManagerHelper::GetInstance().GetCurrentCallingUserId(userId); if (ret != ERR_OK) { + ANS_LOGE("Get current calling userId failed."); + message.ErrorCode(ret).Append(" Get userId Failed"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ret; } subInfo->AddAppUserId(userId); @@ -103,13 +109,15 @@ ErrCode NotificationSubscriberManager::AddSubscriber( ANS_LOGE("queue is nullptr"); return result; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_2); + ffrt::task_handle handler = notificationSubQueue_->submit_h(std::bind([this, &subscriber, &subInfo, &result]() { result = this->AddSubscriberInner(subscriber, subInfo); })); notificationSubQueue_->wait(handler); - message.Message("Subscribe notification: " + GetClientBundleName() + " user " + - std::to_string(subInfo->GetAppUserId()) + " " + std::to_string(result)); + + ANS_LOGI("%{public}s_, user: %{public}s, Add subscriber result: %{public}d", GetClientBundleName().c_str(), + std::to_string(subInfo->GetAppUserId()).c_str(), result); + message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -128,7 +136,7 @@ ErrCode NotificationSubscriberManager::RemoveSubscriber( ANS_LOGE("queue is nullptr"); return result; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_3); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_1); ffrt::task_handle handler = notificationSubQueue_->submit_h(std::bind([this, &subscriber, &subscribeInfo, &result]() { ANS_LOGE("ffrt enter!"); @@ -136,8 +144,11 @@ ErrCode NotificationSubscriberManager::RemoveSubscriber( })); notificationSubQueue_->wait(handler); std::string appUserId = (subscribeInfo == nullptr) ? "all" : std::to_string(subscribeInfo->GetAppUserId()); - message.Message("Remove subscriber: " + GetClientBundleName() + " user " + - appUserId + " " + std::to_string(result)); + + ANS_LOGI("%{public}s_, user: %{public}s, Remove subscriber result: %{public}d", GetClientBundleName().c_str(), + appUserId.c_str(), result); + message.Message(GetClientBundleName() + "_" + " user:" + appUserId); + message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -280,7 +291,7 @@ void NotificationSubscriberManager::OnRemoteDied(const wptr &obje std::shared_ptr record = FindSubscriberRecord(object); if (record != nullptr) { auto subscriberUid = record->subscriberUid; - ANS_LOGW("subscriber removed."); + ANS_LOGI("subscriber removed . subscriberUid = %{public}d", record->subscriberUid); subscriberRecordList_.remove(record); AdvancedNotificationService::GetInstance()->RemoveSystemLiveViewNotificationsOfSa(record->subscriberUid); } @@ -420,7 +431,6 @@ void NotificationSubscriberManager::NotifyConsumedInner( HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s notification->GetUserId <%{public}d>", __FUNCTION__, notification->GetUserId()); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_1).Checkfailed(false); for (auto record : subscriberRecordList_) { ANS_LOGD("%{public}s record->userId = <%{public}d> BundleName = <%{public}s deviceType = %{public}s", __FUNCTION__, record->userId, notification->GetBundleName().c_str(), record->deviceType.c_str()); @@ -442,9 +452,6 @@ void NotificationSubscriberManager::NotifyConsumedInner( record->subscriber->OnConsumed(notification, notificationMap); } } - message.Message(notification->GetKey() + " " + std::to_string(notification->GetUserId()) + - " size " + std::to_string(subscriberRecordList_.size())); - NotificationAnalyticsUtil::ReportPublishFailedEvent(notification->GetNotificationRequestPoint(), message); } #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED @@ -501,9 +508,7 @@ void NotificationSubscriberManager::NotifyCanceledInner( liveViewContent->FillPictureMarshallingMap(); } - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 6).ErrorCode(ERR_OK); - ReportDeleteFailedEventPushByNotification(notification, haMetaMessage, deleteReason, "success"); - + ANS_LOGI("CancelNotification key = %{public}s", notification->GetKey().c_str()); for (auto record : subscriberRecordList_) { ANS_LOGD("%{public}s record->userId = <%{public}d>", __FUNCTION__, record->userId); if (IsSubscribedBysubscriber(record, notification)) { @@ -522,7 +527,7 @@ bool NotificationSubscriberManager::IsSubscribedBysubscriber( auto BundleNames = notification->GetBundleName(); auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); bool isSubscribedTheNotification = record->subscribedAll || (iter != record->bundleList_.end()) || - (notification->GetNotificationRequest().GetCreatorUid() == record->subscriberUid); + (notification->GetNotificationRequestPoint()->GetCreatorUid() == record->subscriberUid); if (!isSubscribedTheNotification) { return false; } @@ -531,7 +536,7 @@ bool NotificationSubscriberManager::IsSubscribedBysubscriber( return true; } - int32_t recvUserId = notification->GetNotificationRequest().GetReceiverUserId(); + int32_t recvUserId = notification->GetNotificationRequestPoint()->GetReceiverUserId(); int32_t sendUserId = notification->GetUserId(); if (record->userId == recvUserId) { return true; @@ -555,6 +560,13 @@ void NotificationSubscriberManager::BatchNotifyCanceledInner(const std::vectorGetKey()).append("-"); + } + ANS_LOGI("CancelNotification key = %{public}s", notificationKeys.c_str()); + for (auto record : subscriberRecordList_) { if (record == nullptr) { continue; diff --git a/services/ans/src/notification_timer_info.cpp b/services/ans/src/notification_timer_info.cpp index 924a96617bfc2951879019ff047d200ddfa34726..4b4a20be67076a7763eda46325c2d10533e49bd8 100644 --- a/services/ans/src/notification_timer_info.cpp +++ b/services/ans/src/notification_timer_info.cpp @@ -46,6 +46,7 @@ void NotificationTimerInfo::OnTrigger() ANS_LOGD("ffrt enter!"); if (callBack_ != nullptr) { callBack_(); + callBack_ = nullptr; } })); notificationSvrQueue_->wait(handler); @@ -55,5 +56,10 @@ void NotificationTimerInfo::SetCallbackInfo(const std::function &callBac { callBack_ = callBack; } + +std::function NotificationTimerInfo::GetCallBack() +{ + return callBack_; +} } } diff --git a/services/ans/src/notification_trust_list.cpp b/services/ans/src/notification_trust_list.cpp index ce1b0c13640eeca4ec0d7d2a01568535a9b23704..6df8d69b0ad912eafddf6494a2cd3bb06ca09992 100644 --- a/services/ans/src/notification_trust_list.cpp +++ b/services/ans/src/notification_trust_list.cpp @@ -14,9 +14,12 @@ */ #include "notification_trust_list.h" +#include "notification_extension_wrapper.h" + namespace OHOS { namespace Notification { +constexpr static uint32_t LIVE_VIEW_INDEX = 0; constexpr static uint32_t REMINDER_LIST_INDEX = 2; NotificationTrustList::NotificationTrustList() { @@ -45,6 +48,9 @@ void NotificationTrustList::GetCcmPrivilegesConfig() } for (auto &affect : affects.items()) { std::string affects_value = affect.value().get(); + if (affects_value[LIVE_VIEW_INDEX] != PRIVILEGES_BANNER_NOT_ALLOW) { + liveViewTrustlist_.insert(affect.key()); + } if (affects_value.length() >= PRIVILEGES_CONFIG_MIN_LEN && affects_value[PRIVILEGES_BANNER_INDEX] != PRIVILEGES_BANNER_NOT_ALLOW) { notificationSlotFlagsTrustlist_.insert(affect.key()); @@ -53,11 +59,15 @@ void NotificationTrustList::GetCcmPrivilegesConfig() affects_value[REMINDER_LIST_INDEX] != PRIVILEGES_BANNER_NOT_ALLOW) { reminderTrustlist_.insert(affect.key()); } - notificationSlotFlagsTrustlist_.insert(affect.key()); } return; } +bool NotificationTrustList::IsLiveViewTrtust(const std::string bundleName) +{ + return liveViewTrustlist_.count(bundleName); +} + bool NotificationTrustList::IsReminderTrustList(const std::string& bundleName) { return reminderTrustlist_.count(bundleName); @@ -65,7 +75,15 @@ bool NotificationTrustList::IsReminderTrustList(const std::string& bundleName) bool NotificationTrustList::IsSlotFlagsTrustlistAsBundle(const sptr &bundleOption) { - return notificationSlotFlagsTrustlist_.count(bundleOption->GetBundleName()); + if (notificationSlotFlagsTrustlist_.count(bundleOption->GetBundleName()) > 0) { + return true; + } +#ifdef ENABLE_ANS_EXT_WRAPPER + int32_t ctrlResult = EXTENTION_WRAPPER->BannerControl(bundleOption->GetBundleName()); + return (ctrlResult == ERR_OK) ? true : false; +#else + return false; +#endif } } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/os_account_manager_helper.cpp b/services/ans/src/os_account_manager_helper.cpp index fa92124aa162fee16f2c00855a3f982562f4b465..1355bfec8b98ffdc81db235e1d4af51444868dee 100644 --- a/services/ans/src/os_account_manager_helper.cpp +++ b/services/ans/src/os_account_manager_helper.cpp @@ -57,10 +57,12 @@ ErrCode OsAccountManagerHelper::GetCurrentCallingUserId(int32_t &userId) ErrCode OsAccountManagerHelper::GetCurrentActiveUserId(int32_t &id) { - std::vector activeUserId; - int32_t ret = GetAllActiveOsAccount(activeUserId); - if (activeUserId.size() > 0) { - id = activeUserId[0]; + int32_t ret = OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(id); + if (ret != ERR_OK) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_4) + .Message("Get foreground os account failed ret " + std::to_string(ret)); + NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Failed to call OsAccountManager::GetForegroundOsAccountLocalId, code is %{public}d", ret); } return ret; } diff --git a/services/ans/src/permission_filter.cpp b/services/ans/src/permission_filter.cpp index 5734361ca380ccca085d6994d0807843b32705a3..cc7525aae7aba92d825f8a08d5f17d0720a46882 100644 --- a/services/ans/src/permission_filter.cpp +++ b/services/ans/src/permission_filter.cpp @@ -19,6 +19,7 @@ #include "ans_log_wrapper.h" #include "bundle_manager_helper.h" #include "notification_preferences.h" +#include "notification_analytics_util.h" namespace OHOS { namespace Notification { @@ -32,6 +33,7 @@ ErrCode PermissionFilter::OnPublish(const std::shared_ptr &r { bool isForceControl = false; bool enable = false; + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_1); ErrCode result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(record->bundleOption, enable); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { @@ -44,11 +46,14 @@ ErrCode PermissionFilter::OnPublish(const std::shared_ptr &r sptr slot; NotificationConstant::SlotType slotType = record->request->GetSlotType(); + message.SlotType(slotType); result = NotificationPreferences::GetInstance()->GetNotificationSlot(record->bundleOption, slotType, slot); if (result == ERR_OK) { if (slot != nullptr) { isForceControl = slot->GetForceControl(); } else { + message.ErrorCode(ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED).Message("Slot type not exist."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED; ANS_LOGE("Type[%{public}d] slot does not exist", slotType); } @@ -56,6 +61,8 @@ ErrCode PermissionFilter::OnPublish(const std::shared_ptr &r if (result == ERR_OK) { if (!enable && !isForceControl) { + message.ErrorCode(ERR_ANS_NOT_ALLOWED).Message("Notifications is off."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); ANS_LOGE("Enable notifications for bundle is OFF"); return ERR_ANS_NOT_ALLOWED; } @@ -67,4 +74,4 @@ ErrCode PermissionFilter::OnPublish(const std::shared_ptr &r return result; } } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index a2e9ce63d568cc9d740a38057fcffdb86cf2f5e5..27e4042bb9f18d74c554edc74f89433a87917607 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -30,6 +30,7 @@ #include "ipc_skeleton.h" #include "notification_slot.h" #include "os_account_manager.h" +#include "os_account_manager_helper.h" #include "reminder_event_manager.h" #include "time_service_client.h" #include "singleton.h" @@ -61,6 +62,8 @@ const int REASON_APP_API = 1; const int INDEX_KEY = 0; const int INDEX_TYPE = 1; const int INDEX_VALUE = 2; +constexpr int8_t NORMAL_CALLBACK = 0; // timer callback +constexpr int8_t REISSUE_CALLBACK = 1; // time change, boot complte callback } /** @@ -99,7 +102,6 @@ ErrCode ReminderDataManager::PublishReminder(const sptr &remind } UpdateAndSaveReminderLocked(reminder, bundleOption); queue_->submit([this, reminder]() { - UpdateReminderLanguageLocked(reminder); StartRecentReminder(); }); return ERR_OK; @@ -251,13 +253,6 @@ void ReminderDataManager::CancelRemindersImplLocked(const std::string &packageNa } } for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) { - int32_t reminderId = (*vit)->GetReminderId(); - auto mit = notificationBundleOptionMap_.find(reminderId); - if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); - ++vit; - continue; - } if (IsMatched(*vit, packageName, userId, uid)) { if ((*vit)->IsAlerting()) { StopAlertingReminder(*vit); @@ -265,7 +260,6 @@ void ReminderDataManager::CancelRemindersImplLocked(const std::string &packageNa CancelNotification(*vit); RemoveFromShowedReminders(*vit); vit = reminderVector_.erase(vit); - notificationBundleOptionMap_.erase(mit); totalCount_--; continue; } @@ -328,7 +322,7 @@ void ReminderDataManager::CancelNotification(const sptr &remind ANSR_LOGE("Cancel notification fail"); return; } - sptr bundleOption = FindNotificationBundleOption(reminder->GetReminderId()); + sptr bundleOption = reminder->GetNotificationBundleOption(); advancedNotificationService_->CancelPreparedNotification(notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL, bundleOption, NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE); } @@ -381,12 +375,6 @@ void ReminderDataManager::OnUserRemove(const int32_t& userId) CancelAllReminders(userId); } -void ReminderDataManager::OnServiceStart() -{ - std::vector> immediatelyShowReminders; - GetImmediatelyShowRemindersLocked(immediatelyShowReminders); -} - void ReminderDataManager::OnUserSwitch(const int32_t& userId) { ANSR_LOGD("Switch user id from %{private}d to %{private}d", currentUserId_, userId); @@ -402,19 +390,10 @@ void ReminderDataManager::OnProcessDiedLocked(const sptrGetBundleName(); int32_t uid = bundleOption->GetUid(); ANSR_LOGD("OnProcessDiedLocked, bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); - std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); std::lock_guard locker(ReminderDataManager::MUTEX); + std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { - int32_t reminderId = (*it)->GetReminderId(); - auto mit = notificationBundleOptionMap_.find(reminderId); - if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGD("Not get bundle option, the reminder may has been cancelled, reminderId=%{public}d", reminderId); - CancelNotification(*it); - showedReminderVector_.erase(it); - --it; - continue; - } - if (mit->second->GetBundleName() != bundleName || mit->second->GetUid() != uid) { + if ((*it)->GetBundleName() != bundleName || (*it)->GetUid() != uid) { continue; } if ((*it)->IsAlerting()) { @@ -437,46 +416,10 @@ void ReminderDataManager::InitTimerInfo(std::shared_ptr &shar sharedTimerInfo->SetRepeat(false); sharedTimerInfo->SetInterval(0); - auto mit = notificationBundleOptionMap_.find(reminderRequest->GetReminderId()); - if (mit == notificationBundleOptionMap_.end()) { - ANS_LOGE("Failed to get bundle information. reminderId=%{public}d", - reminderRequest->GetReminderId()); - return; - } - sharedTimerInfo->SetBundleName(mit->second->GetBundleName()); - sharedTimerInfo->SetUid(mit->second->GetUid()); + sharedTimerInfo->SetBundleName(reminderRequest->GetBundleName()); + sharedTimerInfo->SetUid(reminderRequest->GetUid()); - // The systemtimer type will be set TIMER_TYPE_INEXACT_REMINDER&&EXACT if reminder type is CALENDAR or TIMER, - // and set WAKEUP&&EXACT if ALARM. - int32_t timerType; - if (reminderType == TimerType::TRIGGER_TIMER && - (reminderRequest->GetReminderType() == ReminderRequest::ReminderType::CALENDAR || - reminderRequest->GetReminderType() == ReminderRequest::ReminderType::TIMER)) { -#ifdef DEVICE_STANDBY_ENABLE - // Get allow list. - std::string name = mit->second->GetBundleName(); - std::vector allowInfoList; - DevStandbyMgr::StandbyServiceClient::GetInstance().GetAllowList(DevStandbyMgr::AllowType::TIMER, - allowInfoList, REASON_APP_API); - auto it = std::find_if(allowInfoList.begin(), - allowInfoList.end(), - [&name](const DevStandbyMgr::AllowInfo &allowInfo) { - return allowInfo.GetName() == name; - }); - if (reminderRequest->IsSystemApp() || it != allowInfoList.end()) { - ANS_LOGI("%{public}s is systemapp or in allowlist, set ALARM type.", name.c_str()); - timerType = static_cast(timerTypeWakeup | timerTypeExact); - } else { - ANS_LOGI("%{public}s is CALENDAR or TIMER type.", name.c_str()); - uint8_t timerTypeAns = static_cast(sharedTimerInfo->TIMER_TYPE_INEXACT_REMINDER); - timerType = static_cast(timerTypeAns | timerTypeExact); - } -#else - timerType = static_cast(timerTypeWakeup | timerTypeExact); -#endif - } else { - timerType = static_cast(timerTypeWakeup | timerTypeExact); - } + int32_t timerType = static_cast(timerTypeWakeup | timerTypeExact); sharedTimerInfo->SetType(timerType); } @@ -559,23 +502,12 @@ sptr ReminderDataManager::FindReminderRequestLocked( return reminder; } -sptr ReminderDataManager::FindNotificationBundleOption(const int32_t &reminderId) const -{ - auto it = notificationBundleOptionMap_.find(reminderId); - if (it == notificationBundleOptionMap_.end()) { - ANSR_LOGW("Failed to get bundle option."); - return nullptr; - } else { - return it->second; - } -} - bool ReminderDataManager::cmp(sptr &reminderRequest, sptr &other) { return reminderRequest->GetTriggerTimeInMilli() < other->GetTriggerTimeInMilli(); } -void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification) +void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification, bool isButtonClick) { int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); sptr reminder = FindReminderRequestLocked(reminderId); @@ -590,8 +522,10 @@ void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool c CloseRemindersByGroupId(reminderId, packageName, groupId); } CloseReminder(reminder, cancelNotification); - UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); - CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); + if (isButtonClick) { + UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); + CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); + } StartRecentReminder(); } @@ -617,7 +551,7 @@ void ReminderDataManager::CloseRemindersByGroupId(const int32_t &oldReminderId, if (IsMatchedForGroupIdAndPkgName(reminder, packageName, groupId)) { reminder->SetExpired(true); reminder->SetStateToInActive(); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); ResetStates(TimerType::TRIGGER_TIMER); ANSR_LOGD("Cancel reminders by groupid, reminder is %{public}s", reminder->Dump().c_str()); } @@ -641,7 +575,7 @@ void ReminderDataManager::CloseReminder(const sptr &reminder, b } reminder->OnClose(true); RemoveFromShowedReminders(reminder); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); if (cancelNotification) { CancelNotification(reminder); } @@ -701,11 +635,7 @@ void ReminderDataManager::UpdateAppDatabase(const sptr &reminde return; } // init default dstBundleName - std::string dstBundleName; - auto mit = notificationBundleOptionMap_.find(reminder->GetReminderId()); - if (mit != notificationBundleOptionMap_.end()) { - dstBundleName = mit->second->GetBundleName(); - } + std::string dstBundleName = reminder->GetBundleName(); GenDstBundleName(dstBundleName, actionButtonMap.at(actionButtonType).dataShareUpdate->uri); DataShare::CreateOptions options; @@ -820,6 +750,10 @@ void ReminderDataManager::GenDstBundleName(std::string &dstBundleName, const std void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) { + if (!IsSystemReady()) { + ANSR_LOGW("bundle service or ability service not ready."); + return; + } std::string typeInfo = type == TIME_ZONE_CHANGE ? "timeZone" : "dateTime"; ANSR_LOGI("Refresh all reminders due to %{public}s changed by user", typeInfo.c_str()); if (activeReminderId_ != -1) { @@ -834,7 +768,7 @@ void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) std::vector> extensionReminders; RefreshRemindersLocked(type, showImmediately, extensionReminders); HandleImmediatelyShow(showImmediately, true); - HandleExtensionReminder(extensionReminders); + HandleExtensionReminder(extensionReminders, REISSUE_CALLBACK); StartRecentReminder(); } @@ -869,7 +803,7 @@ void ReminderDataManager::TerminateAlerting(const sptr &reminde return; } int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = FindNotificationBundleOption(reminderId); + sptr bundleOption = reminder->GetNotificationBundleOption(); sptr notificationRequest = reminder->GetNotificationRequest(); if (bundleOption == nullptr) { ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); @@ -883,8 +817,10 @@ void ReminderDataManager::TerminateAlerting(const sptr &reminde } // Set the notification SoundEnabled and VibrationEnabled by soltType advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + // Since Ans and reminder share a notificationRequest, there is a multi-threaded contention, + // so need to make a copy when calling the Ans interface + PublishNotificationRequest(notificationRequest, bundleOption); + store_->UpdateOrInsert(reminder, bundleOption); } void ReminderDataManager::UpdateAndSaveReminderLocked( @@ -892,7 +828,9 @@ void ReminderDataManager::UpdateAndSaveReminderLocked( { std::lock_guard lock(ReminderDataManager::MUTEX); reminder->InitReminderId(); - reminder->InitUserId(ReminderRequest::GetUserId(bundleOption->GetUid())); + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); + reminder->InitUserId(userId); reminder->InitUid(bundleOption->GetUid()); reminder->InitBundleName(bundleOption->GetBundleName()); @@ -900,13 +838,7 @@ void ReminderDataManager::UpdateAndSaveReminderLocked( ANSR_LOGW("now publish reminder is expired. reminder is =%{public}s", reminder->Dump().c_str()); reminder->SetExpired(true); } - int32_t reminderId = reminder->GetReminderId(); - auto ret = notificationBundleOptionMap_.insert( - std::pair>(reminderId, bundleOption)); - if (!ret.second) { - ANSR_LOGE("Containers add to map error"); - return; - } + reminder->SetNotificationBundleOption(bundleOption); reminderVector_.push_back(reminder); totalCount_++; store_->UpdateOrInsert(reminder, bundleOption); @@ -923,12 +855,13 @@ bool ReminderDataManager::ShouldAlert(const sptr &reminder) con return false; } int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = FindNotificationBundleOption(reminderId); + sptr bundleOption = reminder->GetNotificationBundleOption(); if (bundleOption == nullptr) { ANSR_LOGD("The reminder (reminderId=%{public}d) is silent", reminderId); return false; } - int32_t userId = ReminderRequest::GetUserId(bundleOption->GetUid()); + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); if (currentUserId_ != userId) { ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for not in active user, " \ "current user id: %{private}d, reminder user id: %{private}d", reminderId, currentUserId_, userId); @@ -939,7 +872,7 @@ bool ReminderDataManager::ShouldAlert(const sptr &reminder) con 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; + return true; } if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { return true; @@ -978,7 +911,9 @@ void ReminderDataManager::ShowActiveReminder(const EventFwk::Want &want) if (HandleSysTimeChange(reminder)) { return; } - ShowActiveReminderExtendLocked(reminder); + std::vector> extensionReminders; + ShowActiveReminderExtendLocked(reminder, extensionReminders); + HandleExtensionReminder(extensionReminders, NORMAL_CALLBACK); StartRecentReminder(); } @@ -1017,12 +952,15 @@ void ReminderDataManager::SetAlertingReminder(const sptr &remin ANSR_LOGD("Set alertingReminderId=%{public}d", alertingReminderId_.load()); } -void ReminderDataManager::ShowActiveReminderExtendLocked(sptr &reminder) +void ReminderDataManager::ShowActiveReminderExtendLocked(sptr& reminder, + std::vector>& extensionReminders) { std::lock_guard lock(ReminderDataManager::MUTEX); uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); bool isAlerting = false; sptr playSoundReminder = nullptr; + std::unordered_map limits; + int32_t totalCount = 0; for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { if ((*it)->IsExpired()) { continue; @@ -1038,11 +976,16 @@ void ReminderDataManager::ShowActiveReminderExtendLocked(sptr & if (!(*it)->IsNeedNotification()) { continue; } - ReminderDataManager::AsyncStartExtensionAbility((*it), CONNECT_EXTENSION_MAX_RETRY_TIMES); + extensionReminders.push_back((*it)); if ((*it)->CheckExcludeDate()) { ANSR_LOGI("reminder[%{public}d] trigger time is in exclude date", (*it)->GetReminderId()); continue; } + if (!CheckShowLimit(limits, totalCount, (*it))) { + (*it)->OnShow(false, false, false); + store_->UpdateOrInsert((*it), (*it)->GetNotificationBundleOption()); + continue; + } if (((*it)->GetRingDuration() > 0) && !isAlerting) { playSoundReminder = (*it); isAlerting = true; @@ -1055,7 +998,7 @@ void ReminderDataManager::ShowActiveReminderExtendLocked(sptr & } } -bool ReminderDataManager::StartExtensionAbility(const sptr &reminder) +bool ReminderDataManager::StartExtensionAbility(const sptr &reminder, const int8_t type) { ANSR_LOGD("StartExtensionAbility"); if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { @@ -1065,6 +1008,7 @@ bool ReminderDataManager::StartExtensionAbility(const sptr &rem AAFwk::Want want; want.SetElementName(wantInfo->pkgName, wantInfo->abilityName); want.SetParam(ReminderRequest::PARAM_REMINDER_ID, reminder->GetReminderId()); + want.SetParam("PULL_TYPE", type); int32_t result = IN_PROCESS_CALL( AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, nullptr)); if (result != ERR_OK) { @@ -1076,15 +1020,31 @@ bool ReminderDataManager::StartExtensionAbility(const sptr &rem return true; } -void ReminderDataManager::AsyncStartExtensionAbility(const sptr &reminder, int32_t times) +void ReminderDataManager::AsyncStartExtensionAbility(const sptr &reminder, int32_t times, + const int8_t type) { + auto manager = ReminderDataManager::GetInstance(); + if (manager == nullptr) { + ANSR_LOGW("ReminderDataManager is nullptr."); + return; + } + if (!manager->IsSystemReady()) { + ANSR_LOGW("bundle service or ability service not ready."); + return; + } + if (!reminder->IsSystemApp()) { + ANSR_LOGI("Start extension ability failed, is not system app"); + return; + } times--; - bool ret = ReminderDataManager::StartExtensionAbility(reminder); + bool ret = ReminderDataManager::StartExtensionAbility(reminder, type); if (!ret && times > 0 && serviceQueue_ != nullptr) { ANSR_LOGD("StartExtensionAbilty failed, reminder times: %{public}d", times); ffrt::task_attr taskAttr; taskAttr.delay(CONNECT_EXTENSION_INTERVAL); - auto callback = [reminder, times]() { ReminderDataManager::AsyncStartExtensionAbility(reminder, times); }; + auto callback = [reminder, times, type]() { + ReminderDataManager::AsyncStartExtensionAbility(reminder, times, type); + }; serviceQueue_->submit(callback, taskAttr); } } @@ -1092,10 +1052,8 @@ void ReminderDataManager::AsyncStartExtensionAbility(const sptr void ReminderDataManager::ShowReminder(const sptr &reminder, const bool &isNeedToPlaySound, const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout) { - ANSR_LOGD("Show the reminder(Play sound: %{public}d), %{public}s", - static_cast(isNeedToPlaySound), reminder->Dump().c_str()); int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = FindNotificationBundleOption(reminderId); + sptr bundleOption = reminder->GetNotificationBundleOption(); sptr notificationRequest = reminder->GetNotificationRequest(); if (bundleOption == nullptr) { ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); @@ -1104,13 +1062,13 @@ 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())); + store_->UpdateOrInsert(reminder, bundleOption); return; } if (!IsAllowedNotify(reminder)) { ANSR_LOGE("Not allow to notify."); reminder->OnShow(false, isSysTimeChanged, false); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, bundleOption); return; } ReportSysEvent(reminder); @@ -1124,7 +1082,9 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co } // Set the notification SoundEnabled and VibrationEnabled by soltType advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - ErrCode errCode = advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + // Since Ans and reminder share a notificationRequest, there is a multi-threaded contention, + // so need to make a copy when calling the Ans interface + ErrCode errCode = PublishNotificationRequest(notificationRequest, bundleOption); if (errCode != ERR_OK) { reminder->OnShowFail(); RemoveFromShowedReminders(reminder); @@ -1139,7 +1099,7 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co } HandleSameNotificationIdShowing(reminder); } - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, bundleOption); if (isNeedToStartNext) { StartRecentReminder(); @@ -1148,12 +1108,6 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co void ReminderDataManager::UpdateNotification(const sptr &reminder, bool isSnooze) { - int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = FindNotificationBundleOption(reminderId); - if (bundleOption == nullptr) { - ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); - return; - } if (isSnooze) { reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, "snooze"); } else { @@ -1197,10 +1151,10 @@ void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) StopTimerLocked(TimerType::ALERTING_TIMER); } reminder->OnSnooze(); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); // 2) Show the notification dialog in the systemUI - sptr bundleOption = FindNotificationBundleOption(reminderId); + sptr bundleOption = reminder->GetNotificationBundleOption(); sptr notificationRequest = reminder->GetNotificationRequest(); if (bundleOption == nullptr) { ANSR_LOGW("snoozeReminder, invalid bundle option"); @@ -1214,7 +1168,9 @@ void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) } // Set the notification SoundEnabled and VibrationEnabled by soltType advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + // Since Ans and reminder share a notificationRequest, there is a multi-threaded contention, + // so need to make a copy when calling the Ans interface + PublishNotificationRequest(notificationRequest, bundleOption); StartRecentReminder(); } @@ -1234,14 +1190,14 @@ void ReminderDataManager::StartRecentReminder() { std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); activeReminder_->OnStop(); - store_->UpdateOrInsert(activeReminder_, FindNotificationBundleOption(activeReminderId_)); + store_->UpdateOrInsert(activeReminder_, activeReminder_->GetNotificationBundleOption()); } StopTimerLocked(TimerType::TRIGGER_TIMER); } ANSR_LOGI("Start recent reminder"); StartTimerLocked(reminder, TimerType::TRIGGER_TIMER); reminder->OnStart(); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); } void ReminderDataManager::StopAlertingReminder(const sptr &reminder) @@ -1266,13 +1222,7 @@ std::string ReminderDataManager::Dump() const if ((*it)->IsExpired()) { continue; } - int32_t reminderId = (*it)->GetReminderId(); - auto mit = notificationBundleOptionMap_.find(reminderId); - if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Dump get notificationBundleOption(reminderId=%{public}d) fail", reminderId); - continue; - } - std::string bundleName = mit->second->GetBundleName(); + std::string bundleName = (*it)->GetBundleName(); auto val = bundleNameMap.find(bundleName); if (val == bundleNameMap.end()) { std::vector> reminders; @@ -1332,12 +1282,6 @@ sptr ReminderDataManager::GetRecentReminderLocked() } int32_t reminderId = (*it)->GetReminderId(); ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); - auto mit = notificationBundleOptionMap_.find(reminderId); - if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", reminderId); - } else { - notificationBundleOptionMap_.erase(mit); - } it = reminderVector_.erase(it); totalCount_--; store_->Delete(reminderId); @@ -1349,20 +1293,34 @@ void ReminderDataManager::HandleImmediatelyShow( std::vector> &showImmediately, bool isSysTimeChanged) { bool isAlerting = false; + std::unordered_map limits; + int32_t totalCount = 0; for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { + if ((*it)->IsShowing()) { + continue; + } + if (!CheckShowLimit(limits, totalCount, (*it))) { + std::lock_guard lock(ReminderDataManager::MUTEX); + (*it)->OnShow(false, isSysTimeChanged, false); + store_->UpdateOrInsert((*it), (*it)->GetNotificationBundleOption()); + continue; + } if (((*it)->GetRingDuration() > 0) && !isAlerting) { + std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder((*it), true, false, isSysTimeChanged, true); isAlerting = true; } else { + std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder((*it), false, false, isSysTimeChanged, false); } } } -void ReminderDataManager::HandleExtensionReminder(std::vector>& extensionReminders) +void ReminderDataManager::HandleExtensionReminder(std::vector>& extensionReminders, + const int8_t type) { for (auto& reminder : extensionReminders) { - ReminderDataManager::AsyncStartExtensionAbility(reminder, CONNECT_EXTENSION_MAX_RETRY_TIMES); + ReminderDataManager::AsyncStartExtensionAbility(reminder, CONNECT_EXTENSION_MAX_RETRY_TIMES, type); } } @@ -1382,10 +1340,10 @@ sptr ReminderDataManager::HandleRefreshReminder(const uint8_t & if (triggerTimeBefore != triggerTimeAfter || reminder->GetReminderId() == alertingReminderId_) { CloseReminder(reminder, true); } - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); return nullptr; } - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); return reminder; } @@ -1395,8 +1353,8 @@ 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()) { + sptr option1 = reminder->GetNotificationBundleOption(); + if (option1 == nullptr) { ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", curReminderId); return; } @@ -1409,18 +1367,18 @@ void ReminderDataManager::HandleSameNotificationIdShowing(const sptrIsShowing()) { continue; } - sptr bundleOption = FindNotificationBundleOption(tmpId); + sptr bundleOption = (*it)->GetNotificationBundleOption(); if (bundleOption == nullptr) { ANSR_LOGW("Get notificationBundleOption(reminderId=%{public}d) fail", tmpId); continue; } - if (notificationId == (*it)->GetNotificationId() && IsBelongToSameApp(bundleOption, mit->second)) { + if (notificationId == (*it)->GetNotificationId() && IsBelongToSameApp(bundleOption, option1)) { if ((*it)->IsAlerting()) { StopAlertingReminder(*it); } (*it)->OnSameNotificationIdCovered(); RemoveFromShowedReminders(*it); - store_->UpdateOrInsert((*it), FindNotificationBundleOption((*it)->GetReminderId())); + store_->UpdateOrInsert((*it), bundleOption); } } } @@ -1433,7 +1391,7 @@ void ReminderDataManager::Init(bool isFromBootComplete) std::vector> extensionReminders; CheckReminderTime(immediatelyReminders, extensionReminders); HandleImmediatelyShow(immediatelyReminders, false); - HandleExtensionReminder(extensionReminders); + HandleExtensionReminder(extensionReminders, REISSUE_CALLBACK); StartRecentReminder(); } if (IsReminderAgentReady()) { @@ -1498,15 +1456,8 @@ void ReminderDataManager::CheckReminderTime(std::vector>& void ReminderDataManager::InitUserId() { - std::vector activeUserId; - AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); - if (activeUserId.size() > 0) { - currentUserId_ = activeUserId[0]; - ANSR_LOGD("Init user id=%{private}d", currentUserId_); - } else { - currentUserId_ = MAIN_USER_ID; - ANSR_LOGE("Failed to get active user id."); - } + currentUserId_ = MAIN_USER_ID; + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(currentUserId_); } bool ReminderDataManager::RegisterConfigurationObserver() @@ -1549,14 +1500,13 @@ bool ReminderDataManager::IsAllowedNotify(const sptr &reminder) if (reminder == nullptr) { return false; } - int32_t reminderId = reminder->GetReminderId(); - auto mit = notificationBundleOptionMap_.find(reminderId); - if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); + auto option = reminder->GetNotificationBundleOption(); + if (option == nullptr) { + ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminder->GetReminderId()); return false; } bool isAllowed = false; - ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(mit->second, isAllowed); + ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(option, isAllowed); if (errCode != ERR_OK) { ANSR_LOGE("Failed to call IsSpecialBundleAllowedNotify, errCode=%{public}d", errCode); return false; @@ -1575,7 +1525,7 @@ bool ReminderDataManager::CheckIsSameApp(const sptr &reminder, std::string bundleName = reminder->GetCreatorBundleName(); int32_t uid = reminder->GetCreatorUid(); if (uid == -1) { - uid = ReminderRequest::GetUid(reminder->GetUserId(), bundleName); + uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, reminder->GetUserId()); } return bundleName == other->GetBundleName() && uid == other->GetUid(); } @@ -1586,7 +1536,11 @@ bool ReminderDataManager::IsBelongToSameApp(const sptr int32_t uidSrc = bundleOption->GetUid(); int32_t uidTar = other->GetUid(); bool result = uidSrc == uidTar; - result = result && (ReminderRequest::GetUserId(uidSrc) == ReminderRequest::GetUserId(uidTar)); + int32_t userIdSrc = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidSrc, userIdSrc); + int32_t userIdTar = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidTar, userIdTar); + result = result && (userIdSrc == userIdTar); result = result && (bundleOption->GetBundleName() == other->GetBundleName()); return result; } @@ -1605,13 +1559,7 @@ void ReminderDataManager::LoadReminderFromDb() } bundleOption->SetBundleName((*it)->GetBundleName()); bundleOption->SetUid((*it)->GetUid()); - int32_t reminderId = (*it)->GetReminderId(); - auto ret = notificationBundleOptionMap_.insert( - std::pair>(reminderId, bundleOption)); - if (!ret.second) { - ANSR_LOGE("Containers add to map error"); - continue; - } + (*it)->SetNotificationBundleOption(bundleOption); } totalCount_ = static_cast(reminderVector_.size()); ReminderRequest::GLOBAL_ID = store_->GetMaxId() + 1; @@ -1661,19 +1609,32 @@ void ReminderDataManager::PlaySoundAndVibration(const sptr &rem return; } } - std::string defaultPath; - if (access(DEFAULT_REMINDER_SOUND_1.c_str(), F_OK) == 0) { - defaultPath = "file:/" + DEFAULT_REMINDER_SOUND_1; + std::string customRingUri = reminder->GetCustomRingUri(); + if (customRingUri.empty()) { + // use default ring + std::string defaultPath; + if (access(DEFAULT_REMINDER_SOUND_1.c_str(), F_OK) == 0) { + defaultPath = "file:/" + DEFAULT_REMINDER_SOUND_1; + } else { + defaultPath = "file:/" + GetFullPath(DEFAULT_REMINDER_SOUND_2); + } + Uri defaultSound(defaultPath); + soundPlayer_->SetSource(defaultSound.GetSchemeSpecificPart()); + ANSR_LOGI("Play default sound."); } else { - defaultPath = "file:/" + GetFullPath(DEFAULT_REMINDER_SOUND_2); - } - std::string ringUri = GetCustomRingUri(reminder); - Uri reminderSound(ringUri); - Uri defaultSound(defaultPath); - Uri soundUri = ringUri.empty() ? defaultSound : reminderSound; - std::string uri = soundUri.GetSchemeSpecificPart(); - ANSR_LOGD("uri:%{public}s", uri.c_str()); - soundPlayer_->SetSource(uri); + Global::Resource::ResourceManager::RawFileDescriptor desc; + if (GetCustomRingFileDesc(reminder, desc)) { + soundPlayer_->SetSource(desc.fd, desc.offset, desc.length); + } + ANSR_LOGI("Play custom sound, reminderId:[%{public}d].", reminder->GetReminderId()); + } + constexpr int32_t STREAM_ALARM = 4; + constexpr int32_t DEFAULT_VALUE = 0; // CONTENT_UNKNOWN + Media::Format format; + (void)format.PutIntValue(Media::PlayerKeys::CONTENT_TYPE, DEFAULT_VALUE); + (void)format.PutIntValue(Media::PlayerKeys::STREAM_USAGE, STREAM_ALARM); + (void)format.PutIntValue(Media::PlayerKeys::RENDERER_FLAG, DEFAULT_VALUE); + soundPlayer_->SetParameter(format); soundPlayer_->SetLooping(true); soundPlayer_->PrepareAsync(); soundPlayer_->Play(); @@ -1688,7 +1649,7 @@ std::string ReminderDataManager::GetSoundUri(const sptr &remind ANSR_LOGE("Ans instance is null."); return uri.GetSchemeSpecificPart(); } - sptr bundle = FindNotificationBundleOption(reminder->GetReminderId()); + sptr bundle = reminder->GetNotificationBundleOption(); std::vector> slots; ErrCode errCode = advancedNotificationService_->GetSlotsByBundle(bundle, slots); if (errCode != ERR_OK) { @@ -1726,6 +1687,12 @@ void ReminderDataManager::StopSoundAndVibration(const sptr &rem if (soundPlayer_ == nullptr) { ANSR_LOGW("Sound player is null"); } else { + std::string customRingUri = reminder->GetCustomRingUri(); + if (customRingUri.empty()) { + ANSR_LOGI("Stop default sound."); + } else { + CloseCustomRingFileDesc(reminder->GetReminderId(), customRingUri); + } soundPlayer_->Stop(); soundPlayer_->Release(); soundPlayer_ = nullptr; @@ -1777,13 +1744,6 @@ void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId) ++it; } } - auto it = notificationBundleOptionMap_.find(reminderId); - if (it == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", reminderId); - } else { - ANSR_LOGD("Containers(map) remove. reminderId=%{public}d", reminderId); - notificationBundleOptionMap_.erase(it); - } } void ReminderDataManager::StartTimerLocked(const sptr &reminderRequest, TimerType type) @@ -1901,15 +1861,18 @@ void ReminderDataManager::StopTimer(TimerType type) void ReminderDataManager::ResetStates(TimerType type) { + uint64_t timerId = 0; switch (type) { case TimerType::TRIGGER_TIMER: { ANSR_LOGD("ResetStates(activeReminderId, timerId(next triggerTime))"); + timerId = timerId_; timerId_ = 0; activeReminderId_ = -1; break; } case TimerType::ALERTING_TIMER: { ANSR_LOGD("ResetStates(alertingReminderId, timeId(alerting time out))"); + timerId = timerIdAlerting_; timerIdAlerting_ = 0; alertingReminderId_ = -1; break; @@ -1919,6 +1882,14 @@ void ReminderDataManager::ResetStates(TimerType type) break; } } + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr) { + ANSR_LOGE("Failed to destroy timer due to get TimeServiceClient is null."); + return; + } + if (timerId != 0) { + timer->DestroyTimer(timerId); + } } void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &want) @@ -1929,6 +1900,10 @@ void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &wa ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); return; } + if (!reminder->IsSystemApp()) { + ANSR_LOGI("Custom button click, is not system app"); + return; + } CloseReminder(reminder, false); UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CUSTOM); std::string buttonPkgName = want.GetStringParam("PkgName"); @@ -1941,7 +1916,8 @@ void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &wa if (client == nullptr) { return; } - int32_t result = client->StartAbility(abilityWant); + uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); + int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); if (result != 0) { ANSR_LOGE("Start ability failed, result = %{public}d", result); return; @@ -1958,8 +1934,6 @@ void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) return; } CloseReminder(reminder, true); - UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); - CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); StartRecentReminder(); auto wantInfo = reminder->GetWantAgentInfo(); @@ -1972,7 +1946,7 @@ void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) abilityWant.SetElement(element); abilityWant.SetUri(wantInfo->uri); abilityWant.SetParams(wantInfo->parameters); - int32_t appIndex = ReminderRequest::GetAppIndex(reminder->GetUid()); + int32_t appIndex = BundleManagerHelper::GetInstance()->GetAppIndexByUid(reminder->GetUid()); abilityWant.SetParam("ohos.extra.param.key.appCloneIndex", appIndex); auto client = AppExecFwk::AbilityManagerClient::GetInstance(); @@ -1980,18 +1954,26 @@ void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) ANSR_LOGE("start ability failed, due to ability mgr client is nullptr."); return; } - int32_t result = client->StartAbility(abilityWant); + uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); + int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); if (result != 0) { ANSR_LOGE("Start ability failed, result = %{public}d", result); } } -std::shared_ptr ReminderDataManager::GetBundleResMgr( - const AppExecFwk::BundleInfo &bundleInfo) +std::shared_ptr ReminderDataManager::GetResourceMgr(const std::string& bundleName, + const int32_t uid) { + AppExecFwk::BundleInfo bundleInfo; + if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, + AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, uid, bundleInfo)) { + ANSR_LOGE("GetBundleInfo[%{public}s][%{public}d] fail.", bundleName.c_str(), uid); + return nullptr; + } + // obtains the resource manager std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); if (!resourceManager) { - ANSR_LOGE("create resourceManager failed."); + ANSR_LOGE("CreateResourceManager fail."); return nullptr; } // obtains the resource path. @@ -2000,9 +1982,8 @@ std::shared_ptr ReminderDataManager::GetBundl if (moduleResPath.empty()) { continue; } - ANSR_LOGD("GetBundleResMgr, moduleResPath: %{private}s", moduleResPath.c_str()); if (!resourceManager->AddResource(moduleResPath.c_str())) { - ANSR_LOGW("GetBundleResMgr AddResource failed"); + ANSR_LOGW("AddResource fail."); } } // obtains the current system language. @@ -2014,51 +1995,55 @@ std::shared_ptr ReminderDataManager::GetBundl return resourceManager; } -void ReminderDataManager::UpdateReminderLanguage(const sptr &reminder) +void ReminderDataManager::UpdateReminderLanguageLocked(const int32_t uid, + const std::vector>& reminders) { // obtains the bundle info by bundle name - const std::string bundleName = reminder->GetBundleName(); - AppExecFwk::BundleInfo bundleInfo; - if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, - AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, reminder->GetUid(), bundleInfo)) { - ANSR_LOGE("Get reminder request[%{public}d][%{public}s] bundle info failed.", - reminder->GetReminderId(), bundleName.c_str()); + if (reminders.empty()) { return; } + + std::string bundleName = reminders[0]->GetBundleName(); // obtains the resource manager - auto resourceMgr = GetBundleResMgr(bundleInfo); + auto resourceMgr = GetResourceMgr(bundleName, uid); if (resourceMgr == nullptr) { ANSR_LOGE("Get reminder request[%{public}d][%{public}s] resource manager failed.", - reminder->GetReminderId(), bundleName.c_str()); + uid, bundleName.c_str()); return; } // update action button title - reminder->OnLanguageChange(resourceMgr); -} - -void ReminderDataManager::UpdateReminderLanguageLocked(const sptr &reminder) -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - UpdateReminderLanguage(reminder); + for (auto reminder : reminders) { + std::lock_guard lock(ReminderDataManager::MUTEX); + reminder->OnLanguageChange(resourceMgr); + } } void ReminderDataManager::OnLanguageChanged() { - ANSR_LOGI("System language config changed."); + ANSR_LOGI("System language config changed start."); + std::unordered_map>> reminders; { std::lock_guard lock(ReminderDataManager::MUTEX); for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - UpdateReminderLanguage(*it); + if ((*it)->IsExpired() || (*it)->GetTriggerTimeInMilli() == 0) { + continue; + } + reminders[(*it)->GetUid()].push_back((*it)); } } + for (auto& each : reminders) { + UpdateReminderLanguageLocked(each.first, each.second); + } std::vector> showedReminder; { std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); showedReminder = showedReminderVector_; } for (auto it = showedReminder.begin(); it != showedReminder.end(); ++it) { + std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder((*it), false, false, false, false); } + ANSR_LOGI("System language config changed end."); } void ReminderDataManager::OnRemoveAppMgr() @@ -2101,42 +2086,46 @@ void ReminderDataManager::CheckNeedNotifyStatus(const sptr &rem if (bundleName.empty()) { return; } - ANS_LOGI("notify bundleName is: %{public}s", bundleName.c_str()); - // get foreground application - std::vector apps; + bool isRunning = false; { std::lock_guard lock(appMgrMutex_); if (!ConnectAppMgr()) { return; } - if (appMgrProxy_->GetForegroundApplications(apps) != ERR_OK) { - ANS_LOGW("get foreground application failed"); - return; - } + isRunning = appMgrProxy_->GetAppRunningStateByBundleName(bundleName); + } + if (!isRunning) { + return; } - // notify application - for (auto &eachApp : apps) { - if (eachApp.bundleName != bundleName) { - continue; - } - EventFwk::Want want; - // common event not add COMMON_EVENT_REMINDER_STATUS_CHANGE, Temporary use of string - want.SetAction("usual.event.REMINDER_STATUS_CHANGE"); - EventFwk::CommonEventData eventData(want); + EventFwk::Want want; + // common event not add COMMON_EVENT_REMINDER_STATUS_CHANGE, Temporary use of string + want.SetAction("usual.event.REMINDER_STATUS_CHANGE"); + EventFwk::CommonEventData eventData(want); - std::string data; - data.append(std::to_string(static_cast(buttonType))).append(","); - data.append(std::to_string(reminder->GetReminderId())); - eventData.SetData(data); + std::string data; + data.append(std::to_string(static_cast(buttonType))).append(","); + data.append(std::to_string(reminder->GetReminderId())); + eventData.SetData(data); - EventFwk::CommonEventPublishInfo info; - info.SetBundleName(bundleName); - if (EventFwk::CommonEventManager::PublishCommonEvent(eventData, info)) { - ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str()); - } - break; + EventFwk::CommonEventPublishInfo info; + info.SetBundleName(bundleName); + if (EventFwk::CommonEventManager::PublishCommonEvent(eventData, info)) { + ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str()); + } +} + +ErrCode ReminderDataManager::PublishNotificationRequest(sptr& request, + const sptr& bundleOption) +{ + MessageParcel data; + data.WriteParcelable(request); + sptr newRequest = data.ReadParcelable(); + if (newRequest == nullptr) { + ANSR_LOGE("NotificationRequest is nullptr"); + return ERR_REMINDER_INVALID_PARAM; } + return advancedNotificationService_->PublishPreparedNotification(newRequest, bundleOption); } } } diff --git a/services/ans/src/reminder_data_manager_inner.cpp b/services/ans/src/reminder_data_manager_inner.cpp index 8f2c301175fd823614f0ceb31c305a3b1193f594..cef2dd13ccc1d6f5d8edb32e11fb64ff8c6a80bd 100644 --- a/services/ans/src/reminder_data_manager_inner.cpp +++ b/services/ans/src/reminder_data_manager_inner.cpp @@ -52,6 +52,19 @@ namespace OHOS { namespace Notification { +namespace { +constexpr int32_t ALL_SA_READY_FLAG = 2; // bundle service and ability service ready. +// The maximum number of applications that can be displayed at a time +constexpr int32_t ONE_HAP_MAX_NUMBER_SHOW_AT_ONCE = 10; +// The maximum number of system that can be displayed at a time +constexpr int32_t TOTAL_MAX_NUMBER_SHOW_AT_ONCE = 500; +} + +bool ReminderDataManager::IsSystemReady() +{ + return saReadyFlag_ >= ALL_SA_READY_FLAG; +} + bool ReminderDataManager::IsActionButtonDataShareValid(const sptr& reminder, const uint32_t callerTokenId) { @@ -97,6 +110,49 @@ void ReminderDataManager::HandleAutoDeleteReminder(const int32_t notificationId, StartRecentReminder(); } +void ReminderDataManager::OnBundleMgrServiceStart() +{ + saReadyFlag_.fetch_add(1); +} + +void ReminderDataManager::OnAbilityMgrServiceStart() +{ + saReadyFlag_.fetch_add(1); +} + +bool ReminderDataManager::GetCustomRingFileDesc(const sptr& reminder, + Global::Resource::ResourceManager::RawFileDescriptor& desc) +{ + // obtains the resource manager + std::lock_guard locker(resourceMutex_); + soundResource_ = GetResourceMgr(reminder->GetBundleName(), reminder->GetUid()); + if (soundResource_ == nullptr) { + ANSR_LOGE("GetResourceMgr fail."); + return false; + } + auto result = soundResource_->GetRawFileDescriptor(reminder->GetCustomRingUri(), desc); + if (result != Global::Resource::SUCCESS) { + ANSR_LOGE("GetRawFileDescriptor fail[%{public}d].", static_cast(result)); + return false; + } + return true; +} + +void ReminderDataManager::CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri) +{ + std::lock_guard locker(resourceMutex_); + if (soundResource_ == nullptr) { + ANSR_LOGW("ResourceManager is nullptr."); + return; + } + auto result = soundResource_->CloseRawFileDescriptor(customRingUri); + if (result != Global::Resource::SUCCESS) { + ANSR_LOGW("CloseRawFileDescriptor fail[%{public}d]", static_cast(result)); + } + ANSR_LOGI("Stop custom sound, reminderId:[%{public}d].", reminderId); + soundResource_ = nullptr; +} + void ReminderDataManager::ReportSysEvent(const sptr& reminder) { #ifdef HAS_HISYSEVENT_PART @@ -108,9 +164,32 @@ void ReminderDataManager::ReportSysEvent(const sptr& reminder) uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); int32_t ringTime = static_cast(reminder->GetRingDuration()); HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::NOTIFICATION, event, HiviewDFX::HiSysEvent::EventType::STATISTIC, - "PID", 0, "UID", uid, "NAME", bundleName, "TYPE", type, "repeat", repeat, "TRIGGER_TIME", triggerTime, + "UID", uid, "NAME", bundleName, "TYPE", type, "REPEAT", repeat, "TRIGGER_TIME", triggerTime, "RING_TIME", ringTime); #endif } + +bool ReminderDataManager::CheckShowLimit(std::unordered_map& limits, int32_t& totalCount, + sptr& reminder) +{ + if (totalCount > TOTAL_MAX_NUMBER_SHOW_AT_ONCE) { + ANSR_LOGW("The maximum number of displays that can be displayed at a time has been reached."); + return false; + } + ++totalCount; + std::string key = std::to_string(reminder->GetUid()) + "_" + std::to_string(reminder->GetTriggerTimeInMilli()); + auto iter = limits.find(key); + if (iter == limits.end()) { + limits[key] = 1; + return true; + } + if (iter->second > ONE_HAP_MAX_NUMBER_SHOW_AT_ONCE) { + ANSR_LOGW("The maximum number of displays that can be displayed in a single app[%{public}s] has been reached", + reminder->GetBundleName().c_str()); + return false; + } + ++iter->second; + return true; +} } } diff --git a/services/ans/src/reminder_event_manager.cpp b/services/ans/src/reminder_event_manager.cpp index 6211e82d1f740d271dfa54479d238517ea76d32a..6b8b629b11e79d4f062e114b4822ca4c2b2cd9ec 100644 --- a/services/ans/src/reminder_event_manager.cpp +++ b/services/ans/src/reminder_event_manager.cpp @@ -20,6 +20,7 @@ #include "bundle_mgr_interface.h" #include "common_event_manager.h" #include "common_event_support.h" +#include "bundle_manager_helper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" @@ -99,6 +100,13 @@ void ReminderEventManager::SubscribeSystemAbility(std::shared_ptr abilityMgrStatusListener + = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); + if (abilityMgrStatusListener == nullptr) { + ANSR_LOGE("Failed to create abilityMgrStatusListener due to no memory."); + return; + } sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgrProxy == nullptr) { @@ -113,6 +121,10 @@ void ReminderEventManager::SubscribeSystemAbility(std::shared_ptrSubscribeSystemAbility(ABILITY_MGR_SERVICE_ID, abilityMgrStatusListener); + if (ret != ERR_OK) { + ANSR_LOGE("subscribe system ability id: %{public}d failed", ABILITY_MGR_SERVICE_ID); + } } ReminderEventManager::ReminderEventSubscriber::ReminderEventSubscriber( @@ -155,7 +167,7 @@ void ReminderEventManager::ReminderEventCustomSubscriber::OnReceiveEvent(const E return; } if (action == ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION) { - reminderDataManager_->CloseReminder(want, false); + reminderDataManager_->CloseReminder(want, false, false); return; } if (action == ReminderRequest::REMINDER_EVENT_CLICK_ALERT) { @@ -228,7 +240,7 @@ sptr ReminderEventManager::ReminderEventSubscriber::Ge OHOS::AppExecFwk::ElementName ele = want.GetElement(); std::string bundleName = ele.GetBundleName(); int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); - int32_t uid = ReminderRequest::GetUid(userId, bundleName); + int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId); ANSR_LOGD("bundleName=%{public}s, userId=%{private}d, uid=%{public}d", bundleName.c_str(), userId, uid); sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); if (bundleOption == nullptr) { @@ -250,11 +262,15 @@ void ReminderEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility switch (systemAbilityId) { case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: ANSR_LOGD("OnAddSystemAbilityInner: BUNDLE_MGR_SERVICE_SYS_ABILITY"); - reminderDataManager_->OnServiceStart(); + reminderDataManager_->OnBundleMgrServiceStart(); break; case APP_MGR_SERVICE_ID: ANSR_LOGD("OnAddSystemAbilityInner: APP_MGR_SERVICE"); break; + case ABILITY_MGR_SERVICE_ID: + ANSR_LOGD("OnAddSystemAbilityInner ABILITY_MGR_SERVICE_ID"); + reminderDataManager_->OnAbilityMgrServiceStart(); + break; default: break; } @@ -272,6 +288,9 @@ void ReminderEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbil ANSR_LOGD("OnRemoveSystemAbilityInner: APP_MGR_SERVICE"); reminderDataManager_->OnRemoveAppMgr(); break; + case ABILITY_MGR_SERVICE_ID: + ANSR_LOGD("OnRemoveSystemAbilityInner ABILITY_MGR_SERVICE_ID"); + break; default: break; } @@ -293,7 +312,8 @@ void ReminderEventManager::ReminderNotificationSubscriber::OnCanceled( const std::shared_ptr ¬ification, const std::shared_ptr &sortingMap, int deleteReason) { - if (deleteReason != NotificationConstant::APP_CANCEL_REASON_DELETE) { + // Note: Don't modify param notification + if (deleteReason != NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE) { return; } if (notification == nullptr) { diff --git a/frameworks/ans/src/reminder_store.cpp b/services/ans/src/reminder_store.cpp similarity index 94% rename from frameworks/ans/src/reminder_store.cpp rename to services/ans/src/reminder_store.cpp index e75be5b9c953366d26b659e60bed28b29a288e84..74e08b9fc442b19d0910115270c07f7223fa4eac 100644 --- a/frameworks/ans/src/reminder_store.cpp +++ b/services/ans/src/reminder_store.cpp @@ -20,13 +20,14 @@ #include #include -#include "fa_ability_context.h" +#include "ability_context.h" #include "ans_log_wrapper.h" #include "reminder_table.h" #include "reminder_table_old.h" #include "reminder_request_alarm.h" #include "reminder_request_timer.h" #include "reminder_request_calendar.h" +#include "reminder_store_strategy.h" namespace OHOS { namespace Notification { @@ -177,14 +178,17 @@ std::vector> ReminderStore::ReminderStoreDataCallBack::Get switch (reminderType) { case (static_cast(ReminderRequest::ReminderType::TIMER)): { reminderReq = new (std::nothrow) ReminderRequestTimer(reminderId); + ReminderTimerStrategy::RecoverFromOldVersion(reminderReq, queryResult); break; } case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { reminderReq = new (std::nothrow) ReminderRequestCalendar(reminderId); + ReminderCalendarStrategy::RecoverFromOldVersion(reminderReq, queryResult); break; } case (static_cast(ReminderRequest::ReminderType::ALARM)): { reminderReq = new (std::nothrow) ReminderRequestAlarm(reminderId); + ReminderAlarmStrategy::RecoverFromOldVersion(reminderReq, queryResult); break; } default: { @@ -192,7 +196,6 @@ std::vector> ReminderStore::ReminderStoreDataCallBack::Get } } if (reminderReq != nullptr) { - reminderReq->RecoverFromOldVersion(queryResult); reminders.push_back(reminderReq); } queryResult->IsAtLastRow(isLastRow); @@ -211,7 +214,7 @@ void ReminderStore::ReminderStoreDataCallBack::InsertNewReminders(NativeRdb::Rdb } bundleOption->SetBundleName(reminder->GetBundleName()); NativeRdb::ValuesBucket baseValues; - ReminderRequest::AppendValuesBucket(reminder, bundleOption, baseValues, true); + ReminderStrategy::AppendValuesBucket(reminder, baseValues, true); store.BeginTransaction(); // insert reminder_base @@ -228,15 +231,15 @@ void ReminderStore::ReminderStoreDataCallBack::InsertNewReminders(NativeRdb::Rdb rowId = STATE_FAIL; switch (reminder->GetReminderType()) { case ReminderRequest::ReminderType::CALENDAR: - ReminderRequestCalendar::AppendValuesBucket(reminder, bundleOption, values); + ReminderCalendarStrategy::AppendValuesBucket(reminder, values); ret = store.Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); break; case ReminderRequest::ReminderType::ALARM: - ReminderRequestAlarm::AppendValuesBucket(reminder, bundleOption, values); + ReminderAlarmStrategy::AppendValuesBucket(reminder, values); ret = store.Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); break; case ReminderRequest::ReminderType::TIMER: - ReminderRequestTimer::AppendValuesBucket(reminder, bundleOption, values); + ReminderTimerStrategy::AppendValuesBucket(reminder, values); ret = store.Insert(rowId, ReminderTimerTable::TABLE_NAME, values); break; default: @@ -596,7 +599,7 @@ int32_t ReminderStore::Insert( } int64_t rowId = STATE_FAIL; NativeRdb::ValuesBucket baseValues; - ReminderRequest::AppendValuesBucket(reminder, bundleOption, baseValues); + ReminderStrategy::AppendValuesBucket(reminder, baseValues); rdbStore_->BeginTransaction(); // insert reminder_base @@ -613,17 +616,17 @@ int32_t ReminderStore::Insert( rowId = STATE_FAIL; switch (reminder->GetReminderType()) { case ReminderRequest::ReminderType::CALENDAR: { - ReminderRequestCalendar::AppendValuesBucket(reminder, bundleOption, values); + ReminderCalendarStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); break; } case ReminderRequest::ReminderType::ALARM: { - ReminderRequestAlarm::AppendValuesBucket(reminder, bundleOption, values); + ReminderAlarmStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); break; } case ReminderRequest::ReminderType::TIMER: { - ReminderRequestTimer::AppendValuesBucket(reminder, bundleOption, values); + ReminderTimerStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Insert(rowId, ReminderTimerTable::TABLE_NAME, values); break; } @@ -653,7 +656,7 @@ int32_t ReminderStore::Update( } int32_t rowId = STATE_FAIL; NativeRdb::ValuesBucket baseValues; - ReminderRequest::AppendValuesBucket(reminder, bundleOption, baseValues); + ReminderStrategy::AppendValuesBucket(reminder, baseValues); std::string updateCondition = ReminderBaseTable::REMINDER_ID + " = " + std::to_string(reminder->GetReminderId()); @@ -674,15 +677,15 @@ int32_t ReminderStore::Update( rowId = STATE_FAIL; switch (reminder->GetReminderType()) { case ReminderRequest::ReminderType::CALENDAR: - ReminderRequestCalendar::AppendValuesBucket(reminder, bundleOption, values); + ReminderCalendarStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Update(rowId, ReminderCalendarTable::TABLE_NAME, values, updateCondition, whereArgs); break; case ReminderRequest::ReminderType::ALARM: - ReminderRequestAlarm::AppendValuesBucket(reminder, bundleOption, values); + ReminderAlarmStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Update(rowId, ReminderAlarmTable::TABLE_NAME, values, updateCondition, whereArgs); break; case ReminderRequest::ReminderType::TIMER: - ReminderRequestTimer::AppendValuesBucket(reminder, bundleOption, values); + ReminderTimerStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Update(rowId, ReminderTimerTable::TABLE_NAME, values, updateCondition, whereArgs); break; default: @@ -727,14 +730,14 @@ std::vector> ReminderStore::GetReminders(const std::string return reminders; } bool isAtLastRow = false; - queryResultSet->IsAtLastRow(isAtLastRow); - while (!isAtLastRow) { + int32_t ret = queryResultSet->IsAtLastRow(isAtLastRow); + while (ret == NativeRdb::E_OK && !isAtLastRow) { queryResultSet->GoToNextRow(); sptr reminder = BuildReminder(queryResultSet); if (reminder != nullptr) { reminders.push_back(reminder); } - queryResultSet->IsAtLastRow(isAtLastRow); + ret = queryResultSet->IsAtLastRow(isAtLastRow); } ANSR_LOGD("Size=%{public}zu", reminders.size()); return reminders; @@ -753,16 +756,19 @@ sptr ReminderStore::BuildReminder(const std::shared_ptr(ReminderRequest::ReminderType::TIMER)): { reminder = new (std::nothrow) ReminderRequestTimer(reminderId); resultSet = Query(ReminderTimerTable::TABLE_NAME, ReminderTimerTable::SELECT_COLUMNS, reminderId); + ReminderTimerStrategy::RecoverFromDb(reminder, resultBase, resultSet); break; } case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { reminder = new (std::nothrow) ReminderRequestCalendar(reminderId); resultSet = Query(ReminderCalendarTable::TABLE_NAME, ReminderCalendarTable::SELECT_COLUMNS, reminderId); + ReminderCalendarStrategy::RecoverFromDb(reminder, resultBase, resultSet); break; } case (static_cast(ReminderRequest::ReminderType::ALARM)): { reminder = new (std::nothrow) ReminderRequestAlarm(reminderId); resultSet = Query(ReminderAlarmTable::TABLE_NAME, ReminderAlarmTable::SELECT_COLUMNS, reminderId); + ReminderAlarmStrategy::RecoverFromDb(reminder, resultBase, resultSet); break; } default: { @@ -771,8 +777,6 @@ sptr ReminderStore::BuildReminder(const std::shared_ptrRecoverFromDbBase(resultBase); - reminder->RecoverFromDb(resultSet); ANSR_LOGI("BuildReminder success."); } else { ANSR_LOGW("BuildReminder fail."); diff --git a/services/ans/src/reminder_store_strategy.cpp b/services/ans/src/reminder_store_strategy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b9af4d41124fb2dc998d56571c3366f51fd1fb67 --- /dev/null +++ b/services/ans/src/reminder_store_strategy.cpp @@ -0,0 +1,649 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "reminder_store_strategy.h" + +#include "ans_log_wrapper.h" +#include "reminder_store.h" +#include "reminder_table.h" +#include "reminder_table_old.h" +#include "reminder_request_alarm.h" +#include "reminder_request_timer.h" +#include "reminder_request_calendar.h" + +namespace OHOS { +namespace Notification { +void ReminderStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket &values, const bool oldVersion) +{ + values.PutInt(ReminderBaseTable::REMINDER_ID, reminder->GetReminderId()); + values.PutString(ReminderBaseTable::PACKAGE_NAME, reminder->GetBundleName()); + values.PutInt(ReminderBaseTable::USER_ID, reminder->GetUserId()); + values.PutInt(ReminderBaseTable::UID, reminder->GetUid()); + values.PutString(ReminderBaseTable::SYSTEM_APP, reminder->IsSystemApp() ? "true" : "false"); + values.PutInt(ReminderBaseTable::REMINDER_TYPE, static_cast(reminder->GetReminderType())); + values.PutLong(ReminderBaseTable::REMINDER_TIME, reminder->GetReminderTimeInMilli()); + values.PutLong(ReminderBaseTable::TRIGGER_TIME, reminder->GetTriggerTimeInMilli()); + values.PutLong(ReminderBaseTable::TIME_INTERVAL, reminder->GetTimeInterval()); + values.PutInt(ReminderBaseTable::SNOOZE_TIMES, reminder->GetSnoozeTimes()); + values.PutInt(ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, reminder->GetSnoozeTimesDynamic()); + values.PutLong(ReminderBaseTable::RING_DURATION, reminder->GetRingDuration()); + values.PutString(ReminderBaseTable::IS_EXPIRED, reminder->IsExpired() ? "true" : "false"); + values.PutInt(ReminderBaseTable::STATE, reminder->GetState()); + values.PutString(ReminderBaseTable::ACTION_BUTTON_INFO, reminder->SerializeButtonInfo()); + values.PutString(ReminderBaseTable::CUSTOM_BUTTON_URI, reminder->GetCustomButtonUri()); + values.PutInt(ReminderBaseTable::SLOT_ID, reminder->GetSlotType()); + values.PutInt(ReminderBaseTable::SNOOZE_SLOT_ID, reminder->GetSnoozeSlotType()); + values.PutInt(ReminderBaseTable::NOTIFICATION_ID, reminder->GetNotificationId()); + values.PutString(ReminderBaseTable::TITLE, reminder->GetTitle()); + values.PutString(ReminderBaseTable::CONTENT, reminder->GetContent()); + values.PutString(ReminderBaseTable::SNOOZE_CONTENT, reminder->GetSnoozeContent()); + values.PutString(ReminderBaseTable::EXPIRED_CONTENT, reminder->GetExpiredContent()); + + if (oldVersion) { + values.PutString(ReminderBaseTable::WANT_AGENT, reminder->GetWantAgentStr()); + values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, reminder->GetMaxWantAgentStr()); + } else { + std::string wantInfoStr; + std::string maxWantInfoStr; + reminder->SerializeWantAgent(wantInfoStr, maxWantInfoStr); + values.PutString(ReminderBaseTable::WANT_AGENT, wantInfoStr); + values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, maxWantInfoStr); + } + + values.PutString(ReminderBaseTable::TAP_DISMISSED, reminder->IsTapDismissed() ? "true" : "false"); + values.PutLong(ReminderBaseTable::AUTO_DELETED_TIME, reminder->GetAutoDeletedTime()); + values.PutString(ReminderBaseTable::GROUP_ID, reminder->GetGroupId()); + values.PutString(ReminderBaseTable::CUSTOM_RING_URI, reminder->GetCustomRingUri()); + values.PutString(ReminderBaseTable::CREATOR_BUNDLE_NAME, reminder->GetCreatorBundleName()); + values.PutInt(ReminderBaseTable::CREATOR_UID, reminder->GetCreatorUid()); +} + +void ReminderStrategy::RecoverTimeFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + uint64_t reminderTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_TIME, reminderTime); + reminder->SetReminderTimeInMilli(reminderTime); + + uint64_t triggerTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TRIGGER_TIME, triggerTime); + reminder->SetTriggerTimeInMilli(triggerTime); + + uint64_t timeInterval = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TIME_INTERVAL, timeInterval); + reminder->SetTimeInterval(timeInterval); + + uint8_t snoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_TIMES, snoozeTimes); + reminder->SetSnoozeTimes(snoozeTimes); + + uint8_t dynamicSnoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::DYNAMIC_SNOOZE_TIMES, dynamicSnoozeTimes); + reminder->SetSnoozeTimesDynamic(dynamicSnoozeTimes); + + uint64_t ringDuration = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::RING_DURATION, ringDuration); + reminder->SetRingDuration(ringDuration); + + int64_t autoDeletedTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::AUTO_DELETED_TIME, autoDeletedTime); + reminder->SetAutoDeletedTime(autoDeletedTime); +} + +void ReminderStrategy::RecoverIdFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + int32_t reminderId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_ID, reminderId); + reminder->SetReminderId(reminderId); + + int32_t userId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::USER_ID, userId); + reminder->InitUserId(userId); + + int32_t uid = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::UID, uid); + reminder->InitUid(uid); + + int32_t reminderType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_TYPE, reminderType); + reminder->SetReminderType(ReminderRequest::ReminderType(reminderType)); + + int32_t slotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SLOT_ID, slotType); + reminder->SetSlotType(NotificationConstant::SlotType(slotType)); + + int32_t snoozeSlotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_SLOT_ID, snoozeSlotType); + reminder->SetSnoozeSlotType(NotificationConstant::SlotType(snoozeSlotType)); + + int32_t notificationId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::NOTIFICATION_ID, notificationId); + reminder->SetNotificationId(notificationId); + + std::string groupId; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::GROUP_ID, groupId); + reminder->SetGroupId(groupId); +} + +void ReminderStrategy::RecoverContextFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + std::string bundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::PKG_NAME, bundleName); + reminder->InitBundleName(bundleName); + + std::string title; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TITLE, title); + reminder->SetTitle(title); + + std::string content; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CONTENT, content); + reminder->SetContent(content); + + std::string snoozeContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_CONTENT, snoozeContent); + reminder->SetSnoozeContent(snoozeContent); + + std::string expiredContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::EXPIRED_CONTENT, expiredContent); + reminder->SetExpiredContent(expiredContent); + + std::string customButtonUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CUSTOM_BUTTON_URI, customButtonUri); + reminder->SetCustomButtonUri(customButtonUri); + + std::string customRingUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CUSTOM_RING_URI, customRingUri); + reminder->SetCustomRingUri(customRingUri); + + std::string creatorBundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CREATOR_BUNDLE_NAME, creatorBundleName); + reminder->InitCreatorBundleName(creatorBundleName); +} + +void ReminderStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (reminder == nullptr || resultSet == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + + ReminderStrategy::RecoverTimeFromOldVersion(reminder, resultSet); + ReminderStrategy::RecoverIdFromOldVersion(reminder, resultSet); + ReminderStrategy::RecoverContextFromOldVersion(reminder, resultSet); + + std::string isSystemApp; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SYS_APP, isSystemApp); + reminder->SetSystemApp(isSystemApp == "true" ? true : false); + + std::string isExpired; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::IS_EXPIRED, isExpired); + reminder->SetExpired(isExpired == "true" ? true : false); + + std::string actionButtons; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ACTION_BUTTON_INFO, actionButtons); + reminder->DeserializeButtonInfo(actionButtons); + + uint8_t state = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::STATE, state); + reminder->SetState(state); + + uint8_t repeatDaysOfWeek = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + reminder->SetRepeatDaysOfWeek(repeatDaysOfWeek); + + std::string wantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::AGENT, wantAgent); + reminder->SetWantAgentStr(wantAgent); + + std::string maxScreenWantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::MAX_SCREEN_AGENT, maxScreenWantAgent); + reminder->SetMaxWantAgentStr(maxScreenWantAgent); + + std::string tapDismissed; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TAP_DISMISSED, tapDismissed); + reminder->SetTapDismissed(tapDismissed == "true" ? true : false); +} + +void ReminderStrategy::RecoverTimeFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + uint64_t reminderTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_TIME, reminderTime); + reminder->SetReminderTimeInMilli(reminderTime); + + uint64_t triggerTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TRIGGER_TIME, triggerTime); + reminder->SetTriggerTimeInMilli(triggerTime); + + uint64_t timeInterval = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TIME_INTERVAL, timeInterval); + reminder->SetTimeInterval(timeInterval); + + uint8_t snoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_TIMES, snoozeTimes); + reminder->SetSnoozeTimes(snoozeTimes); + + uint8_t dynamicSnoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, dynamicSnoozeTimes); + reminder->SetSnoozeTimesDynamic(dynamicSnoozeTimes); + + uint64_t ringDuration = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::RING_DURATION, ringDuration); + reminder->SetRingDuration(ringDuration); + + int64_t autoDeletedTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::AUTO_DELETED_TIME, autoDeletedTime); + reminder->SetAutoDeletedTime(autoDeletedTime); +} + +void ReminderStrategy::RecoverIdFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + int32_t reminderId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_ID, reminderId); + reminder->SetReminderId(reminderId); + + int32_t userId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::USER_ID, userId); + reminder->InitUserId(userId); + + int32_t uid = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::UID, uid); + reminder->InitUid(uid); + + int32_t reminderType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_TYPE, reminderType); + reminder->SetReminderType(ReminderRequest::ReminderType(reminderType)); + + int32_t slotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SLOT_ID, slotType); + reminder->SetSlotType(NotificationConstant::SlotType(slotType)); + + int32_t snoozeSlotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_SLOT_ID, snoozeSlotType); + reminder->SetSnoozeSlotType(NotificationConstant::SlotType(snoozeSlotType)); + + int32_t notificationId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::NOTIFICATION_ID, notificationId); + reminder->SetNotificationId(notificationId); + + std::string groupId; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::GROUP_ID, groupId); + reminder->SetGroupId(groupId); + + int32_t creatorUid; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CREATOR_UID, creatorUid); + reminder->InitCreatorUid(creatorUid); +} + +void ReminderStrategy::RecoverContextFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + std::string bundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::PACKAGE_NAME, bundleName); + reminder->InitBundleName(bundleName); + + std::string customButtonUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CUSTOM_BUTTON_URI, customButtonUri); + reminder->SetCustomButtonUri(customButtonUri); + + std::string title; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TITLE, title); + reminder->SetTitle(title); + + std::string content; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CONTENT, content); + reminder->SetContent(content); + + std::string snoozeContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_CONTENT, snoozeContent); + reminder->SetSnoozeContent(snoozeContent); + + std::string expiredContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::EXPIRED_CONTENT, expiredContent); + reminder->SetExpiredContent(expiredContent); + + std::string customRingUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CUSTOM_RING_URI, customRingUri); + reminder->SetCustomRingUri(customRingUri); + + std::string creatorBundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CREATOR_BUNDLE_NAME, creatorBundleName); + reminder->InitCreatorBundleName(creatorBundleName); +} + +void ReminderStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (reminder == nullptr || resultSet == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverTimeFromDb(reminder, resultSet); + ReminderStrategy::RecoverIdFromDb(reminder, resultSet); + ReminderStrategy::RecoverContextFromDb(reminder, resultSet); + + uint8_t state = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::STATE, state); + reminder->SetState(state); + + std::string isSystemApp; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SYSTEM_APP, isSystemApp); + reminder->SetSystemApp(isSystemApp == "true" ? true : false); + + std::string isExpired; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::IS_EXPIRED, isExpired); + reminder->SetExpired(isExpired == "true" ? true : false); + + std::string actionButtons; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::ACTION_BUTTON_INFO, actionButtons); + reminder->DeserializeButtonInfo(actionButtons); + + reminder->InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent + std::string wantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::WANT_AGENT, wantAgent); + reminder->DeserializeWantAgent(wantAgent, 0); + + std::string maxWantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::MAX_SCREEN_WANT_AGENT, maxWantAgent); + reminder->DeserializeWantAgent(maxWantAgent, 1); + + std::string tapDismissed; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TAP_DISMISSED, tapDismissed); + reminder->SetTapDismissed(tapDismissed == "true" ? true : false); +} + +void ReminderTimerStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values) +{ + uint64_t seconds = 0; + if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + seconds = timer->GetInitInfo(); + } + values.PutInt(ReminderTimerTable::REMINDER_ID, reminder->GetReminderId()); + values.PutLong(ReminderTimerTable::TRIGGER_SECOND, seconds); + values.PutLong(ReminderTimerTable::START_DATE_TIME, 0); + values.PutLong(ReminderTimerTable::END_DATE_TIME, 0); +} + +void ReminderTimerStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); +} + +void ReminderTimerStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromDb(reminder, baseResult); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + uint64_t seconds; + ReminderStrategy::GetRdbValue(resultSet, ReminderTimerTable::TRIGGER_SECOND, seconds); + timer->SetInitInfo(seconds); + } +} + +void ReminderAlarmStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values) +{ + uint8_t hour = 0; + uint8_t minute = 0; + uint8_t repeatDaysOfWeek = 0; + if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + hour = alarm->GetHour(); + minute = alarm->GetMinute(); + repeatDaysOfWeek = alarm->GetRepeatDaysOfWeek(); + } + values.PutInt(ReminderAlarmTable::REMINDER_ID, reminder->GetReminderId()); + values.PutInt(ReminderAlarmTable::ALARM_HOUR, hour); + values.PutInt(ReminderAlarmTable::ALARM_MINUTE, minute); + values.PutInt(ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); +} + +void ReminderAlarmStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); + + if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + uint8_t hour = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ALARM_HOUR, hour); + alarm->SetHour(hour); + + uint8_t minute = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ALARM_MINUTE, minute); + alarm->SetMinute(minute); + } +} + +void ReminderAlarmStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromDb(reminder, baseResult); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + uint8_t hour = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::ALARM_HOUR, hour); + alarm->SetHour(hour); + + uint8_t minute = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::ALARM_MINUTE, minute); + alarm->SetMinute(minute); + + uint8_t repeatDaysOfWeek = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + alarm->SetRepeatDaysOfWeek(repeatDaysOfWeek); + } +} + +void ReminderCalendarStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values) +{ + uint16_t firstDesignateYear = 0; + uint8_t firstDesignateMonth = 0; + uint8_t firstDesignateDay = 0; + uint64_t dateTime = 0; + uint32_t repeatDay = 0; + uint16_t repeatMonth = 0; + uint8_t repeatDaysOfWeek = 0; + uint64_t endDateTime = 0; + uint64_t lastStartDateTime = 0; + std::string rruleWantAgent; + std::string excludeDates; + if (reminder != nullptr && reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + if (calendar != nullptr) { + repeatDay = calendar->GetRepeatDay(); + repeatMonth = calendar->GetRepeatMonth(); + firstDesignateYear = calendar->GetFirstDesignateYear(); + firstDesignateMonth = calendar->GetFirstDesignageMonth(); + firstDesignateDay = calendar->GetFirstDesignateDay(); + dateTime = calendar->GetDateTime(); + repeatDaysOfWeek = calendar->GetRepeatDaysOfWeek(); + endDateTime = calendar->GetEndDateTime(); + lastStartDateTime = calendar->GetLastStartDateTime(); + rruleWantAgent = calendar->SerializationRRule(); + excludeDates = calendar->SerializationExcludeDates(); + } + } + values.PutInt(ReminderCalendarTable::REMINDER_ID, reminder->GetReminderId()); + values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_YEAR, firstDesignateYear); + values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth); + values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_DAY, firstDesignateDay); + values.PutLong(ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); + values.PutLong(ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); + values.PutLong(ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, lastStartDateTime); + values.PutInt(ReminderCalendarTable::REPEAT_DAYS, repeatDay); + values.PutInt(ReminderCalendarTable::REPEAT_MONTHS, repeatMonth); + values.PutInt(ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + values.PutString(ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); + values.PutString(ReminderCalendarTable::EXCLUDE_DATES, excludeDates); +} + +void ReminderCalendarStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + uint32_t repeatDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_DAYS, repeatDay); + calendar->SetRepeatDay(repeatDay); + + uint16_t repeatMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_MONTHS, repeatMonth); + calendar->SetRepeatMonth(repeatMonth); + + uint16_t firstDesignateYear = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_YEAR, firstDesignateYear); + calendar->SetFirstDesignateYear(firstDesignateYear); + + uint8_t firstDesignateMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth); + calendar->SetFirstDesignageMonth(firstDesignateMonth); + + uint8_t firstDesignateDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_DAY, firstDesignateDay); + calendar->SetFirstDesignateDay(firstDesignateDay); + + uint16_t year = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_YEAR, year); + calendar->SetYear(year); + + uint8_t month = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_MONTH, month); + calendar->SetMonth(month); + + uint8_t day = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_DAY, day); + calendar->SetDay(day); + + uint8_t hour = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_HOUR, hour); + calendar->SetHour(hour); + + uint8_t minute = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_MINUTE, minute); + calendar->SetMinute(minute); + } +} + +void ReminderCalendarStrategy::RecoverTime(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + + uint16_t firstDesignateYear = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_YEAR, + firstDesignateYear); + calendar->SetFirstDesignateYear(firstDesignateYear); + + uint8_t firstDesignateMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_MONTH, + firstDesignateMonth); + calendar->SetFirstDesignageMonth(firstDesignateMonth); + + uint8_t firstDesignateDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_DAY, + firstDesignateDay); + calendar->SetFirstDesignateDay(firstDesignateDay); + + uint64_t dateTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); + calendar->SetDateTime(dateTime); + + uint64_t endDateTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); + if (endDateTime != 0 && endDateTime >= dateTime) { + calendar->SetEndDateTime(endDateTime); + } else { + calendar->SetEndDateTime(dateTime); + } + + uint64_t lastStartDateTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, + lastStartDateTime); + if (lastStartDateTime == 0) { + calendar->SetLastStartDateTime(dateTime); + } else { + calendar->SetLastStartDateTime(lastStartDateTime); + } + } +} + +void ReminderCalendarStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromDb(reminder, baseResult); + ReminderCalendarStrategy::RecoverTime(reminder, resultSet); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + + uint32_t repeatDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_DAYS, repeatDay); + calendar->SetRepeatDay(repeatDay); + + uint16_t repeatMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_MONTHS, repeatMonth); + calendar->SetRepeatMonth(repeatMonth); + + uint8_t repeatDaysOfWeek = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + calendar->SetRepeatDaysOfWeek(repeatDaysOfWeek); + + std::string rruleWantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); + calendar->DeserializationRRule(rruleWantAgent); + + std::string excludeDates; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::EXCLUDE_DATES, excludeDates); + calendar->DeserializationExcludeDates(excludeDates); + } +} +} +} \ No newline at end of file diff --git a/frameworks/ans/src/reminder_table.cpp b/services/ans/src/reminder_table.cpp similarity index 100% rename from frameworks/ans/src/reminder_table.cpp rename to services/ans/src/reminder_table.cpp diff --git a/frameworks/ans/src/reminder_table_old.cpp b/services/ans/src/reminder_table_old.cpp similarity index 100% rename from frameworks/ans/src/reminder_table_old.cpp rename to services/ans/src/reminder_table_old.cpp diff --git a/services/ans/src/report_time_info.cpp b/services/ans/src/report_time_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a427a76d846f464cf3304b605e8598f196e2b494 --- /dev/null +++ b/services/ans/src/report_time_info.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "report_timer_info.h" + +namespace OHOS { +namespace Notification { +void ReportTimerInfo::OnTrigger() +{ + ANS_LOGI("ReportTimerInfo is arrived."); + auto callBack = GetCallBack(); + if (callBack != nullptr) { + IN_PROCESS_CALL_WITHOUT_RET(callBack()); + } +} +} +} diff --git a/services/ans/src/system_dialog_connect_stb.cpp b/services/ans/src/system_dialog_connect_stb.cpp index 5ded65f491bfc38dd6fb2fefb6d72038344fcac5..3ae9a5006c8b06b622acb46ac2c23b64c6f74a92 100644 --- a/services/ans/src/system_dialog_connect_stb.cpp +++ b/services/ans/src/system_dialog_connect_stb.cpp @@ -18,10 +18,10 @@ #include "ans_log_wrapper.h" #include "ans_inner_errors.h" #include "common_event_manager.h" +#include "advanced_notification_service.h" +#include "notification_bundle_option.h" constexpr int32_t SIGNAL_NUM = 3; -constexpr int32_t REMOVE_BUNDLE_CODE = 3; -const static std::string DIALOG_CRASH_EVENT = "OnNotificationServiceDialogClicked"; namespace OHOS { namespace Notification { @@ -44,8 +44,33 @@ void SystemDialogConnectStb::OnAbilityConnectDone(const AppExecFwk::ElementName int32_t errCode = remoteObject->SendRequest(IAbilityConnection::ON_ABILITY_CONNECT_DONE, data, reply, option); ANS_LOGI("AbilityConnectionWrapperProxy::OnAbilityConnectDone result %{public}d", errCode); if (errCode != ERR_OK) { - ANS_LOGD("send Request to SytemDialog fail"); - SendRemoveBundleEvent(); + ANS_LOGE("send Request to SytemDialog fail"); + if (commandStr_.empty() || !nlohmann::json::accept(commandStr_)) { + ANS_LOGE("Invalid JSON"); + return; + } + nlohmann::json root = nlohmann::json::parse(commandStr_); + if (root.is_null() or !root.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } + if (!root.contains("bundleName") || !root.contains("bundleUid")) { + ANS_LOGE("not found jsonKey from"); + return; + } + if (!root["bundleName"].is_string() || !root["bundleUid"].is_number_integer()) { + ANS_LOGE("value type is not right"); + return; + } + std::string bundleName = root["bundleName"]; + int32_t bundleUid = root["bundleUid"]; + sptr bundleOption = new (std::nothrow) NotificationBundleOption( + bundleName, bundleUid); + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption inin fail"); + return; + } + AdvancedNotificationService::GetInstance()->RemoveEnableNotificationDialog(bundleOption); } } @@ -54,37 +79,5 @@ void SystemDialogConnectStb::OnAbilityDisconnectDone(const AppExecFwk::ElementNa { ANS_LOGI("on ability disconnected"); } - -void SystemDialogConnectStb::SendRemoveBundleEvent() -{ - if (commandStr_.empty() || !nlohmann::json::accept(commandStr_)) { - ANS_LOGW("Invaild json param"); - return; - } - nlohmann::json root = nlohmann::json::parse(commandStr_); - if (!root.contains("bundleName") || !root.contains("bundleUid")) { - ANS_LOGW("not found jsonKey from"); - return; - } - if (!root["bundleName"].is_string() || !root["bundleUid"].is_string()) { - ANS_LOGW("value type of json key from is not string"); - return; - } - EventFwk::CommonEventData commonData; - std::string bundleName = root["bundleName"]; - std::string bundleUid = root["bundleUid"]; - - EventFwk::Want want; - want.SetAction(DIALOG_CRASH_EVENT); - want.SetParam("bundleName", bundleName); - want.SetParam("bundleUid", bundleUid); - commonData.SetWant(want); - commonData.SetCode(REMOVE_BUNDLE_CODE); - commonData.SetData(bundleName); - if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) { - ANS_LOGE("Publish remove bundle failed"); - } -} - } } \ No newline at end of file diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index f382a5891bc3e40b1b4c1dfdaad738a354d50987..bf740a9c83bce87c0a518fee97d0e6019089f958 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -21,6 +21,7 @@ #include "common_event_manager.h" #include "common_event_support.h" #include "notification_preferences.h" +#include "notification_clone_manager.h" namespace OHOS { namespace Notification { @@ -60,12 +61,29 @@ sptr SystemEventObserver::GetBundleOption(AAFwk::Want { auto element = want.GetElement(); std::string bundleName = element.GetBundleName(); + int32_t appIndex = want.GetIntParam("appIndex", -1); int32_t uid = want.GetIntParam(AppExecFwk::Constants::UID, -1); sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); if (bundleOption == nullptr) { ANS_LOGE("Failed to create bundleOption."); return nullptr; } + bundleOption->SetAppIndex(appIndex); + return bundleOption; +} + +sptr SystemEventObserver::GetBundleOptionDataCleared(AAFwk::Want want) +{ + auto element = want.GetElement(); + std::string bundleName = element.GetBundleName(); + int32_t appIndex = want.GetIntParam("appIndex", -1); + int32_t uid = want.GetIntParam("ohos.aafwk.param.targetUid", -1); + sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); + if (bundleOption == nullptr) { + ANS_LOGE("Failed to create bundleOption."); + return nullptr; + } + bundleOption->SetAppIndex(appIndex); return bundleOption; } @@ -92,11 +110,17 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) } #endif } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - NotificationPreferences::GetInstance()->InitSettingFromDisturbDB(); - AdvancedNotificationService::GetInstance()->RecoverLiveViewFromDb(); + int32_t userId = data.GetCode(); + if (userId <= SUBSCRIBE_USER_INIT) { + ANS_LOGE("Illegal userId, userId[%{public}d].", userId); + return; + } + NotificationPreferences::GetInstance()->InitSettingFromDisturbDB(userId); + AdvancedNotificationService::GetInstance()->RecoverLiveViewFromDb(userId); + NotificationCloneManager::GetInstance().OnUserSwitch(userId); } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { int32_t userId = data.GetCode(); - if (userId <= DEFAULT_USER_ID) { + if (userId <= SUBSCRIBE_USER_INIT) { ANS_LOGE("Illegal userId, userId[%{public}d].", userId); return; } @@ -105,7 +129,7 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) } } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { if (callbacks_.onBundleDataCleared != nullptr) { - sptr bundleOption = GetBundleOption(want); + sptr bundleOption = GetBundleOptionDataCleared(want); if (bundleOption != nullptr) { callbacks_.onBundleDataCleared(bundleOption); } diff --git a/services/ans/src/telephony_extension_wrapper.cpp b/services/ans/src/telephony_extension_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2050c7533d32a076953801f20dfdf572d91e3505 --- /dev/null +++ b/services/ans/src/telephony_extension_wrapper.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "advanced_notification_service.h" +#include "telephony_extension_wrapper.h" +#include "notification_preferences.h" + +namespace OHOS::Notification { +const std::string EXTENTION_TELEPHONY_PATH = "libtelephony_cust_api.z.so"; +TelExtensionWrapper::TelExtensionWrapper() = default; +TelExtensionWrapper::~TelExtensionWrapper() = default; + +void TelExtensionWrapper::InitTelExtentionWrapper() +{ + telephonyCustHandle_ = dlopen(EXTENTION_TELEPHONY_PATH.c_str(), RTLD_NOW); + if (telephonyCustHandle_ == nullptr) { + ANS_LOGE("telephony extension wrapper symbol failed, error: %{public}s", dlerror()); + return; + } + + getCallerIndex_ = (GET_CALLER_INDEX)dlsym(telephonyCustHandle_, "GetCallerNumIndex"); + if (getCallerIndex_ == nullptr) { + ANS_LOGE("telephony extension wrapper getCallerIndex symbol failed, error: %{public}s", dlerror()); + return; + } + ANS_LOGI("telephony extension wrapper telephonyCustHandle_: %{public}p", telephonyCustHandle_); + ANS_LOGI("telephony extension wrapper getCallerIndex_: %{public}p", getCallerIndex_); + ANS_LOGI("telephony extension wrapper init success"); +} + +ErrCode TelExtensionWrapper::GetCallerIndex( + std::shared_ptr resultSet, std::string compNum) +{ + if (getCallerIndex_ == nullptr) { + ANS_LOGE("GetCallerIndex wrapper symbol failed"); + return -1; + } + return getCallerIndex_(resultSet, compNum); +} + +void TelExtensionWrapper::CloseTelExtentionWrapper() +{ + if (telephonyCustHandle_ != nullptr) { + dlclose(telephonyCustHandle_); + telephonyCustHandle_ = nullptr; + } +} +} // namespace OHOS::Notification \ No newline at end of file diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 5eb12e21859582ad47e153e2989fdad617c89486..f088f19bc70f7654321a4a1efa42628e0c8a0cb7 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -467,6 +467,7 @@ ohos_unittest("notification_publish_service_test") { sources = [ "${test_path}/mock/mock_tokenid_kit.cpp", + "advanced_notification_flow_control_service_test.cpp", "advanced_notification_publish_service_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", @@ -1014,6 +1015,7 @@ ohos_unittest("notification_preferences_database_branch_test") { ] sources = [ + "${services_path}/ans/src/bundle_manager_helper.cpp", "${services_path}/ans/src/common/notification_config_parse.cpp", "${services_path}/ans/src/notification_preferences_database.cpp", "${services_path}/ans/src/notification_preferences_info.cpp", diff --git a/services/ans/test/unittest/access_token_helper_test/access_token_helper_test.cpp b/services/ans/test/unittest/access_token_helper_test/access_token_helper_test.cpp index 7ab64e542f9d14c15e5c091f652f6e3f6f667b86..7cd61c13c4c35d4e6e9e4c13cabf7f2193cb7f38 100644 --- a/services/ans/test/unittest/access_token_helper_test/access_token_helper_test.cpp +++ b/services/ans/test/unittest/access_token_helper_test/access_token_helper_test.cpp @@ -141,7 +141,7 @@ HWTEST_F(AccessTokenHelperTest, CheckPermission_00100, Function | SmallTest | Le { std::string permission = ""; MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - ASSERT_EQ(stub_->CheckPermission(permission), false); + ASSERT_EQ(stub_->CheckPermission(permission), true); } } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/advanced_notification_flow_control_service_test.cpp b/services/ans/test/unittest/advanced_notification_flow_control_service_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5cdebef4766340e3e89319da4694378e5526d8e9 --- /dev/null +++ b/services/ans/test/unittest/advanced_notification_flow_control_service_test.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "advanced_notification_flow_control_service.h" + +#include "gtest/gtest.h" + +#include "ans_const_define.h" +#include "ans_inner_errors.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Notification { +namespace { + constexpr int32_t NON_SYSTEM_APP_UID = 1000; +} +class FlowControlServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void FlowControlServiceTest::SetUpTestCase() {} + +void FlowControlServiceTest::TearDownTestCase() {} + +void FlowControlServiceTest::SetUp() {} + +void FlowControlServiceTest::TearDown() {} + +/** + * @tc.number : FlowControl_00001 + * @tc.name : Test FlowControl + * @tc.desc : Test FlowControl + */ +HWTEST_F(FlowControlServiceTest, FlowControl_00001, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + sptr notification = new (std::nothrow) Notification(request); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + record->isThirdparty = false; + record->isNeedFlowCtrl = true; + ErrCode result = ERR_OK; + int32_t callingUid = DEFAULT_UID; + + // create flow control + // single app flow control test + for (int i = 0; i < MAX_CREATE_NUM_PERSECOND_PERAPP; i++) { + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, false); + } + ASSERT_EQ(result, (int)ERR_OK); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, false); + ASSERT_EQ(result, (int)ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); + + // global flow control test + int gap = MAX_CREATE_NUM_PERSECOND - MAX_CREATE_NUM_PERSECOND_PERAPP; + callingUid = NON_SYSTEM_APP_UID; + for (int i = 0; i < gap; i++) { + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, false); + } + ASSERT_EQ(result, (int)ERR_OK); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, false); + ASSERT_EQ(result, (int)ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); + + // update flow control + // single app flow control test + callingUid = DEFAULT_UID; + for (int i = 0; i < MAX_UPDATE_NUM_PERSECOND_PERAPP; i++) { + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, true); + } + ASSERT_EQ(result, (int)ERR_OK); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, true); + ASSERT_EQ(result, (int)ERR_ANS_OVER_MAX_UPDATE_PERSECOND); + + // global flow control test + gap = MAX_UPDATE_NUM_PERSECOND - MAX_UPDATE_NUM_PERSECOND_PERAPP; + callingUid = NON_SYSTEM_APP_UID; + for (int i = 0; i < gap; i++) { + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, true); + } + ASSERT_EQ(result, (int)ERR_OK); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, true); + ASSERT_EQ(result, (int)ERR_ANS_OVER_MAX_UPDATE_PERSECOND); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp b/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp index de6f6d9976788f67a05ffacf77204d08f12817e1..bb1b585d2cdefaa37808faad687723022a4fefb2 100644 --- a/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp @@ -191,10 +191,6 @@ HWTEST_F(AnsLiveViewServiceTest, GetNotificationRequestFromDb_00002, Function | { .request = request, .bundleOption = bundle}; auto ret = advancedNotificationService_->SetNotificationRequestToDb(requestDb); ASSERT_EQ(ret, (int)ERR_OK); - - AdvancedNotificationService::NotificationRequestDb requestdbTmp; - ret = advancedNotificationService_->GetNotificationRequestFromDb(request->GetKey(), requestdbTmp); - ASSERT_EQ(ret, (int)ERR_OK); } /** @@ -310,5 +306,37 @@ HWTEST_F(AnsLiveViewServiceTest, IsSaCreateSystemLiveViewAsBundle_002, Function flag = advancedNotificationService_->IsSaCreateSystemLiveViewAsBundle(record, creatorUid); ASSERT_EQ(flag, false); } + +/** + * @tc.name: HandleUpdateLiveViewNotificationTimer_001 + * @tc.desc: Test HandleUpdateLiveViewNotificationTimer + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsLiveViewServiceTest, HandleUpdateLiveViewNotificationTimer_001, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + auto slotType = NotificationConstant::SlotType::LIVE_VIEW; + request->SetSlotType(slotType); + request->SetNotificationId(1); + int32_t TYPE_CODE_DOWNLOAD = 8; + auto localLiveViewContent = std::make_shared(); + localLiveViewContent->SetType(TYPE_CODE_DOWNLOAD); + auto content = std::make_shared(localLiveViewContent); + request->SetContent(content); + int creatorUid = 3051; + request->SetCreatorUid(creatorUid); + int ownerUid = 20099999; + request->SetOwnerUid(ownerUid); + sptr bundle = new NotificationBundleOption("test", ownerUid); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + advancedNotificationService_->AddToNotificationList(record); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); + auto timer = record->notification->GetFinishTimer(); + advancedNotificationService_->HandleUpdateLiveViewNotificationTimer(ownerUid, true); + ASSERT_EQ(timer, record->notification->GetFinishTimer()); + advancedNotificationService_->HandleUpdateLiveViewNotificationTimer(ownerUid, false); + ASSERT_NE(timer, record->notification->GetFinishTimer()); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/advanced_notification_publish_service_test.cpp b/services/ans/test/unittest/advanced_notification_publish_service_test.cpp index ad5fcf14e6a6fa26c99eafa1bb06ddbd4246984d..d88ab5b12d28f53b695ff88ee21fac58c78903f1 100644 --- a/services/ans/test/unittest/advanced_notification_publish_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_publish_service_test.cpp @@ -178,6 +178,7 @@ HWTEST_F(AnsPublishServiceTest, Publish_00003, Function | SmallTest | Level1) MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); MockIsSystemApp(true); MockIsVerfyPermisson(false); + auto ret = advancedNotificationService_->Publish(label, request); ASSERT_EQ(ret, (int)ERR_OK); @@ -205,6 +206,7 @@ HWTEST_F(AnsPublishServiceTest, Publish_00004, Function | SmallTest | Level1) auto content = std::make_shared(liveContent); request->SetContent(content); RegisterPushCheck(); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); MockIsSystemApp(true); MockIsVerfyPermisson(false); @@ -243,8 +245,8 @@ HWTEST_F(AnsPublishServiceTest, Publish_00005, Function | SmallTest | Level1) auto liveContent = std::make_shared(); auto content = std::make_shared(liveContent); request->SetContent(content); - MockIsOsAccountExists(true); RegisterPushCheck(); + MockIsOsAccountExists(true); MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); MockIsSystemApp(true); MockIsVerfyPermisson(true); @@ -393,7 +395,7 @@ HWTEST_F(AnsPublishServiceTest, GetShowBadgeEnabled_00002, Function | SmallTest MockIsVerfyPermisson(true); auto ret = advancedNotificationService_->GetShowBadgeEnabled(enabled); ASSERT_EQ(ret, (int)ERR_OK); - ASSERT_EQ(enabled, false); + ASSERT_EQ(enabled, true); } /** @@ -640,11 +642,6 @@ HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00001, Function | Small MockIsSystemApp(true); MockIsVerfyPermisson(false); - ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, - NotificationConstant::DEFAULT_REASON_DELETE); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); - - MockIsVerfyPermisson(true); ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, NotificationConstant::DEFAULT_REASON_DELETE); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); @@ -684,6 +681,8 @@ HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00002, Function | Small */ HWTEST_F(AnsPublishServiceTest, NotificationSvrQueue_00001, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); advancedNotificationService_->notificationSvrQueue_ = nullptr; auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); @@ -720,6 +719,8 @@ HWTEST_F(AnsPublishServiceTest, NotificationSvrQueue_00001, Function | SmallTest */ HWTEST_F(AnsPublishServiceTest, SetDistributedEnabledByBundle_0100, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); sptr bundleOption(new NotificationBundleOption("bundleName", 1)); std::string deviceType = "testDeviceType"; @@ -768,6 +769,8 @@ HWTEST_F(AnsPublishServiceTest, SetDistributedEnabledByBundle_0300, TestSize.Lev */ HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0100, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); sptr bundleOption(new NotificationBundleOption("bundleName", 1)); std::string deviceType = "testDeviceType1111"; bool enable = true; @@ -782,6 +785,8 @@ HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0100, TestSize.Leve */ HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0200, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); sptr bundleOption(new NotificationBundleOption("bundleName", 1)); std::string deviceType = "testDeviceType"; @@ -857,7 +862,7 @@ HWTEST_F(AnsPublishServiceTest, DuplicateMsgControl_00002, Function | SmallTest request->SetAppMessageId("test1"); auto uniqueKey = request->GenerateUniqueKey(); advancedNotificationService_->uniqueKeyList_.emplace_back( - std::make_pair(std::chrono::system_clock::now(), uniqueKey)); + std::make_pair(std::chrono::steady_clock::now(), uniqueKey)); auto ret = advancedNotificationService_->DuplicateMsgControl(request); ASSERT_EQ(ret, (int)ERR_ANS_DUPLICATE_MSG); @@ -910,7 +915,7 @@ HWTEST_F(AnsPublishServiceTest, IsDuplicateMsg_00002, Function | SmallTest | Lev request->SetAppMessageId("test2"); auto uniqueKey = request->GenerateUniqueKey(); advancedNotificationService_->uniqueKeyList_.emplace_back( - std::make_pair(std::chrono::system_clock::now(), uniqueKey)); + std::make_pair(std::chrono::steady_clock::now(), uniqueKey)); auto ret = advancedNotificationService_->IsDuplicateMsg(uniqueKey); ASSERT_EQ(ret, true); @@ -929,7 +934,7 @@ HWTEST_F(AnsPublishServiceTest, RemoveExpiredUniqueKey_00001, Function | SmallTe request->SetAppMessageId("test2"); auto uniqueKey = request->GenerateUniqueKey(); advancedNotificationService_->uniqueKeyList_.emplace_back( - std::make_pair(std::chrono::system_clock::now() - std::chrono::hours(24), uniqueKey)); + std::make_pair(std::chrono::steady_clock::now() - std::chrono::hours(24), uniqueKey)); sleep(1); ASSERT_EQ(advancedNotificationService_->uniqueKeyList_.size(), 1); @@ -944,6 +949,8 @@ HWTEST_F(AnsPublishServiceTest, RemoveExpiredUniqueKey_00001, Function | SmallTe */ HWTEST_F(AnsPublishServiceTest, SetSmartReminderEnabled_0100, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); ErrCode res = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); ASSERT_EQ(res, ERR_OK); } @@ -985,6 +992,8 @@ HWTEST_F(AnsPublishServiceTest, SetSmartReminderEnabled_0300, TestSize.Level1) */ HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0100, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); bool enable = true; ErrCode result = advancedNotificationService_->IsSmartReminderEnabled("testDeviceType1111", enable); ASSERT_EQ(result, ERR_OK); @@ -997,6 +1006,8 @@ HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0100, TestSize.Level1) */ HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0200, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); ErrCode ret = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); ASSERT_EQ(ret, ERR_OK); bool enable = false; diff --git a/services/ans/test/unittest/advanced_notification_service_branch_test.cpp b/services/ans/test/unittest/advanced_notification_service_branch_test.cpp index 29e5a880939f0ca734f8b69d68e2e09942e4b987..ff07401ed9e61ec18c41309cb9ec5d7098852f34 100644 --- a/services/ans/test/unittest/advanced_notification_service_branch_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_branch_test.cpp @@ -25,6 +25,7 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "ans_subscriber_listener.h" #include "ans_ut_constant.h" #include "iremote_object.h" #include "want_agent_info.h" @@ -82,7 +83,6 @@ void AnsBranchTest::SetUp() advancedNotificationService_ = new (std::nothrow) AdvancedNotificationService(); IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); - NotificationPreferences::GetInstance()->ClearNotificationInRestoreFactorySettings(); advancedNotificationService_->CancelAll(0); MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); MockIsSystemApp(true); @@ -1074,6 +1074,8 @@ HWTEST_F(AnsBranchTest, AnsBranchTest_275000, Function | SmallTest | Level1) */ HWTEST_F(AnsBranchTest, AnsBranchTest_276000, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); MockVerifyNativeToken(true); MockGetDistributedEnableInApplicationInfo(true, 2); sptr bundleOption = new NotificationBundleOption( @@ -1189,5 +1191,35 @@ HWTEST_F(AnsBranchTest, AnsBranchTest_279002, Function | SmallTest | Level1) ASSERT_EQ(record->notification->GetFinishTimer(), NotificationConstant::INVALID_TIMER_ID); } +/** + * @tc.number : AnsBranchTest_285000 + * @tc.name : IsNeedSilentInDoNotDisturbMode_1000 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function return ERR_ANS_NON_SYSTEM_APP. + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_285000, Function | SmallTest | Level1) +{ + MockIsSystemApp(false); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType), -1); +} + +/** + * @tc.number : AnsBranchTest_286000 + * @tc.name : IsNeedSilentInDoNotDisturbMode_2000 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function return ERR_ANS_PERMISSION_DENIED. + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_286000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode( + phoneNumber, callerType), ERR_ANS_PERMISSION_DENIED); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index 38c03b4fbc8db744415df319e2af4313188ac43c..bcd5e50f41d48934596ff1ae59e3c9f4e9457513 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -14,16 +14,15 @@ */ #include "errors.h" +#include "notification_bundle_option.h" #include "notification_content.h" #include "notification_record.h" #include "notification_request.h" #include #include -#include #include #include "gtest/gtest.h" -#include #define private public @@ -306,6 +305,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03100, { const std::string localSwitch = "current"; advancedNotificationService_->ClearAllNotificationGroupInfo(localSwitch); + EXPECT_TRUE(advancedNotificationService_ != nullptr); } /** @@ -318,6 +318,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03200, const std::string key = "key"; std::shared_ptr groupInfo; advancedNotificationService_->UpdateUnifiedGroupInfo(key, groupInfo); + EXPECT_TRUE(advancedNotificationService_ != nullptr); } /** @@ -361,7 +362,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03500, int32_t id = 0; sptr bundleOption = new (std::nothrow) NotificationBundleOption(); auto ret = advancedNotificationService_->CancelAsBundleWithAgent(bundleOption, id); - ASSERT_EQ(ret, (int)ERR_ANS_NO_AGENT_SETTING); + ASSERT_EQ(ret, (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); } /** @@ -450,6 +451,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04300, sptr request(new NotificationRequest()); std::string bundleName = "bundleName"; advancedNotificationService_->SetAgentNotification(request, bundleName); + EXPECT_TRUE(advancedNotificationService_ != nullptr); } /** @@ -1552,6 +1554,10 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17100, ASSERT_EQ(advancedNotificationService_->GetSyncNotificationEnabledWithoutApp(userId, enable), ERR_OK); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType), -1); + GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test end"; } @@ -2419,6 +2425,23 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_220000 ASSERT_EQ(result.size(), ret); } +/** + * @tc.number : AdvancedNotificationServiceTest_22600 + * @tc.name : ANS_IsNeedSilentInDoNotDisturbMode_0100 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22600, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + auto ret = advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + ASSERT_EQ(ret, -1); +} + /** * @tc.number : AdvancedNotificationServiceTest_00001 * @tc.name : PrepareNotificationRequest @@ -3075,7 +3098,7 @@ HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0005, Function | S /** * @tc.number : IsNeedPushCheckTest_0006 * @tc.name : IsNeedPushCheckTest - * @tc.desc : Test notification except live view registered but has inconsistent contentType dont't need push check. + * @tc.desc : Test notification except live view registered but has inconsistent contentType don't need push check. * @tc.require : #I6Z5OV */ HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0006, Function | SmallTest | Level1) @@ -3292,6 +3315,7 @@ HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00002, Function | { advancedNotificationService_->notificationSvrQueue_ = nullptr; auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + sptr bundle1 = nullptr; auto request = new (std::nothrow) NotificationRequest(); auto ret = advancedNotificationService_->EnableDistributedSelf(true); @@ -3301,7 +3325,7 @@ HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00002, Function | ret = advancedNotificationService_->IsDistributedEnableByBundle(bundle, enable); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - ret = advancedNotificationService_->GetHasPoppedDialog(bundle, enable); + ret = advancedNotificationService_->GetHasPoppedDialog(bundle1, enable); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); ret = advancedNotificationService_->SetSyncNotificationEnabledWithoutApp(1, enable); @@ -3310,7 +3334,6 @@ HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00002, Function | ret = advancedNotificationService_->GetSyncNotificationEnabledWithoutApp(1, enable); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - advancedNotificationService_->FillActionButtons(request); request->SetIsCoverActionButtons(true); advancedNotificationService_->FillActionButtons(request); } @@ -3348,7 +3371,7 @@ HWTEST_F(AdvancedNotificationServiceTest, StartArchiveTimer_00001, Function | Sm auto slotType = NotificationConstant::SlotType::LIVE_VIEW; sptr request = new (std::nothrow) NotificationRequest(); request->SetSlotType(slotType); - request->SetAutoDeletedTime(NotificationConstant::NO_DELAY_DELETE_TIME); + request->SetAutoDeletedTime(0); auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); advancedNotificationService_->StartArchiveTimer(record); @@ -3398,8 +3421,9 @@ HWTEST_F(AdvancedNotificationServiceTest, ChangeNotificationByControlFlags_00001 flags->SetStatusIconEnabled(true); request->SetFlags(flags); + bool isAgentController = true; auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - advancedNotificationService_->ChangeNotificationByControlFlags(record); + advancedNotificationService_->ChangeNotificationByControlFlags(record, isAgentController); u_int32_t reminderFlags = flags->GetReminderFlags(); ASSERT_EQ(reminderFlags, 0); @@ -3573,6 +3597,7 @@ HWTEST_F(AdvancedNotificationServiceTest, SetBadgeNumberByBundle_00001, Function { ASSERT_NE(advancedNotificationService_, nullptr); MockIsSystemApp(true); + MockIsVerfyPermisson(true); sptr bundleOption = new (std::nothrow) NotificationBundleOption(); ASSERT_NE(bundleOption, nullptr); std::string bundleName = "invalidBundleName"; @@ -3687,6 +3712,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AddExcludeDate_00001, Function | Small { int32_t reminderId = 10; uint64_t time = 124325; + MockIsVerfyPermisson(false); ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_REMINDER_PERMISSION_DENIED); TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); MockIsNonBundleName(true); @@ -3705,6 +3731,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AddExcludeDate_00001, Function | Small HWTEST_F(AdvancedNotificationServiceTest, DelExcludeDates_00002, Function | SmallTest | Level1) { int32_t reminderId = 10; + MockIsVerfyPermisson(false); ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_REMINDER_PERMISSION_DENIED); TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); MockIsNonBundleName(true); @@ -3724,6 +3751,7 @@ HWTEST_F(AdvancedNotificationServiceTest, GetExcludeDates_00001, Function | Smal { int32_t reminderId = 10; std::vector times; + MockIsVerfyPermisson(false); ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_REMINDER_PERMISSION_DENIED); TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); MockIsNonBundleName(true); @@ -3732,5 +3760,31 @@ HWTEST_F(AdvancedNotificationServiceTest, GetExcludeDates_00001, Function | Smal ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_NO_INIT); MockIsVerfyPermisson(false); } + +/** + * @tc.number : PublishInNotificationList_00001 + * @tc.name : Test PublishInNotificationList + * @tc.desc : Test PublishInNotificationList function when the record->slot is nullptr + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, PublishInNotificationList_00001, Function | SmallTest | Level1) +{ + for (int i = 0; i < 100; i++) { + sptr request = new (std::nothrow) NotificationRequest(); + sptr notification = new (std::nothrow) Notification(request); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->notificationList_.push_back(record); + } + ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 100); + sptr request = new (std::nothrow) NotificationRequest(); + sptr notification = new (std::nothrow) Notification(request); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->PublishInNotificationList(record); + ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 100); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp b/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp index 5796543956ad358f64bcdf1a91bd8712ea351b19..7e53f8932dfacb6f2e5d7616ffe71b3e38d7ea5a 100644 --- a/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp @@ -217,41 +217,6 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00100, SleepForFC(); } -/** - * @tc.number : ANS_Publish_Update_Flow_00100 - * @tc.name : ANSPublish00100 - * @tc.desc : Publish a normal text type notification 30 times,trigger flow. - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceUpdateFlowTest_00100, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - sptr req = new NotificationRequest(1); - EXPECT_NE(req, nullptr); - req->SetSlotType(NotificationConstant::SlotType::OTHER); - req->SetLabel("req's label update flow"); - req->SetCreatorUid(1); - 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 count = 30; - for (uint64_t i = 1; i <= 30; ++i) { - if (i <= 21) { - ASSERT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); - } else { - ASSERT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_ANS_OVER_MAX_UPDATE_PERSECOND); - } - } - SleepForFC(); -} - - /** * @tc.number : ANS_Publish_00200 * @tc.name : ANSPublish00200 diff --git a/services/ans/test/unittest/advanced_notification_slot_service_test.cpp b/services/ans/test/unittest/advanced_notification_slot_service_test.cpp index 129dfbc3ca181f49e435906a7acb20fa9bdcc3c8..ea3f8a9ec6e5be9647bf983c9bd484b65aa1466d 100644 --- a/services/ans/test/unittest/advanced_notification_slot_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_slot_service_test.cpp @@ -13,9 +13,11 @@ * limitations under the License. */ +#include "notification_bundle_option.h" #include #include #include +#include #include #include "gtest/gtest.h" @@ -97,6 +99,8 @@ void AnsSlotServiceTest::TestAddSlot(NotificationConstant::SlotType type) */ HWTEST_F(AnsSlotServiceTest, AddSlots_00001, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); NotificationConstant::SlotType slotType = NotificationConstant::SlotType::CUSTOMER_SERVICE; std::vector> slots; sptr slot = new NotificationSlot(slotType); @@ -126,6 +130,8 @@ HWTEST_F(AnsSlotServiceTest, GetSlots_00001, Function | SmallTest | Level1) */ HWTEST_F(AnsSlotServiceTest, GetSlotsByBundle_00001, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); std::vector> slots; sptr bundle = nullptr; ASSERT_EQ(advancedNotificationService_->GetSlotsByBundle(bundle, slots), (int)ERR_ANS_INVALID_BUNDLE); @@ -139,6 +145,8 @@ HWTEST_F(AnsSlotServiceTest, GetSlotsByBundle_00001, Function | SmallTest | Leve */ HWTEST_F(AnsSlotServiceTest, GetSlotsByBundle_00002, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); std::vector> slots; sptr bundle = new NotificationBundleOption("test", 1); advancedNotificationService_->notificationSvrQueue_ = nullptr; @@ -153,6 +161,8 @@ HWTEST_F(AnsSlotServiceTest, GetSlotsByBundle_00002, Function | SmallTest | Leve */ HWTEST_F(AnsSlotServiceTest, UpdateSlots_00001, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); std::vector> slots; sptr bundle = nullptr; ASSERT_EQ(advancedNotificationService_->UpdateSlots(bundle, slots), (int)ERR_ANS_INVALID_BUNDLE); @@ -170,6 +180,8 @@ HWTEST_F(AnsSlotServiceTest, UpdateSlots_00001, Function | SmallTest | Level1) */ HWTEST_F(AnsSlotServiceTest, UpdateSlots_00002, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); std::vector> slots; sptr slot = new NotificationSlot(NotificationConstant::SlotType::LIVE_VIEW); slot->SetEnable(true); @@ -333,7 +345,7 @@ HWTEST_F(AnsSlotServiceTest, SetRequestBySlotType_00001, Function | SmallTest | { sptr request = new NotificationRequest(); request->SetSlotType(NotificationConstant::SlotType::CUSTOMER_SERVICE); - sptr bundle = nullptr; + sptr bundle = new (std::nothrow) NotificationBundleOption(); advancedNotificationService_->SetRequestBySlotType(request, bundle); EXPECT_NE(request->GetFlags(), nullptr); } @@ -503,7 +515,7 @@ HWTEST_F(AnsSlotServiceTest, UpdateSlotReminderModeBySlotFlags_00002, Function | */ HWTEST_F(AnsSlotServiceTest, GenerateSlotReminderMode_00001, Function | SmallTest | Level1) { - sptr bundle = nullptr; + sptr bundle = new (std::nothrow) NotificationBundleOption(); sptr slot = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); advancedNotificationService_->GenerateSlotReminderMode(slot, bundle); ASSERT_EQ(slot->GetReminderMode(), (int)0b111011); @@ -517,7 +529,7 @@ HWTEST_F(AnsSlotServiceTest, GenerateSlotReminderMode_00001, Function | SmallTes */ HWTEST_F(AnsSlotServiceTest, GenerateSlotReminderMode_00002, Function | SmallTest | Level1) { - sptr bundle = nullptr; + sptr bundle = new (std::nothrow) NotificationBundleOption(); sptr slot = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); advancedNotificationService_->GenerateSlotReminderMode(slot, bundle, true); ASSERT_EQ(slot->GetReminderMode(), (int)0b111011); diff --git a/services/ans/test/unittest/advanced_notification_utils_test.cpp b/services/ans/test/unittest/advanced_notification_utils_test.cpp index 4b6acc76fcfa66e1b64699c71b71e343638ae2ba..233545ade1f5f921eb09a750590bc234fe2a7a1a 100644 --- a/services/ans/test/unittest/advanced_notification_utils_test.cpp +++ b/services/ans/test/unittest/advanced_notification_utils_test.cpp @@ -170,37 +170,15 @@ HWTEST_F(AnsUtilsTest, FillRequestByKeys_00001, Function | SmallTest | Level1) */ HWTEST_F(AnsUtilsTest, IsAllowedGetNotificationByFilter_00001, Function | SmallTest | Level1) { + sptr bundle = new NotificationBundleOption("test", 1); auto record = std::make_shared(); record->bundleOption = new NotificationBundleOption("test", 1); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - int ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); - - MockIsVerfyPermisson(true); - ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record); + int ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record, bundle); ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.name: IsAllowedGetNotificationByFilter_00002 - * @tc.desc: Test IsAllowedGetNotificationByFilter - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsUtilsTest, IsAllowedGetNotificationByFilter_00002, Function | SmallTest | Level1) -{ - auto record = std::make_shared(); - record->bundleOption = new NotificationBundleOption("test", IPCSkeleton::GetCallingUid()); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - int ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); record->bundleOption->SetBundleName("bundleName"); - ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record); - ASSERT_EQ(ret, (int)ERR_OK); + ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record, bundle); + ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** 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 501bf9e10e714341be801df9b7bd77e372f5021a..f03a0287d07c38f6797096e42109bd2897865f61 100644 --- a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -73,5 +73,10 @@ bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &b return true; } #endif + +bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) +{ + return true; +} } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/ans/test/unittest/notification_dialog_test/mock_os_account_manager_annex.cpp b/services/ans/test/unittest/notification_dialog_test/mock_os_account_manager_annex.cpp index 067b2eff5163b000d67eabaefd5fc9dc0ec5740c..8be5780b35d8bdd2c36a8f184568184b77c273e4 100644 --- a/services/ans/test/unittest/notification_dialog_test/mock_os_account_manager_annex.cpp +++ b/services/ans/test/unittest/notification_dialog_test/mock_os_account_manager_annex.cpp @@ -17,15 +17,15 @@ namespace { int32_t g_mockId = 100; // default id when there is no os_account part -bool g_mockQueryActiveOsAccountIdsRet = true; +bool g_mockQueryForgroundOsAccountRet = true; bool g_mockGetOsAccountLocalIdFromUidRet = true; int32_t g_mockIdForGetOsAccountLocalIdFromUid = 100; bool g_mockOsAccountExists = true; } -void MockQueryActiveOsAccountIds(bool mockRet, uint8_t mockCase) +void MockQueryForgroundOsAccountId(bool mockRet, uint8_t mockCase) { - g_mockQueryActiveOsAccountIdsRet = mockRet; + g_mockQueryForgroundOsAccountRet = mockRet; switch (mockCase) { case 1: { g_mockId = 101; // 101 mockcase1 @@ -46,7 +46,7 @@ void MockIsOsAccountExists(bool mockRet) void ResetAccountMock() { g_mockId = 100; // 100 mockId - g_mockQueryActiveOsAccountIdsRet = true; + g_mockQueryForgroundOsAccountRet = true; g_mockGetOsAccountLocalIdFromUidRet = true; g_mockIdForGetOsAccountLocalIdFromUid = 100; g_mockOsAccountExists = true; @@ -73,12 +73,12 @@ void MockGetOsAccountLocalIdFromUid(bool mockRet, uint8_t mockCase = 0) namespace OHOS { namespace AccountSA { -ErrCode OsAccountManager::QueryActiveOsAccountIds(std::vector& ids) +ErrCode OsAccountManager::GetForegroundOsAccountLocalId(int32_t &id) { - if (!g_mockQueryActiveOsAccountIdsRet) { + if (!g_mockQueryForgroundOsAccountRet) { return ERR_INVALID_OPERATION; } - ids.emplace_back(g_mockId); + id = g_mockId; return ERR_OK; } diff --git a/services/ans/test/unittest/notification_dialog_test/notification_dialog_test.cpp b/services/ans/test/unittest/notification_dialog_test/notification_dialog_test.cpp index fc2cde99a4e3f55f1aefac09181119605852011e..a43ffabdb159d0409b6eb5cd96facf61330cdbc9 100644 --- a/services/ans/test/unittest/notification_dialog_test/notification_dialog_test.cpp +++ b/services/ans/test/unittest/notification_dialog_test/notification_dialog_test.cpp @@ -24,7 +24,7 @@ #undef protected #include "ans_inner_errors.h" -extern void MockQueryActiveOsAccountIds(bool mockRet, uint8_t mockCase); +extern void MockQueryForgroundOsAccountId(bool mockRet, uint8_t mockCase); using namespace testing::ext; @@ -38,30 +38,14 @@ public: void TearDown() {}; }; -/** - * @tc.name : NotificationDialog_00100 - * @tc.number : - * @tc.desc : test GetActiveUserId function and QueryActiveOsAccountIds is ERR_OK - */ -HWTEST_F(NotificationDialogTest, NotificationDialog_00100, Function | SmallTest | Level1) -{ - MockQueryActiveOsAccountIds(true, 0); - int32_t result = NotificationDialog::GetActiveUserId(); - int32_t activeUserId = 100; - ASSERT_EQ(result, activeUserId); -} - /** * @tc.name : NotificationDialog_00200 * @tc.number : - * @tc.desc : test GetActiveUserId function and QueryActiveOsAccountIds is ERR_INVALID_OPERATION + * @tc.desc : test QueryActiveOsAccountIds is ERR_INVALID_OPERATION */ HWTEST_F(NotificationDialogTest, NotificationDialog_00200, Function | SmallTest | Level1) { - MockQueryActiveOsAccountIds(false, 1); - int32_t result = NotificationDialog::GetActiveUserId(); - int32_t activeUserId = -4; - ASSERT_EQ(result, activeUserId); + MockQueryForgroundOsAccountId(false, 1); std::string bundleName = "BundleName"; int32_t result2 = NotificationDialog::GetUidByBundleName(bundleName); @@ -76,10 +60,7 @@ HWTEST_F(NotificationDialogTest, NotificationDialog_00200, Function | SmallTest */ HWTEST_F(NotificationDialogTest, NotificationDialog_00300, Function | SmallTest | Level1) { - MockQueryActiveOsAccountIds(false, 1); - int32_t result = NotificationDialog::GetActiveUserId(); - int32_t activeUserId = -4; - ASSERT_EQ(result, activeUserId); + MockQueryForgroundOsAccountId(false, 1); std::string bundleName = "BundleName"; int32_t result2 = NotificationDialog::GetUidByBundleName(bundleName); @@ -104,10 +85,7 @@ HWTEST_F(NotificationDialogTest, NotificationDialog_00300, Function | SmallTest */ HWTEST_F(NotificationDialogTest, NotificationDialog_00400, Function | SmallTest | Level1) { - MockQueryActiveOsAccountIds(false, 1); - int32_t result = NotificationDialog::GetActiveUserId(); - int32_t activeUserId = -4; - ASSERT_EQ(result, activeUserId); + MockQueryForgroundOsAccountId(false, 1); std::string bundleName = "BundleName"; int32_t result2 = NotificationDialog::GetUidByBundleName(bundleName); diff --git a/services/ans/test/unittest/notification_preferences_database_test.cpp b/services/ans/test/unittest/notification_preferences_database_test.cpp index 448c2e280c7569bfed847a5b0711dd990d7e721d..ad38241171c54a6297e69a6e2e4e7903e19013c2 100644 --- a/services/ans/test/unittest/notification_preferences_database_test.cpp +++ b/services/ans/test/unittest/notification_preferences_database_test.cpp @@ -932,7 +932,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, GenerateBundleLablel_0100, TestSiz bundleInfo.SetBundleUid(1); std::string deviceType = "test"; auto ret = preferncesDB_->GenerateBundleLablel(bundleInfo, deviceType); - ASSERT_EQ(ret, "enabledNotificationDistributed-name-1-test"); + ASSERT_EQ(ret, "enabledDistributedNotification-name-1-test"); } /** diff --git a/services/ans/test/unittest/notification_preferences_test.cpp b/services/ans/test/unittest/notification_preferences_test.cpp index 9d3a053cff90540c89f47eeac6d1bf84b739a764..3588a96c0ccebc58e9c02add2ba85c7dbff762e9 100644 --- a/services/ans/test/unittest/notification_preferences_test.cpp +++ b/services/ans/test/unittest/notification_preferences_test.cpp @@ -1501,7 +1501,7 @@ HWTEST_F(NotificationPreferencesTest, GetDoNotDisturbProfile_0200, TestSize.Leve int32_t userId = 1; sptr profile; auto res = NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(profileId, userId, profile); - ASSERT_EQ(res, ERR_ANS_INVALID_PARAM); + ASSERT_EQ(res, ERR_ANS_NO_PROFILE_TEMPLATE); } /** diff --git a/services/ans/test/unittest/notification_rdb_data_mgr_test/notification_rdb_data_mgr_test.cpp b/services/ans/test/unittest/notification_rdb_data_mgr_test/notification_rdb_data_mgr_test.cpp index 4f8469b7e3347a08f2c9d688a4ba1d603b1f6a30..f1aa458be60f1471be5829ed53d146efd4e7384b 100755 --- a/services/ans/test/unittest/notification_rdb_data_mgr_test/notification_rdb_data_mgr_test.cpp +++ b/services/ans/test/unittest/notification_rdb_data_mgr_test/notification_rdb_data_mgr_test.cpp @@ -127,7 +127,7 @@ class RdbStoreTest : public RdbStore { return nullptr; }; virtual std::shared_ptr QueryByStep( - const std::string &sql, const std::vector &bindArgs = {}) + const std::string &sql, const std::vector &bindArgs = {}, bool preCount = true) { return nullptr; }; @@ -185,7 +185,7 @@ class RdbStoreTest : public RdbStore { return nullptr; }; virtual std::shared_ptr QueryByStep( - const AbsRdbPredicates &predicates, const std::vector &columns) + const AbsRdbPredicates &predicates, const std::vector &columns, bool preCount = true) { return nullptr; }; diff --git a/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp b/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp index d640882e670bb1d13144ffeffb94bae4afadef22..a8ae3da03d18f651fe062b7e902e397c0cb9086a 100644 --- a/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp +++ b/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp @@ -30,7 +30,7 @@ extern void MockGetUserId(bool mockRet); extern void MockGetBundleName(bool mockRet); extern void MockGetNotificationSlotRet(bool mockRet); -extern void MockQueryActiveOsAccountIds(bool mockRet, uint8_t mockCase); +extern void MockQueryForgroundOsAccountId(bool mockRet, uint8_t mockCase); using namespace OHOS::Security::AccessToken; using namespace testing::ext; @@ -535,7 +535,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_02 { IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); - sptr bundleOption = nullptr; + sptr bundleOption = new NotificationBundleOption(); bool enabled = true; MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); @@ -639,7 +639,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_02 std::string deviceId = ""; bool enabled = true; MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); - MockQueryActiveOsAccountIds(false, 1); + MockQueryForgroundOsAccountId(false, 1); AdvancedNotificationService advancedNotificationService; ASSERT_EQ(advancedNotificationService.SetNotificationsEnabledForAllBundles(deviceId, enabled), @@ -654,7 +654,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_02 HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_02900, Function | SmallTest | Level1) { std::string deviceId = ""; - sptr bundleOption = nullptr; + sptr bundleOption = new NotificationBundleOption(); bool enabled = true; MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); @@ -689,7 +689,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_03 bool enabled = true; MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); - MockQueryActiveOsAccountIds(false, 1); + MockQueryForgroundOsAccountId(false, 1); AdvancedNotificationService advancedNotificationService; ASSERT_EQ(advancedNotificationService.IsAllowedNotify(enabled), ERR_ANS_GET_ACTIVE_USER_FAILED); } @@ -735,7 +735,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_03 HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_03400, Function | SmallTest | Level1) { sptr bundleOption = new NotificationBundleOption(); - MockQueryActiveOsAccountIds(false, 1); + MockQueryForgroundOsAccountId(false, 1); bool allowed = true; int32_t uid = 2; @@ -923,7 +923,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_04 HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_04500, Function | SmallTest | Level1) { sptr date = nullptr; - MockQueryActiveOsAccountIds(false, 1); + MockQueryForgroundOsAccountId(false, 1); MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); AdvancedNotificationService advancedNotificationService; @@ -953,7 +953,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_04 HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_04700, Function | SmallTest | Level1) { sptr date = nullptr; - MockQueryActiveOsAccountIds(false, 1); + MockQueryForgroundOsAccountId(false, 1); MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); AdvancedNotificationService advancedNotificationService; @@ -1142,7 +1142,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_05 */ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_05900, Function | SmallTest | Level1) { - sptr bundleOption = nullptr; + sptr bundleOption = new NotificationBundleOption(); NotificationConstant::SlotType slotType = NotificationConstant::SlotType::OTHER; bool enabled = true; bool isForceControl = false; @@ -1315,5 +1315,22 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_06 AdvancedNotificationService advancedNotificationService; ASSERT_EQ(advancedNotificationService.GetEnabledForBundleSlotSelf(slotType, enabled), ERR_ANS_INVALID_BUNDLE); } + +/** + * @tc.number : AdvancedNotificationService_06900 + * @tc.name : AdvancedNotificationService_06900 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function and CheckPermission is false + */ +HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_06900, Function | SmallTest | Level1) +{ + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + AdvancedNotificationService advancedNotificationService; + ASSERT_EQ(advancedNotificationService.IsNeedSilentInDoNotDisturbMode( + phoneNumber, callerType), ERR_ANS_GET_ACTIVE_USER_FAILED); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/os_account_manager_helper_test.cpp b/services/ans/test/unittest/os_account_manager_helper_test.cpp index 092c5d746fe5cef321133cf51a181f8aee2a20e7..a13607524b843f55bf4924ba347b394d39667474 100644 --- a/services/ans/test/unittest/os_account_manager_helper_test.cpp +++ b/services/ans/test/unittest/os_account_manager_helper_test.cpp @@ -90,7 +90,7 @@ HWTEST_F(OsAccountManagerHelperTest, CheckUserExists_00200, Function | SmallTest /** * @tc.number : IsSystemAccount_0100 * @tc.name : IsSystemAccount_0100 - * @tc.desc : test IsSystemAccount function, 100 is true(100 <= userId <= 1099) + * @tc.desc : test IsSystemAccount function, 100 is true(100 <= userId <= 10736) */ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0100, Function | SmallTest | Level1) { @@ -101,18 +101,18 @@ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0100, Function | SmallTest /** * @tc.number : IsSystemAccount_0200 * @tc.name : IsSystemAccount_0200 - * @tc.desc : test IsSystemAccount function, 1100 is false(100 <= userId <= 1099) + * @tc.desc : test IsSystemAccount function, 1100 is false(100 <= userId <= 10736) */ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0200, Function | SmallTest | Level1) { - int32_t userId = 1100; + int32_t userId = 10737; ASSERT_EQ(false, OsAccountManagerHelper::IsSystemAccount(userId)); } /** * @tc.number : IsSystemAccount_0300 * @tc.name : IsSystemAccount_0300 - * @tc.desc : test IsSystemAccount function, 0 is false(100 <= userId <= 1099) + * @tc.desc : test IsSystemAccount function, 0 is false(100 <= userId <= 10736) */ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0300, Function | SmallTest | Level1) { @@ -123,11 +123,11 @@ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0300, Function | SmallTest /** * @tc.number : IsSystemAccount_0400 * @tc.name : IsSystemAccount_0400 - * @tc.desc : test IsSystemAccount function, 1099 is true(100 <= userId <= 1099) + * @tc.desc : test IsSystemAccount function, 1099 is true(100 <= userId <= 10736) */ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0400, Function | SmallTest | Level1) { - int32_t userId = 1099; + int32_t userId = 10736; ASSERT_EQ(true, OsAccountManagerHelper::IsSystemAccount(userId)); } } diff --git a/services/ans/test/unittest/reminder_data_manager_test.cpp b/services/ans/test/unittest/reminder_data_manager_test.cpp index 431381ff9efe3c6e065ee168b84dec73bdb55c51..543d00f2a095b29a859564c4fcb1339fcc2c58fa 100644 --- a/services/ans/test/unittest/reminder_data_manager_test.cpp +++ b/services/ans/test/unittest/reminder_data_manager_test.cpp @@ -44,6 +44,7 @@ public: { ReminderDataManager::InitInstance(nullptr); manager = ReminderDataManager::GetInstance(); + manager->Init(false); } static void TearDownTestCase() { @@ -117,7 +118,8 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_003, Level1) manager->alertingReminderId_ = -1; manager->OnUserSwitch(0); manager->OnUserRemove(0); - manager->OnServiceStart(); + manager->OnBundleMgrServiceStart(); + manager->OnAbilityMgrServiceStart(); system("rm -rf /data/service/el1/public/notification/"); EXPECT_TRUE(manager != nullptr); } @@ -140,7 +142,6 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_004, Level1) manager->reminderVector_.push_back(reminder); manager->FindReminderRequestLocked(10, ""); option->SetBundleName("test"); - manager->notificationBundleOptionMap_[10] = option; manager->FindReminderRequestLocked(10, ""); manager->FindReminderRequestLocked(10, "test"); system("rm -rf /data/service/el1/public/notification/"); @@ -285,8 +286,8 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_011, Level1) sptr reminder(new ReminderRequestTimer(10)); reminder->SetReminderId(0); sptr option(new NotificationBundleOption()); - manager->notificationBundleOptionMap_[10] = option; manager->ShowReminder(reminder, true, true, true, true); + reminder->SetNotificationBundleOption(option); reminder->SetReminderId(10); manager->ShowReminder(reminder, true, true, true, true); manager->ShowReminder(reminder, true, true, true, true); @@ -431,7 +432,7 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_016, Level1) reminder1->SetActionButton("不再提醒", ReminderRequest::ActionButtonType::CLOSE, "", buttonWantAgent1, buttonDataShareUpdate1); manager->UpdateAppDatabase(reminder1, ReminderRequest::ActionButtonType::CLOSE); - SUCCEED(); + EXPECT_TRUE(reminder1->actionButtonMap_.size() > 0); } /** @@ -613,13 +614,13 @@ HWTEST_F(ReminderDataManagerTest, ReminderEventManagerTest_004, Level1) HWTEST_F(ReminderDataManagerTest, StartExtensionAbilityTest_001, Level1) { auto reminder1 = new ReminderRequestCalendar(10); - bool ret1 = manager->StartExtensionAbility(reminder1); + bool ret1 = manager->StartExtensionAbility(reminder1, 0); EXPECT_TRUE(ret1); auto reminder2 = new ReminderRequestCalendar(10); auto wantInfo = std::make_shared(); reminder2->SetRRuleWantAgentInfo(wantInfo); - bool ret2 = manager->StartExtensionAbility(reminder2); + bool ret2 = manager->StartExtensionAbility(reminder2, 0); EXPECT_TRUE(ret2); } @@ -688,6 +689,7 @@ HWTEST_F(ReminderDataManagerTest, CheckPulishReminder_0001, Level1) */ HWTEST_F(ReminderDataManagerTest, OnLanguageChanged_0001, Level1) { + sleep(2); sptr reminder = new ReminderRequestTimer(10); reminder->SetReminderId(10); std::string title = "this is title"; diff --git a/services/dialog_ui/enable_notification_dialog/AppScope/app.json b/services/dialog_ui/enable_notification_dialog/AppScope/app.json index b99cc659357e176479caaf71f9bbbb61d09e4304..f2ee0dc8f5aa0b43f0726693d242bd56e15fbe73 100644 --- a/services/dialog_ui/enable_notification_dialog/AppScope/app.json +++ b/services/dialog_ui/enable_notification_dialog/AppScope/app.json @@ -2,12 +2,13 @@ "app": { "bundleName": "com.ohos.notificationdialog", "vendor": "example", - "versionCode": 1000008, - "versionName": "1.0.8", + "versionCode": 1000015, + "versionName": "1.1.5", "icon": "$media:app_icon", "label": "$string:app_name", "distributedNotificationEnabled": true, "minAPIVersion": 10, - "targetAPIVersion": 10 + "targetAPIVersion": 10, + "configuration": "$profile:configuration" } } diff --git a/services/dialog_ui/enable_notification_dialog/AppScope/resources/base/profile/configuration.json b/services/dialog_ui/enable_notification_dialog/AppScope/resources/base/profile/configuration.json new file mode 100644 index 0000000000000000000000000000000000000000..4bc20f7d54229e91d71040dfec679f71c095d012 --- /dev/null +++ b/services/dialog_ui/enable_notification_dialog/AppScope/resources/base/profile/configuration.json @@ -0,0 +1,6 @@ +{ + "configuration": { + "fontSizeScale": "followSystem", + "fontSizeMaxScale": "3.2" + } +} \ No newline at end of file diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index 64f1bfba4fa1dae08957c5c4c8de32f2b8743abb..c4ddaaa60bf89ecfd56493634829633f3b1eeaec 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -23,11 +23,20 @@ import UIExtensionAbility from '@ohos.app.ability.UIExtensionAbility'; import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; import uiExtensionHost from '@ohos.uiExtensionHost'; import StartOptions from '@ohos.app.ability.StartOptions'; +import configPolicy from '@ohos.configPolicy'; +import fs from '@ohos.file.fs'; +import Constants from '../common/constant'; const TAG = 'NotificationDialog_Service '; +const UPDATE_INIT = 1; +const UPDATE_NUM = 1; +const UPDATE_BOUNDARY = 100; + +let eventSubscriber:CommonEventManager.CommonEventSubscriber; + const enableNotificationDialogDestroyedEvent = { eventId: 1, priority: emitter.EventPriority.LOW @@ -56,11 +65,23 @@ async function handleDialogQuitException(want: Want): Promise { ); } +interface NotificationConfig { + deviceInfo: DeviceInfo; +} + +interface DeviceInfo { + isWatch: boolean; + isPc: boolean; +} export class EnableNotificationDialog { static ENABLE_NOTIFICATION_DIALOG_NAME = 'EnableNotificationDialog'; static DIALOG_PATH = 'pages/notificationDialog'; + static WATCH_DIALOG_PATH = 'pages/watchNotificationDialog'; + static PC_DIALOG_PATH = 'pages/pcNotificationDialog'; static TRANSPARANT_COLOR = '#00000000'; + static SCENEBOARD_BUNDLE = 'com.ohos.sceneboard'; + static SYSTEMUI_BUNDLE = 'com.ohos.systemui'; id: number; want: Want; @@ -68,6 +89,7 @@ export class EnableNotificationDialog { extensionWindow:uiExtensionHost.UIExtensionHostWindowProxy; storage: LocalStorage; stageModel: boolean; + subWindow: window.Window; constructor(id: number, want: Want, stageModel: boolean) { this.id = id; @@ -77,49 +99,6 @@ export class EnableNotificationDialog { this.extensionWindow = undefined; } - async createWindow(windowType: window.WindowType, context, displayRect): Promise { - try { - let winArgs = { - 'name': `${EnableNotificationDialog.ENABLE_NOTIFICATION_DIALOG_NAME}${this.id}`, - 'windowType': windowType, - 'ctx': context - }; - let win = await window.createWindow(winArgs); - this.window = win; - let shouldHide = true; - - if (windowType === window.WindowType.TYPE_DIALOG) { - await win.bindDialogTarget(this.want.parameters.callerToken['value'], - async (): Promise => { - console.info(TAG, `window ${this.id} died`); - await this.destroyException(); - } - ); - } - - this.storage = new LocalStorage({ - 'dialog': this - }); - await win.moveWindowTo(displayRect.left, displayRect.top); - await win.resize(displayRect.width, displayRect.height); - await win.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); - try { - await win.hideNonSystemFloatingWindows(shouldHide); - } catch (err) { - console.error(TAG, 'window hideNonSystemFloatingWindows failed!'); - } - await win.setWindowBackgroundColor(EnableNotificationDialog.TRANSPARANT_COLOR); - await win.showWindow(); - await win.setWindowLayoutFullScreen(true); - } catch (err) { - if (this.window !== undefined) { - await this.destroyWindow(); - } - console.error(TAG, 'window create failed!'); - throw new Error('Failed to create window'); - } - } - async createUiExtensionWindow(session: UIExtensionContentSession, stageModel: boolean): Promise { try { @@ -132,7 +111,37 @@ export class EnableNotificationDialog { 'session': session }); - if (stageModel) { + let path = EnableNotificationDialog.DIALOG_PATH; + let hasConfig = true; + try { + let filePaths = await configPolicy.getCfgFiles(Constants.CCM_CONFIG_PATH); + if (filePaths.length === 0) { + console.info(TAG, 'not get any configFile'); + hasConfig = false; + } + for (let i = 0; i < filePaths.length; i++) { + let res = fs.accessSync(filePaths[i]); + if (res) { + let fileContent = fs.readTextSync(filePaths[i]); + let config: NotificationConfig = JSON.parse(fileContent); + if (config.deviceInfo !== undefined) { + let deviceInfo: DeviceInfo = config.deviceInfo; + if (deviceInfo.isWatch !== undefined) { + path = EnableNotificationDialog.WATCH_DIALOG_PATH; + console.info(TAG, 'watch request'); + } + if (deviceInfo.isPc !== undefined) { + path = EnableNotificationDialog.PC_DIALOG_PATH; + console.info(TAG, 'pc request'); + } + } + } + } + } catch (err) { + console.error(TAG, 'Failed get ccm files'); + } + + if (stageModel && hasConfig) { let subWindowOpts : window.SubWindowOptions = { 'title': '', decorEnabled: false, @@ -140,20 +149,27 @@ export class EnableNotificationDialog { isTopmost: true }; let subWindow = await extensionWindow.createSubWindowWithOptions('subWindowForHost' + Date(), subWindowOpts); - let dis = display.getDefaultDisplaySync(); - await subWindow?.resize(dis.width, dis.height); - await subWindow.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); + this.subWindow = subWindow; + await this.sleep(200); + let windowRect = extensionWindow.properties?.uiExtensionHostWindowProxyRect; + console.info(TAG, `size : ${windowRect?.left} ${windowRect?.top} ${windowRect?.width} ${windowRect?.height}`); + await subWindow.moveWindowTo(windowRect?.left, windowRect?.top); + await subWindow.resize(windowRect?.width, windowRect?.height); + await subWindow.loadContent(path, this.storage); + try { + await subWindow.hideNonSystemFloatingWindows(true); + } catch (err) { + console.error(TAG, 'subWindow hideNonSystemFloatingWindows failed!'); + } await subWindow.setWindowBackgroundColor(EnableNotificationDialog.TRANSPARANT_COLOR); await subWindow.showWindow(); } else { - await session.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); - } - try { - await extensionWindow.hideNonSecureWindows(shouldHide); - } catch (err) { - console.error(TAG, 'window hideNonSecureWindows failed!'); - } - if (!stageModel) { + await session.loadContent(path, this.storage); + try { + await extensionWindow.hideNonSecureWindows(shouldHide); + } catch (err) { + console.error(TAG, 'window hideNonSecureWindows failed!'); + } await session.setWindowBackgroundColor(EnableNotificationDialog.TRANSPARANT_COLOR); } } catch (err) { @@ -162,6 +178,10 @@ export class EnableNotificationDialog { } } + async sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); + } + async publishButtonClickedEvent(enabled: boolean): Promise { CommonEventManager.publish( COMMON_EVENT_NAME, @@ -199,12 +219,14 @@ export class EnableNotificationDialog { }; - class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { onCreate() { console.log(TAG, `UIExtAbility onCreate`); AppStorage.setOrCreate('context', this.context); + AppStorage.setOrCreate('isUpdate', UPDATE_INIT); + AppStorage.setOrCreate('clicked', false); + this.subscribe(); } @@ -213,46 +235,65 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { let stageModel = false; let bundleName = want.parameters['ohos.aafwk.param.callerBundleName']; let bundleUid = want.parameters['ohos.aafwk.param.callerUid']; - if (want.parameters.bundleName === undefined) { + if (bundleName !== EnableNotificationDialog.SCENEBOARD_BUNDLE && + bundleName !== EnableNotificationDialog.SYSTEMUI_BUNDLE) { want.parameters.bundleName = bundleName; want.parameters.bundleUid = bundleUid; stageModel = true; } else { stageModel = false; } - console.log(TAG, `UIExtAbility onSessionCreate bundleName ${want.parameters.bundleName}` - + `uid ${want.parameters.bundleUid}`); + console.log(TAG, `UIExtAbility onSessionCreate bundleName ${want.parameters.bundleName}` + + `uid ${want.parameters.bundleUid}`); let dialog = new EnableNotificationDialog(1, want, stageModel); await dialog.createUiExtensionWindow(session, stageModel); - AppStorage.setOrCreate('clicked', false); AppStorage.setOrCreate('dialog', dialog); } catch (err) { console.error(TAG, `Failed to handle onSessionCreate`); await handleDialogQuitException(want); + this.context.terminateSelf(); } } onForeground() { console.log(TAG, `UIExtAbility onForeground`); let dialog = AppStorage.get('dialog'); - try { - dialog?.extensionWindow?.hideNonSecureWindows(true); - } catch (err) { - console.error(TAG, 'onForeground hideNonSecureWindows failed!'); - } + + if (dialog?.subWindow !== undefined) { + try { + dialog?.subWindow?.hideNonSystemFloatingWindows(true); + } catch (err) { + console.error(TAG, 'onForeground hideNonSystemFloatingWindows failed!'); + } + } else { + try { + dialog?.extensionWindow?.hideNonSecureWindows(true); + } catch (err) { + console.error(TAG, 'onForeground hideNonSecureWindows failed!'); + } + } } onBackground() { console.log(TAG, `UIExtAbility onBackground`); let dialog = AppStorage.get('dialog'); - try { - dialog?.extensionWindow?.hideNonSecureWindows(false); - } catch (err) { - console.error(TAG, 'onBackground hideNonSecureWindows failed!'); + + if (dialog?.subWindow !== undefined) { + try { + dialog?.subWindow?.hideNonSystemFloatingWindows(false); + } catch (err) { + console.error(TAG, 'onBackground hideNonSystemFloatingWindows failed!'); + } + } else { + try { + dialog?.extensionWindow?.hideNonSecureWindows(false); + } catch (err) { + console.error(TAG, 'onBackground hideNonSecureWindows failed!'); + } } } - async onSessionDestroy(session: UIExtensionContentSession) { + async onSessionDestroy(session: UIExtensionContentSession): Promise { console.log(TAG, `UIExtAbility onSessionDestroy`); if (AppStorage.get('clicked') === false) { console.log(TAG, `UIExtAbility onSessionDestroy unclick destory`); @@ -261,10 +302,59 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { } } - onDestroy() { + async onDestroy(): Promise { console.info(TAG, 'UIExtAbility onDestroy.'); + await this.unsubscribe(); + await this.sleep(500); this.context.terminateSelf(); } + + async sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + async subscribe(): Promise { + await CommonEventManager.createSubscriber( + { events: ['usual.event.BUNDLE_RESOURCES_CHANGED'] }) + .then((subscriber:CommonEventManager.CommonEventSubscriber) => { + eventSubscriber = subscriber; + }) + .catch((err) => { + console.log(TAG, `subscriber createSubscriber error code is ${err.code}, message is ${err.message}`); + }); + + if (eventSubscriber === null) { + console.log(TAG, 'need create subscriber'); + return; + } + CommonEventManager.subscribe(eventSubscriber, (err, data) => { + if (err?.code) { + console.error(TAG, `subscribe callBack err= ${JSON.stringify(err)}`); + } else { + console.log(TAG, `subscribe callBack data= ${JSON.stringify(data)}`); + if (data.parameters?.bundleResourceChangeType !== 1) { + return; + } + console.log(TAG, `BUNDLE_RESOURCES_CHANGED-language change`); + let isUpdate:number = AppStorage.get('isUpdate'); + if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { + AppStorage.setOrCreate('isUpdate', UPDATE_NUM); + } else { + AppStorage.setOrCreate('isUpdate', ++isUpdate); + } + } + }); + } + + async unsubscribe(): Promise { + try { + if (eventSubscriber != null) { + CommonEventManager.unsubscribe(eventSubscriber, (err) => {}); + } + } catch (err) { + console.info('ubsubscribe fail'); + } + } } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets index cfd06343a979e5258436fef1df7f8075eaf3394e..103426d75e94147967142f5055b019740a2a3c38 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets @@ -93,7 +93,7 @@ export default class Constants { static CLICK_SHADOW_LENGTH = 48; static DIVIDER = '1px'; static DIVIDER_HEIGHT = 24; - public static DIVIDER_WIDTH = '2px'; + static DIVIDER_WIDTH = "2px"; static DIVIDER_MARGIN_RIGHT_PERMISSION = 52; static DIVIDER_MARGIN_RIGHT_APPLICATION = 68; @@ -117,31 +117,60 @@ export default class Constants { static DIALOG_LABEL_LINE_HEIGHT = 14; // request text of dialog - static DIALOG_REQ_FONT_SIZE = 20; - static DIALOG_REQ_MARGIN_TOP = 16; - static DIALOG_REQ_MARGIN_BUTTOM = 16; - static DIALOG_REQ_MARGIN_LEFT = 24; - static DIALOG_REQ_MARGIN_RIGHT = 24; + public static DIALOG_REQ_FONT_SIZE = 20; + public static DIALOG_REQ_MARGIN_TOP = 16; + public static DIALOG_REQ_MARGIN_BUTTOM = 8; + public static DIALOG_REQ_MARGIN_LEFT = 24; + public static DIALOG_REQ_MARGIN_RIGHT = 24; public static DIALOG_REQ_LINE_HEIGHT = 24; // description text of dialog - static DIALOG_DESP_FONT_SIZE = 16; - static DIALOG_DESP_MARGIN_TOP = 0; - static DIALOG_DESP_MARGIN_LEFT = 24; - static DIALOG_DESP_MARGIN_RIGHT = 24; - static DIALOG_DESP_MARGIN_BOTTOM = 12; - static DIALOG_DESP_LINE_HEIGHT = 21; + public static DIALOG_DESP_FONT_SIZE = 16; + public static DIALOG_DESP_MARGIN_TOP = 0; + public static DIALOG_DESP_MARGIN_LEFT = 24; + public static DIALOG_DESP_MARGIN_RIGHT = 24; + public static DIALOG_DESP_MARGIN_BOTTOM = 8; + public static DIALOG_DESP_LINE_HEIGHT = 21; static BUTTON_MARGIN_TOP = 8; static BUTTON_MARGIN_LEFT = 16; static BUTTON_MARGIN_RIGHT = 16; static BUTTON_HEIGHT = 40; - public static BUTTON_LEFT = 8; - public static BUTTON_RIGHT = 8; + static BUTTON_LEFT = 8; + static BUTTON_RIGHT = 8; static DIALOG_PRIVACY_BORDER_RADIUS = 32; static DIALOG_PADDING_BOTTOM = 16; + public static TITLE_MIN_FONT_SIZE = 16; + public static CROSS_LINE_RATIO = 0.2; + public static CROSS_LINE_RESIZE_PARAM = 1.25; + + public static FONT_SCALE_DEFAULT = 1; + public static FONT_SCALE_MAX = 1.8; + public static MAX_DIALOG_WIDTH = 400; + + //pc + public static PC_ICON_MARGIN_TOP = 24; + + public static PC_TITLE_MARGIN_TOP = 16; + public static PC_TITLE_MARGIN_SIDE = 24; + + public static PC_CONTENT_MARGIN_TOP = 16; + public static PC_CONTENT_MARGIN_SIDE = 24; + + public static PC_OPERATE_MARGIN_SIDE = 16; + public static PC_OPERATE_MARGIN_TOP = 16; + public static PC_OPERATE_MARGIN_BUTTOM = 16; + + public static PC_DIALOG_WIDTH = 400; + public static PC_BUTTON_HEIGHT = 40; + + public static PC_RDIUS_16 = 16; + public static PC_RDIUS_8 = 8; + + public static PC_OUTLINE_COLOR = '#20FFFFFF'; + // ccm config path static CCM_CONFIG_PATH = "etc/notification/notification_config.json"; } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets index 766156628565fb5822b74f63c7b62065f71bb741..be487d359c36877c86a8a9992a09715788a28f64 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets @@ -14,6 +14,9 @@ */ import Constants from './constant'; +import { MeasureOptions } from '@ohos.measure'; +import { MeasureUtils } from '@ohos.arkui.UIContext'; +import common from '@ohos.app.ability.common'; /** * Omit display when application name is too long @@ -29,3 +32,39 @@ export function titleTrim(title: string): string { return title; } } + +export function calContainerWidth( + containerWidth: number, + options: MeasureOptions, + crossLineRatio: number, + measureUtils: MeasureUtils) : string | number { + let targetContainerWidth: string | number = 'auto'; + try { + let textWidth = px2vp(measureUtils.measureText(options)); + let ratio = (textWidth % containerWidth) / containerWidth; + let crossLineFlag: boolean = textWidth > containerWidth; + if (crossLineFlag && ratio < crossLineRatio) { + targetContainerWidth = containerWidth / Constants.CROSS_LINE_RESIZE_PARAM; + } + } catch (err) { + console.error(`refresh width failed, code=${err?.code0}, msg=${err?.message}.`); + } + return targetContainerWidth; + } + +export function getFontSizeScale(context: common.UIAbilityContext, maxScale: number = 3.2): number { + let fontSizeScale = context.config?.fontSizeScale; + console.log(`NotificationDialog_Service fontSizeScale = ${fontSizeScale}`); + if(fontSizeScale === undefined) { + return Constants.FONT_SCALE_DEFAULT; + } + return fontSizeScale > maxScale ? maxScale : fontSizeScale; +} + +export function sourceToVp(source: Resource): number { + return px2vp(getContext().resourceManager.getNumber(source.id)); +} + +export function getLimitFontSize(fontSizeScale: number, sourceFontSize: number): string { + return `${sourceFontSize * fontSizeScale}vp`; +} diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index 55c303f5dd1346abbeb4725a85dacea47573d017..bdc6bd9bcf140d8ef329684b68f3c1f2b13ae946 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -16,13 +16,21 @@ import bundleResourceManager from '@ohos.bundle.bundleResourceManager'; import display from '@ohos.display'; import window from '@ohos.window'; -import { titleTrim } from '../common/utils'; +import { + titleTrim, + calContainerWidth, + getFontSizeScale, + sourceToVp, + getLimitFontSize } from '../common/utils'; import Constants from '../common/constant'; import fs from '@ohos.file.fs'; import configPolicy from '@ohos.configPolicy'; import { EnableNotificationDialog } from '../ServiceExtAbility/NotificationServiceExtAbility'; import { Callback} from '@ohos.base'; import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; +import { MeasureOptions } from '@ohos.measure'; +import { MeasureUtils } from '@ohos.arkui.UIContext'; +import common from '@ohos.app.ability.common'; const TAG = 'NotificationDialog_Service '; const permission: Record = { @@ -34,40 +42,31 @@ const bottomPopoverTypes = ['default', 'phone']; let storage = LocalStorage.getShared(); -@Extend(Button) function rightCustomizeButton() { - .backgroundColor($r('sys.color.ohos_id_color_dialog_bg')) - .fontColor($r('sys.color.font_emphasize')) - .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) +@Extend(Button) function customizeButton() { + .backgroundColor(Color.Transparent) + .fontColor($r('app.color.button_text')) + .fontSize( + getLimitFontSize( + Constants.TEXT_MIDDLE_FONT_SIZE, + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) .fontWeight(FontWeight.Medium) .height(Constants.BUTTON_HEIGHT) .flexGrow(Constants.FLEX_GROW) - .margin({ - left: Constants.BUTTON_LEFT - }) -} - -@Extend(Button) function leftCustomizeButton() { - .backgroundColor($r('sys.color.ohos_id_color_dialog_bg')) - .fontColor($r('sys.color.font_emphasize')) - .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) - .fontWeight(FontWeight.Medium) - .height(Constants.BUTTON_HEIGHT) - .flexGrow(Constants.FLEX_GROW) - .margin({ - right: Constants.BUTTON_RIGHT - }) + .width('50%') } @Entry(storage) @Component struct NotificationDialogPage { - @State isUpdate: number = -1; + @StorageLink('isUpdate') isUpdate: number = 0; privacyDialogController: CustomDialogController = new CustomDialogController({ builder: PermissionDialog({ isUpdate: $isUpdate }), autoCancel: false, alignment: DialogAlignment.Center, customStyle: true, + maskColor: $r('app.color.mask_thin'), onWillDismiss: (dismissDialogAction: DismissDialogAction) => { console.info(TAG, `dialog onWillDismiss reason= : ${JSON.stringify(dismissDialogAction.reason)}`); } @@ -80,7 +79,6 @@ struct NotificationDialogPage { } onPageShow() { - this.isUpdate++; } } @@ -94,93 +92,107 @@ struct PermissionDialog { dialog?: EnableNotificationDialog; session?: UIExtensionContentSession; controller?: CustomDialogController; - panOption: PanGestureOptions = new PanGestureOptions({ - distance:100, - direction:PanDirection.Up - }); + @State titleContainerWidth: string | number = 'auto'; build() { - GridRow({ columns: { xs: Constants.XS_COLUMNS, sm: Constants.SM_COLUMNS, md: Constants.MD_COLUMNS, lg: Constants.LG_COLUMNS }, gutter: Constants.DIALOG_GUTTER }) { - GridCol({ span: { xs: Constants.XS_SPAN, sm: Constants.SM_SPAN, md: Constants.DIALOG_MD_SPAN, lg: Constants.DIALOG_LG_SPAN }, - offset: {xs: Constants.XS_OFFSET, sm: Constants.SM_OFFSET, md: Constants.DIALOG_MD_OFFSET, lg: Constants.DIALOG_LG_OFFSET} }) { - Flex({ justifyContent: FlexAlign.Center, alignItems: this.isBottomPopover ? ItemAlign.End : ItemAlign.Center }) { - Column() { - Image(permission.icon) - .width(Constants.DIALOG_ICON_WIDTH) - .height(Constants.DIALOG_ICON_HEIGHT) - .margin({ - top: Constants.DIALOG_ICON_MARGIN_TOP - }) - Scroll() { - Column() { - Row() { - Flex({ justifyContent: FlexAlign.Center }) { - Text() { - Span(getContext(this).resourceManager.getStringSync(permission.label.id).replace('%s', this.appName)) - } - .fontSize($r('sys.float.ohos_id_text_size_headline8')) - .fontColor($r('sys.color.ohos_id_color_text_primary')) - .fontWeight(FontWeight.Bold) - .lineHeight(Constants.DIALOG_REQ_LINE_HEIGHT) - .margin({ - top: Constants.DIALOG_REQ_MARGIN_TOP, - bottom:Constants.DIALOG_REQ_MARGIN_BUTTOM, - left: Constants.DIALOG_REQ_MARGIN_LEFT, - right: Constants.DIALOG_REQ_MARGIN_RIGHT - }) - .textAlign(TextAlign.Center) - } + Row(){ + Flex({ justifyContent: FlexAlign.Center, alignItems: this.isBottomPopover ? ItemAlign.End : ItemAlign.Center }) { + Column() { + Scroll() { + Column() { + Row() { + Image(permission.icon) + .width(Constants.DIALOG_ICON_WIDTH) + .height(Constants.DIALOG_ICON_HEIGHT) + .margin({ + top: Constants.DIALOG_ICON_MARGIN_TOP + }) + } + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text($r('app.string.group_label_notification', this.appName)) + .fontSize($r('sys.float.ohos_id_text_size_headline8')) + .fontColor($r('app.color.text_primary')) + .fontWeight(FontWeight.Bold) + .minFontSize( + getLimitFontSize(Constants.TITLE_MIN_FONT_SIZE, + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) + .maxFontSize( + getLimitFontSize(sourceToVp($r('sys.float.ohos_id_text_size_headline8')), + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) + .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST) + .maxLines(2) + .textOverflow({overflow: TextOverflow.Ellipsis}) + .width(this.titleContainerWidth) + .textAlign(TextAlign.Center) } - Row() { - Flex({ justifyContent: FlexAlign.Center }) { - Text() { - Span(permission.reason) - } - .fontSize(Constants.DIALOG_DESP_FONT_SIZE) - .fontWeight(FontWeight.Regular) - .fontColor($r('sys.color.ohos_id_color_text_primary')) - .lineHeight(Constants.DIALOG_DESP_LINE_HEIGHT) - .margin({ - top: Constants.DIALOG_DESP_MARGIN_TOP, - left: Constants.DIALOG_DESP_MARGIN_LEFT, - right: Constants.DIALOG_DESP_MARGIN_RIGHT, - bottom: Constants.DIALOG_DESP_MARGIN_BOTTOM - }) + .margin({ + top: Constants.DIALOG_REQ_MARGIN_TOP, + bottom:Constants.DIALOG_REQ_MARGIN_BUTTOM, + left: Constants.DIALOG_REQ_MARGIN_LEFT, + right: Constants.DIALOG_REQ_MARGIN_RIGHT + }) + .onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => { + let containerWidth = newValue.width as number; + let options: MeasureOptions = { + textContent: $r('app.string.group_label_notification', this.appName), + fontSize: getLimitFontSize(sourceToVp($r('sys.float.ohos_id_text_size_headline8')), + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)), + fontWeight: FontWeight.Bold, + }; + this.titleContainerWidth = calContainerWidth(containerWidth, options, + Constants.CROSS_LINE_RATIO, this.getUIContext().getMeasureUtils()); + console.info(TAG, `onSizeChange titleContainerWidth: ${this.titleContainerWidth}`); + }) + } + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text() { + Span(permission.reason) } + .fontSize(Constants.DIALOG_DESP_FONT_SIZE) + .fontWeight(FontWeight.Regular) + .fontColor($r('app.color.text_primary')) + .lineHeight(Constants.DIALOG_DESP_LINE_HEIGHT) + .margin({ + top: Constants.DIALOG_DESP_MARGIN_TOP, + left: Constants.DIALOG_DESP_MARGIN_LEFT, + right: Constants.DIALOG_DESP_MARGIN_RIGHT, + bottom: Constants.DIALOG_DESP_MARGIN_BOTTOM + }) } } - } - .constraintSize({ maxHeight: Constants.MAXIMUM_HEADER_HEIGHT }) - Row() { - Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { - Button($r('app.string.BAN')) - .onClick(async (): Promise => { - await this.enableNotification(false); - }) - .leftCustomizeButton() - Divider() - .color($r('sys.color.comp_divider')) - .vertical(true) - .height(Constants.DIVIDER_HEIGHT) - .strokeWidth(Constants.DIVIDER_WIDTH) - Button($r('app.string.ALLOW')) - .onClick(async (): Promise => { - await this.enableNotification(true); - }) - .rightCustomizeButton() + Row() { + Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Button($r('app.string.BAN')) + .onClick(async (): Promise => { + await this.enableNotification(false); + }) + .customizeButton() + Divider() + .color($r('app.color.comp_divider')) + .vertical(true) + .height(Constants.DIVIDER_HEIGHT) + .strokeWidth(Constants.DIVIDER_WIDTH) + .margin({left: Constants.BUTTON_LEFT, right: Constants.BUTTON_RIGHT}) + Button($r('app.string.ALLOW')) + .onClick(async (): Promise => { + await this.enableNotification(true); + }) + .customizeButton() + } + .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) } - .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) } } - .backgroundColor($r('sys.color.ohos_id_color_dialog_bg')) - .borderRadius(Constants.DIALOG_PRIVACY_BORDER_RADIUS) - .width(Constants.FULL_WIDTH) - .padding({ bottom: Constants.DIALOG_PADDING_BOTTOM }) - .margin({ bottom: $r('sys.float.ohos_id_dialog_margin_bottom') }) - .clip(true) } + .borderRadius(Constants.DIALOG_PRIVACY_BORDER_RADIUS) + .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) .width(Constants.FULL_WIDTH) - .height(Constants.FULL_HEIGHT) + .padding({ bottom: Constants.DIALOG_PADDING_BOTTOM }) + .clip(true) } } .margin({ @@ -188,14 +200,10 @@ struct PermissionDialog { right: this.isBottomPopover ? Constants.DIALOG_MARGIN_VERTICAL : Constants.DIALOG_MARGIN, bottom: this.isBottomPopover ? this.naviHeight : 0 }) - .gesture( - PanGesture(this.panOption) - .onActionStart((event:GestureEvent)=>{ - if (this.dialog?.stageModel == false) { - this.session?.terminateSelf(); - } - }) - ) + .constraintSize({ + maxHeight: Constants.MAXIMUM_HEADER_HEIGHT, + maxWidth: Constants.MAX_DIALOG_WIDTH + }) } async updateApplicationName(bundleName: string): Promise { @@ -208,7 +216,7 @@ struct PermissionDialog { this.appName = titleTrim(appName); console.info(TAG, `hap label: ${this.appName}`); } catch (err) { - console.error(TAG, `applicationName error : ${JSON.stringify(err)}`); + console.error(TAG, `applicationName error : ${err?.code}`); } } @@ -227,7 +235,7 @@ struct PermissionDialog { this.naviHeight = avoidArea.bottomRect.height; } } catch (err) { - console.error(TAG, `Failed to obtain the area. Cause: ${JSON.stringify(err)}`); + console.error(TAG, `Failed to obtain the area. Cause: ${err?.code}`); } } @@ -244,7 +252,7 @@ struct PermissionDialog { } } } catch (err) { - console.error(TAG, 'Failed to get the device foldable status. Code: ' + JSON.stringify(err)); + console.error(TAG, 'Failed to get the device foldable status. Code: ${err?.code}'); } // read ccm configs @@ -265,7 +273,7 @@ struct PermissionDialog { } } } catch (error) { - console.log(TAG, 'Failed get ccm files, Cause: ${JSON.stringify(err)}'); + console.log(TAG, 'Failed get ccm files, Cause: ${err?.code}'); } this.isBottomPopover = isBottomPopoverTemp && isVertical; } @@ -290,7 +298,7 @@ struct PermissionDialog { try { await this.updateStatus(); } catch (err) { - console.error(TAG, `aboutToAppear error : + ${JSON.stringify(err)}`); + console.error(TAG, `aboutToAppear error : ${err?.code}`); await this.dialog?.destroyException(); await this.session?.terminateSelf(); } @@ -305,13 +313,13 @@ struct PermissionDialog { await win.resize(dis.width, dis.height); await this.updateStatus(); } catch (err) { - console.error(TAG, 'Failed to touch callback. Code: ' + JSON.stringify(err)); + console.error(TAG, 'Failed to touch callback. Code: ${err?.code}'); } }; try { display.on('foldDisplayModeChange', callback); } catch (err) { - console.error(TAG, 'Failed to register callback. Code: ' + JSON.stringify(err)); + console.error(TAG, 'Failed to register callback. Code: ${err?.code}'); } } @@ -329,6 +337,7 @@ struct PermissionDialog { console.error(TAG, `NotificationDialog enable error, code is ${err?.code}`); await this.dialog?.destroyException(); } finally { + await this.dialog?.subWindow?.destroyWindow(); this.session?.terminateSelf(); } } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets new file mode 100644 index 0000000000000000000000000000000000000000..2e9c3e10347352448a1f50f77fd34bd9504cf798 --- /dev/null +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets @@ -0,0 +1,330 @@ +/* + * Copyright (c) 2023 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 bundleResourceManager from '@ohos.bundle.bundleResourceManager'; +import display from '@ohos.display'; +import window from '@ohos.window'; +import { + titleTrim, + calContainerWidth, + getFontSizeScale, + sourceToVp, + getLimitFontSize } from '../common/utils'; +import Constants from '../common/constant'; +import fs from '@ohos.file.fs'; +import configPolicy from '@ohos.configPolicy'; +import { EnableNotificationDialog } from '../ServiceExtAbility/NotificationServiceExtAbility'; +import { Callback} from '@ohos.base'; +import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; +import i18n from '@ohos.i18n'; +import { MeasureOptions } from '@ohos.measure'; +import { MeasureUtils } from '@ohos.arkui.UIContext'; +import common from '@ohos.app.ability.common'; + +const TAG = 'NotificationDialog_Service '; + +const LAN_EN = 'These may include banners, sounds and more. You can change this in Settings.'; +const LAN_CN = '通知提醒方式可能包括横幅、响铃等。可前往“设置” 更改。'; +const LAN_HK = '通知提醒方式可能包括橫幅、響鬧等。可前往「設定」更改。'; +const LAN_TW = '通知提醒方式可能包括橫幅、響鈴等。可前往「設定」變更。'; +const LAN_BO = 'བརྡ་ཐོ་དྲན་སྐུལ་གྱི་ཐབས་ལམ་ལ་སྒོ་ལྕགས་བརྙན་ཡོལ་དང་། འཕྲེད་བྱང་། དྲིལ་སྒྲ། སྦིར་བརྡ་སོགས་ཚུད་སྲིད། ༼སྒྲིག་འགོད་༽ལ་བསྐྱོད་ནས་བཅོས་ཆོག'; +const LAN_UG = 'قۇلۇپ ئېكرانى، بالداق، ئاۋاز ۋە تىترەش شۇلارنىڭ ئىچىدە. تەڭشەكتىن ئۆزگەرتەلەيسىز.'; + +const permission: Record = { + 'label': $r('app.string.group_label_notification'), + 'icon': $r('app.media.ic_public_ring'), + 'reason': $r('app.string.reason'), +}; + +let storage = LocalStorage.getShared(); + +@Extend(Button) function customizeButton() { + .type(ButtonType.Normal) + .backgroundColor($r('sys.color.comp_background_tertiary')) + .fontColor($r('sys.color.font_emphasize')) + .fontSize( + getLimitFontSize( + sourceToVp($r('sys.float.Body_L')), + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) + .fontWeight(FontWeight.Medium) + .height(Constants.PC_BUTTON_HEIGHT) + .width('50%') + .borderRadius(Constants.PC_RDIUS_8) + .flexGrow(Constants.FLEX_GROW) +} + +@Entry(storage) +@Component +struct NotificationDialogPage { + @StorageLink('isUpdate') isUpdate: number = 0; + + privacyDialogController: CustomDialogController = new CustomDialogController({ + builder: PermissionDialog({ isUpdate: $isUpdate }), + autoCancel: false, + alignment: DialogAlignment.Center, + customStyle: true, + cornerRadius: Constants.PC_RDIUS_16, + maskColor: $r('sys.color.ohos_id_color_mask_thin'), + onWillDismiss: (dismissDialogAction: DismissDialogAction) => { + console.info(TAG, `dialog onWillDismiss reason= : ${JSON.stringify(dismissDialogAction.reason)}`); + } + }); + + build() {} + + aboutToAppear() { + this.privacyDialogController.open(); + } + + onPageShow() { + } +} + +@CustomDialog +struct PermissionDialog { + @State appName: string = ''; + @State content: string = LAN_CN; + @State naviHeight: number = 0; + @State isBottomPopover: boolean = false; + @StorageLink('clicked') clicked: boolean = false; + @Link @Watch('updateOnPageShow') isUpdate: number; + dialog?: EnableNotificationDialog; + session?: UIExtensionContentSession; + controller?: CustomDialogController; + @State titleContainerWidth: string | number = 'auto'; + + build() { + Row() { + Flex({ justifyContent: FlexAlign.Center, alignItems: this.isBottomPopover ? ItemAlign.End : ItemAlign.Center }) { + Column() { + Scroll() { + Column() { + Row() { + Image(permission.icon) + .width(Constants.DIALOG_ICON_WIDTH) + .height(Constants.DIALOG_ICON_HEIGHT) + .margin({ + top: Constants.PC_ICON_MARGIN_TOP + }) + .draggable(false) + } + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text($r('app.string.group_label_notification', this.appName)) + .fontSize($r('sys.float.Title_S')) + .fontColor($r('sys.color.font_primary')) + .fontWeight(FontWeight.Bold) + .minFontSize( + getLimitFontSize(Constants.TITLE_MIN_FONT_SIZE, + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) + .maxFontSize( + getLimitFontSize(sourceToVp($r('sys.float.Title_S')), + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) + .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST) + .maxLines(2) + .textOverflow({overflow: TextOverflow.Ellipsis}) + .width(this.titleContainerWidth) + .textAlign(TextAlign.Center) + } + .margin({ + left: Constants.PC_TITLE_MARGIN_SIDE, + right: Constants.PC_TITLE_MARGIN_SIDE, + top: Constants.PC_TITLE_MARGIN_TOP, + }) + .onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => { + let containerWidth = newValue.width as number; + let options: MeasureOptions = { + textContent: $r('app.string.group_label_notification', this.appName), + fontSize: getLimitFontSize(sourceToVp($r('sys.float.Title_S')), + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)), + fontWeight: FontWeight.Bold, + }; + this.titleContainerWidth = calContainerWidth(containerWidth, options, + Constants.CROSS_LINE_RATIO, this.getUIContext().getMeasureUtils()); + console.info(TAG, `onSizeChange titleContainerWidth: ${this.titleContainerWidth}`); + }) + } + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text() { + Span(this.content) + } + .fontSize( + getLimitFontSize(sourceToVp($r('sys.float.Body_L')), + getFontSizeScale(getContext(this) as common.UIAbilityContext)) + ) + .fontWeight(FontWeight.Medium) + .fontColor($r('sys.color.font_primary')) + .margin({ + left: Constants.PC_CONTENT_MARGIN_SIDE, + right: Constants.PC_CONTENT_MARGIN_SIDE, + top: Constants.PC_CONTENT_MARGIN_TOP + }) + } + } + Row() { + Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Button($r('app.string.BAN')) + .onClick(async (): Promise => { + await this.enableNotification(false); + }) + .customizeButton() + Divider() + .color($r('sys.color.comp_divider')) + .vertical(true) + .height(Constants.DIVIDER_HEIGHT) + .strokeWidth(Constants.DIVIDER_WIDTH) + .margin({left: Constants.BUTTON_LEFT, right: Constants.BUTTON_RIGHT}) + Button($r('app.string.ALLOW')) + .onClick(async (): Promise => { + await this.enableNotification(true); + }) + .customizeButton() + } + .margin({ + left: Constants.PC_OPERATE_MARGIN_SIDE, + right: Constants.PC_OPERATE_MARGIN_SIDE, + top: Constants.PC_OPERATE_MARGIN_TOP, + bottom: Constants.PC_OPERATE_MARGIN_BUTTOM + }) + } + } + } + .constraintSize({ maxHeight: Constants.MAXIMUM_HEADER_HEIGHT }) + } + .borderRadius(Constants.PC_RDIUS_16) + .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) + .width(Constants.PC_DIALOG_WIDTH) + .outline({ + width: 1, + color: Constants.PC_OUTLINE_COLOR, + radius: Constants.PC_RDIUS_16 + }) + .clip(true) + } + .width(Constants.FULL_WIDTH) + .height(Constants.FULL_HEIGHT) + } + } + + async aboutToAppear(): Promise { + this.dialog = storage.get('dialog') as EnableNotificationDialog; + this.session = storage.get('session') as UIExtensionContentSession; + this.updateAvoidWindow(); + this.updateSubWindowSize(); + try { + await this.updateStatus(); + } catch (err) { + console.error(TAG, `aboutToAppear error : ${err?.code}`); + await this.dialog?.destroyException(); + await this.session?.terminateSelf(); + } + } + + async aboutToDisappear(): Promise { + console.info(TAG, `aboutToDisappear`); + this.session?.terminateSelf(); + } + + async updateOnPageShow(): Promise { + if (this.isUpdate > 0) { + await this.updateStatus(); + } + } + + async updateStatus(): Promise { + let bundleNameObj = this.dialog?.want.parameters?.bundleName; + let bundleName = bundleNameObj ? bundleNameObj.toString() : ''; + await this.updateApplicationName(bundleName); + } + + async updateApplicationName(bundleName: string): Promise { + console.info(TAG, `updateApplicationName bundleName: ${bundleName}`); + try { + let bundleFlags = bundleResourceManager.ResourceFlag.GET_RESOURCE_INFO_ALL; + let resourceInfo = bundleResourceManager.getBundleResourceInfo(bundleName, bundleFlags); + console.info(TAG, `applicationName name : ${JSON.stringify(resourceInfo.label)}`); + let appName = resourceInfo.label; + this.appName = titleTrim(appName); + console.info(TAG, `hap label: ${this.appName}`); + + let systemLanguage: string = i18n.System.getSystemLanguage(); + console.info(TAG, `language: ${systemLanguage}`); + if (systemLanguage.indexOf('zh-Hans') != -1) { + this.content = LAN_CN; + } else if (systemLanguage.indexOf('zh-Hant') != -1) { + this.content = LAN_TW; + } else if (systemLanguage.indexOf('en') != -1) { + this.content = LAN_EN; + } else if (systemLanguage.indexOf('ug') != -1) { + this.content = LAN_UG; + } else if (systemLanguage.indexOf('bo') != -1) { + this.content = LAN_BO; + } + + } catch (err) { + console.error(TAG, `applicationName error : ${err?.code}`); + } + } + + updateAvoidWindow(): void { + let type = window.AvoidAreaType.TYPE_SYSTEM; + try { + this.dialog?.extensionWindow.on('avoidAreaChange', (data): void => { + if (data.type == window.AvoidAreaType.TYPE_SYSTEM) { + console.info(TAG, `avoidAreaChange: ${JSON.stringify(data)}`); + this.naviHeight = data.area.bottomRect.height; + } + }); + let avoidArea = this.dialog?.extensionWindow.getWindowAvoidArea(type); + if (avoidArea != undefined) { + console.info(TAG, `avoidArea: ${JSON.stringify(avoidArea)}`); + this.naviHeight = avoidArea.bottomRect.height; + } + } catch (err) { + console.error(TAG, `Failed to obtain the area. Cause: ${err?.code}`); + } + } + + updateSubWindowSize(): void { + try { + this.dialog?.extensionWindow.on('windowSizeChange', (data):void => { + let windowRect = this.dialog?.extensionWindow.properties?.uiExtensionHostWindowProxyRect; + console.info(TAG, `windowSizeChange event, size = ${windowRect?.left}-${windowRect?.top}-${windowRect?.width}-${windowRect?.height}`); + this.dialog?.subWindow?.moveWindowTo(windowRect?.left, windowRect?.top); + this.dialog?.subWindow?.resize(windowRect?.width, windowRect?.height); + }); + } catch (err) { + console.error(TAG, `updateSubWindowSize error. Cause: ${err?.code}`); + } + } + + async enableNotification(enabled: boolean): Promise { + console.info(TAG, `NotificationDialog enableNotification: ${enabled}`); + try { + await this.dialog?.publishButtonClickedEvent(enabled); + this.clicked = true; + } catch (err) { + console.error(TAG, `NotificationDialog enable error, code is ${err?.code}`); + await this.dialog?.destroyException(); + } finally { + await this.dialog?.subWindow?.destroyWindow(); + this.session?.terminateSelf(); + } + } +} \ No newline at end of file diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/watchNotificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/watchNotificationDialog.ets new file mode 100644 index 0000000000000000000000000000000000000000..7fa6ab181f22a80db9e0f93240100f7562e0bc64 --- /dev/null +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/watchNotificationDialog.ets @@ -0,0 +1,272 @@ +/* + * Copyright (c) 2023 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 bundleResourceManager from '@ohos.bundle.bundleResourceManager'; +import display from '@ohos.display'; +import window from '@ohos.window'; +import { titleTrim } from '../common/utils'; +import Constants from '../common/constant'; +import fs from '@ohos.file.fs'; +import configPolicy from '@ohos.configPolicy'; +import { EnableNotificationDialog } from '../ServiceExtAbility/NotificationServiceExtAbility'; +import { Callback} from '@ohos.base'; +import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; + +const TAG = 'NotificationDialog_Service '; +const permission: Record = { + 'label': $r('app.string.group_label_notification'), + 'icon': $r('app.media.ic_public_ring'), + 'reason': $r('app.string.reason'), +}; + +let storage = LocalStorage.getShared(); + +@Entry(storage) +@Component +struct NotificationDialogPage { + @StorageLink('isUpdate') isUpdate: number = -1; + privacyDialogController: CustomDialogController = new CustomDialogController({ + builder: PermissionDialog({ isUpdate: $isUpdate }), + autoCancel: false, + alignment: DialogAlignment.TopStart, + customStyle: false, + onWillDismiss: (dismissDialogAction: DismissDialogAction) => { + console.info(TAG, `dialog onWillDismiss reason= : ${JSON.stringify(dismissDialogAction.reason)}`); + }, + width: '466px', + height: '466px' + }); + + build() {} + + aboutToAppear() { + this.privacyDialogController.open(); + } + + onPageShow() { + this.isUpdate++; + } +} + +@CustomDialog +struct PermissionDialog { + @State appName: string = ''; + @State isBottomPopover: boolean = true; + @StorageLink('clicked') clicked: boolean = false; + @Link @Watch('updateOnPageShow') isUpdate: number; + dialog?: EnableNotificationDialog; + session?: UIExtensionContentSession; + controller?: CustomDialogController; + + build() { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Column() { + Image(permission.icon) + .width('92px') + .height('92px') + .margin({ + top: '2%' + }) + + Scroll() { + Column() { + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text() { + Span(getContext(this).resourceManager.getStringSync(permission.label.id).replace('%s', this.appName)) + } + .fontSize('38px') + .fontColor('#FFFFFF') + .fontWeight(500) + .lineHeight('45px') + .margin({ + top: '4.1%', + left: '11.2%', + right: '11.2%' + }) + .textAlign(TextAlign.Center) + } + } + + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Button($r('app.string.ALLOW')) + .onClick(async (): Promise => { + await this.enableNotification(true); + }) + .backgroundColor('#1F71FF') + .width('232px') + .height('80px') + .fontColor('#FFFFFF') + .fontSize('30px') + .fontWeight(500) + } + .margin({top:'4.1%'}) + } + + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Button($r('app.string.BAN')) + .onClick(async (): Promise => { + await this.enableNotification(false); + }) + .backgroundColor('#255EA1FF') + .width('232px') + .height('80px') + .fontColor('#5EA1FF') + .fontSize('30px') + .fontWeight(500) + } + .margin({top:'4.1%'}) + } + } + } + .scrollable(ScrollDirection.Vertical) + .scrollBar(BarState.Off) + } + } + .margin({ + top: 0, + left: 0, + right: 0, + bottom: 0 + }) + .width('100%') + .height('100%') + .backgroundColor('#35000000') + .backgroundEffect({ + radius: 20, + saturation: 50, + adaptiveColor: AdaptiveColor.AVERAGE, + blurOptions: { + grayscale: [35, 35] + } + }) + + } + + async updateApplicationName(bundleName: string): Promise { + console.info(TAG, `updateApplicationName bundleName: ${bundleName}`); + try { + let bundleFlags = bundleResourceManager.ResourceFlag.GET_RESOURCE_INFO_ALL; + let resourceInfo = bundleResourceManager.getBundleResourceInfo(bundleName, bundleFlags); + console.info(TAG, `applicationName name : ${JSON.stringify(resourceInfo.label)}`); + let appName = resourceInfo.label; + this.appName = titleTrim(appName); + console.info(TAG, `hap label: ${this.appName}`); + } catch (err) { + console.error(TAG, `applicationName error : ${err?.code}`); + } + } + + async updateIsBottomPopover(): Promise { + let dis = display.getDefaultDisplaySync(); + let isVertical = dis.width <= dis.height; + try { + if (display.isFoldable()) { + let foldStatus = display.getFoldStatus(); + if (foldStatus == display.FoldStatus.FOLD_STATUS_EXPANDED || + foldStatus == display.FoldStatus.FOLD_STATUS_HALF_FOLDED) { + this.isBottomPopover = false; + return; + } + } + } catch (err) { + console.error(TAG, 'Failed to get the device foldable status. Code: ${err?.code}'); + } + + // read ccm configs + let isBottomPopoverTemp = false; + try { + let filePaths = await configPolicy.getCfgFiles(Constants.CCM_CONFIG_PATH); + for (let i = 0; i < filePaths.length; i++) { + let res = fs.accessSync(filePaths[i]); + if (res) { + let fileContent = fs.readTextSync(filePaths[i]); + let config: NotificationConfig = JSON.parse(fileContent); + if (config.notificationAuthorizationWindow != undefined) { + let windowConfig: NotificationAuthorizationWindow = config.notificationAuthorizationWindow; + if (windowConfig.isBottomPopover != undefined) { + isBottomPopoverTemp = windowConfig.isBottomPopover; + } + } + } + } + } catch (error) { + console.log(TAG, 'Failed get ccm files, Cause: ${err?.code}'); + } + this.isBottomPopover = isBottomPopoverTemp && isVertical; + } + + async updateStatus(): Promise { + let bundleNameObj = this.dialog?.want.parameters?.bundleName; + let bundleName = bundleNameObj ? bundleNameObj.toString() : ''; + await this.updateApplicationName(bundleName); + await this.updateIsBottomPopover(); + } + + async updateOnPageShow(): Promise { + if (this.isUpdate > 0) { + await this.updateStatus(); + } + } + + async aboutToAppear(): Promise { + this.dialog = storage.get('dialog') as EnableNotificationDialog; + this.session = storage.get('session') as UIExtensionContentSession; + try { + await this.updateStatus(); + } catch (err) { + console.error(TAG, `aboutToAppear error : ${err?.code}`); + await this.dialog?.destroyException(); + await this.session?.terminateSelf(); + } + } + + async aboutToDisappear(): Promise { + console.info(TAG, `aboutToDisappear`); + this.session?.terminateSelf(); + } + + async enableNotification(enabled: boolean): Promise { + console.info(TAG, `NotificationDialog enableNotification: ${enabled}`); + try { + await this.dialog?.publishButtonClickedEvent(enabled); + this.clicked = true; + } catch (err) { + console.error(TAG, `NotificationDialog enable error, code is ${err?.code}`); + await this.dialog?.destroyException(); + } finally { + await this.dialog?.subWindow?.destroyWindow(); + this.session?.terminateSelf(); + } + } +} + +interface NotificationConfig { + notificationAuthorizationWindow: NotificationAuthorizationWindow; +} + +interface NotificationAuthorizationWindow { + isBottomPopover: boolean; +} + +interface NotificationConfigAbc { + deviceType: DeviceType; +} + +interface DeviceType { + isWatch: boolean; +} diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json index 1bfac1a96a13b0840b57e9dd5ad34075ff20140d..ebd7a89e8a3f16c663eccf25438382c1c390ede1 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json @@ -8,7 +8,8 @@ "deviceTypes": [ "default", "tablet", - "2in1" + "2in1", + "wearable" ], "deliveryWithInstall": true, "installationFree": false, @@ -22,7 +23,8 @@ "icon": "$media:icon", "label": "$string:NotificationServiceExtAbility_label", "exported":true, - "type": "sysDialog/common" + "type": "sysDialog/common", + "extensionProcessMode": "instance" } ], "requestPermissions": [ diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json index 95f6870e2b079e5f72d7c8b1f17a8fab54ee5709..84e0cfbe62795baa9e8df24d698e93fc9b1ca3f8 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json @@ -15,6 +15,26 @@ { "name": "button_color", "value": "#007DFF" + }, + { + "name": "text_primary", + "value": "#E5000000" + }, + { + "name": "comp_divider", + "value": "#33000000" + }, + { + "name": "dialog_bg", + "value": "#FFFFFF" + }, + { + "name": "button_text", + "value": "#0A59F7" + }, + { + "name": "mask_thin", + "value": "#33000000" } ] } \ No newline at end of file diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/string.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/string.json index 6057c4b7d3849e5c1e0307fea8ac4526e396b2ed..da8c2f069067dce9a4e0c21a6e99d4947293f0f4 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/string.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/string.json @@ -14,7 +14,7 @@ }, { "name": "reason", - "value": "May include lock screen notifications, banners, sounds, vibrations, and more. You can change this in Settings." + "value": "These may include lock screen notifications, banners, sounds, vibrations, and more. You can change this in Settings." }, { "name": "ALLOW", diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json index ecceb635d8686b09b77a4916599278bbfb117f31..324b89a258c199f00765b49042f69a14e8c3d17a 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json @@ -1,5 +1,7 @@ { "src": [ - "pages/notificationDialog" + "pages/notificationDialog", + "pages/watchNotificationDialog", + "pages/pcNotificationDialog" ] -} +} \ No newline at end of file diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..80bcbe0f43b093fa5d2d98f8683745d903757034 --- /dev/null +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json @@ -0,0 +1,24 @@ +{ + "color": [ + { + "name": "text_primary", + "value": "#DBFFFFFF" + }, + { + "name": "comp_divider", + "value": "#33FFFFFF" + }, + { + "name": "dialog_bg", + "value": "#202224" + }, + { + "name": "button_text", + "value": "#5291FF" + }, + { + "name": "mask_thin", + "value": "#66000000" + } + ] + } \ No newline at end of file diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/ug/element/string.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/ug/element/string.json index 221c6c6007051b6c5e2a1408c944df61c8be377c..2bc9b3ed16d6f3fd7767a16976942f40bd6c8806 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/ug/element/string.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/ug/element/string.json @@ -26,7 +26,7 @@ }, { "name": "group_label_notification", - "value": "\\u200f«%s» نىڭ ئۇقتۇرۇش يوللىشىغا رۇخسەتمۇ؟" + "value": "\u200f«%s» نىڭ ئۇقتۇرۇش يوللىشىغا رۇخسەتمۇ؟" } ] } diff --git a/services/dialog_ui/enable_notification_dialog/publicity.xml b/services/dialog_ui/enable_notification_dialog/publicity.xml index ba2e4eea972d60c03643fff19b7dc2c7df1362b7..e65a1ccf42fc690e4ec609e9d51e7ea3f15cf23b 100644 --- a/services/dialog_ui/enable_notification_dialog/publicity.xml +++ b/services/dialog_ui/enable_notification_dialog/publicity.xml @@ -1,18 +1,18 @@ -/* - * Copyright (c) 2023 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. - */ + \ No newline at end of file diff --git a/services/distributed/test/unittest/distributed_preferences_test.cpp b/services/distributed/test/unittest/distributed_preferences_test.cpp index 22504c93e8bb4da62b12e0ef48f59067b5b4ca6d..b2d15d12b5e14cb8eabfba7e7b8756b4518bc005 100644 --- a/services/distributed/test/unittest/distributed_preferences_test.cpp +++ b/services/distributed/test/unittest/distributed_preferences_test.cpp @@ -101,7 +101,7 @@ HWTEST_F(DistributedPreferencesTest, SetDistributedBundleEnable_00200, Function */ HWTEST_F(DistributedPreferencesTest, ClearDataInRestoreFactorySettings_00100, Function | SmallTest | Level1) { - EXPECT_EQ(distributedPreferences_->ClearDataInRestoreFactorySettings(), ERR_ANS_DISTRIBUTED_OPERATION_FAILED); + EXPECT_EQ(distributedPreferences_->ClearDataInRestoreFactorySettings(), ERR_OK); } /** diff --git a/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp b/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp index 448b497db214dc9b770e83bfabfeb0cada525b0f..dc1eb3649b81ff867649248af56b97109b8fa6e8 100644 --- a/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp +++ b/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp @@ -14,7 +14,7 @@ */ #include - +#include "ans_inner_errors.h" #include "gtest/gtest.h" #define private public #include "distributed_screen_status_manager.h" @@ -52,7 +52,8 @@ HWTEST_F(DistributedScreenStatusManagerTest, CheckRemoteDevicesIsUsing_00100, Fu { bool isUsing = true; - EXPECT_EQ(distributedScreenStatusManager_->CheckRemoteDevicesIsUsing(isUsing), ERR_OK); + EXPECT_EQ(distributedScreenStatusManager_->CheckRemoteDevicesIsUsing(isUsing), + ERR_ANS_DISTRIBUTED_OPERATION_FAILED); } /** @@ -64,7 +65,7 @@ HWTEST_F(DistributedScreenStatusManagerTest, SetLocalScreenStatus_00100, Functio { bool screenOn = false; - EXPECT_EQ(distributedScreenStatusManager_->SetLocalScreenStatus(screenOn), ERR_OK); + EXPECT_EQ(distributedScreenStatusManager_->SetLocalScreenStatus(screenOn), ERR_ANS_DISTRIBUTED_OPERATION_FAILED); } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp index 4f79e8c7b4506778a2ee1b389fe3921018ce8be0..d58a998297d47558db0d12b5240cd39ec4f30695 100644 --- a/services/test/moduletest/ans_module_test.cpp +++ b/services/test/moduletest/ans_module_test.cpp @@ -192,7 +192,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_003, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetStatusBarText("text"); - + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); g_advancedNotificationService->SetNotificationsEnabledForBundle("", false); g_advancedNotificationService->Publish(label, req); @@ -237,11 +241,17 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_005, Function | SmallTest | Level1) // create request std::string label = "testLabel"; + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); req->SetLabel(label); req1->SetLabel(label); - + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetContent(content2); + req1->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req1->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); g_advancedNotificationService->Publish(label, req1); @@ -276,6 +286,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_006, Function | SmallTest | Level1) std::string label = "testLabel"; sptr req = new NotificationRequest(0); req->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -320,10 +335,17 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_007, Function | SmallTest | Level1) // create request std::string label = "testLabel"; + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); req->SetLabel(label); req1->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetContent(content2); + req1->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req1->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -359,6 +381,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0013, Function | SmallTest | Level1) std::string label = "testLabel"; sptr req = new NotificationRequest(0); req->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1224,6 +1251,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0058, Function | SmallTest | Level1) req->SetLabel(label); req->SetStatusBarText("text"); req->SetBadgeNumber(1); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // SetShowBadgeEnabledForBundle true sptr bundleOption = new NotificationBundleOption("bundleName", 0); @@ -1271,10 +1303,17 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0062, Function | SmallTest | Level1) // create request std::string label = "testLabel"; + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); req->SetLabel(label); req1->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetContent(content2); + req1->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req1->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1316,10 +1355,17 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0063, Function | SmallTest | Level1) // create request std::string label = "testLabel"; + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); req->SetLabel(label); req1->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetContent(content2); + req1->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req1->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1378,6 +1424,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0066, Function | SmallTest | Level1) std::string label = "testLabel"; sptr req = new NotificationRequest(0); req->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1458,6 +1509,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0101, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetWantAgent(agent); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1491,6 +1547,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0102, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetWantAgent(agent); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1524,6 +1585,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0103, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetWantAgent(agent); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1586,6 +1652,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0106, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetWantAgent(agent); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -2166,11 +2237,15 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0123, Function | SmallTest | Level1) slots.push_back(new NotificationSlot(NotificationConstant::SlotType::OTHER)); slots.push_back(new NotificationSlot(NotificationConstant::SlotType::CUSTOM)); EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), 0); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); sptr req2 = new NotificationRequest(2); sptr req3 = new NotificationRequest(3); sptr req4 = new NotificationRequest(4); + req->SetLabel("testLabel"); req1->SetLabel("testLabel"); req2->SetLabel("testLabel"); @@ -2182,6 +2257,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0123, Function | SmallTest | Level1) req2->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); req3->SetSlotType(NotificationConstant::SlotType::OTHER); req4->SetSlotType(NotificationConstant::SlotType::CUSTOM); + req->SetContent(content2); + req1->SetContent(content2); + req2->SetContent(content2); + req3->SetContent(content2); + req4->SetContent(content2); g_advancedNotificationService->Publish("testLabel", req); std::this_thread::sleep_for(std::chrono::milliseconds(200)); @@ -2268,7 +2348,10 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0125, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); @@ -2497,6 +2580,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0132, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetStatusBarText("text"); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); @@ -2533,6 +2621,10 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0133, Function | SmallTest | Level1) req->SetLabel(label); req->SetStatusBarText("text"); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); @@ -2575,6 +2667,10 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0134, Function | SmallTest | Level1) req->SetLabel(label); req->SetStatusBarText("text"); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); @@ -2617,6 +2713,10 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0135, Function | SmallTest | Level1) req->SetLabel(label); req->SetStatusBarText("text"); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); diff --git a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp index 080c28ec373d34c42a69bb3bc304403ffabf923a..16c66878978cc80d97d56de510b971dc95adcfa9 100644 --- a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp @@ -65,5 +65,10 @@ void BundleManagerHelper::Connect() void BundleManagerHelper::Disconnect() {} + +bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) +{ + return true; +} } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS 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 index e0d31ddac910268673f2f3f4bbc8f0bed9c060d2..127129e1b0ab2b91b86edcd72a0b7c6b89b32f6a 100644 --- a/test/bechmarktest/notification_services_test/mock/mock_bundle_manager_helper.cpp +++ b/test/bechmarktest/notification_services_test/mock/mock_bundle_manager_helper.cpp @@ -68,5 +68,10 @@ bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &b return true; } #endif + +bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) +{ + return true; +} } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp b/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp index 71e6f7cda201c71442042fdd4e7eb1c037cca371..ebb7c6f67647929a4a593e3a29c4e3334057f6c9 100644 --- a/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp +++ b/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp @@ -44,6 +44,12 @@ namespace OHOS { MessageParcel datas; MessageParcel reply; MessageOption flags; + // test HandleIsNeedSilentInDoNotDisturbMode function + ansManagerStub.HandleIsNeedSilentInDoNotDisturbMode(datas, reply); + // test HandleRegisterSwingCallback function + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED + ansManagerStub.HandleRegisterSwingCallback(datas, reply); + #endif ansManagerStub.OnRemoteRequest(0, datas, reply, flags); ansManagerStub.OnRemoteRequest((int) Notification::NotificationInterfaceCode::PUBLISH_NOTIFICATION, datas, reply, flags); @@ -311,6 +317,9 @@ namespace OHOS { datas.WriteString(stringData); datas.WriteInt32(intData); ansManagerStub.HandleSetTargetDeviceStatus(datas, reply); + datas.WriteInt32(intData); + datas.WriteBool(boolData); + ansManagerStub.HandleUpdateNotificationTimerByUid(datas, reply); sptr notification2 = new Notification::NotificationRequest(); notification2->SetOwnerUid(fuzzData.GenerateRandomInt32()); notification2->SetCreatorUid(fuzzData.GenerateRandomInt32()); diff --git a/test/fuzztest/anssubscriberstub_fuzzer/anssubscriberstub_fuzzer.cpp b/test/fuzztest/anssubscriberstub_fuzzer/anssubscriberstub_fuzzer.cpp index a9aac1a989e627f19eef01865051dbbc3a97a0ff..68e82b5a5cf91b0e2f6f8cd15adb5fa989f63c17 100644 --- a/test/fuzztest/anssubscriberstub_fuzzer/anssubscriberstub_fuzzer.cpp +++ b/test/fuzztest/anssubscriberstub_fuzzer/anssubscriberstub_fuzzer.cpp @@ -16,6 +16,7 @@ #define private public #define protected public #include "ans_subscriber_stub.h" +#include "ans_subscriber_local_live_view_stub.h" #undef private #undef protected #include "ans_permission_def.h" @@ -26,6 +27,7 @@ namespace OHOS { bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) { Notification::AnsSubscriberStub ansSubscriberStub; + Notification::AnsSubscriberLocalLiveViewStub ansSubscriberLocalLiveViewStub; uint32_t code = GetU32Data(data); MessageParcel datas; MessageParcel reply; @@ -64,6 +66,20 @@ namespace OHOS { ansSubscriberStub.OnDoNotDisturbDateChange(date); // test OnEnabledNotificationChanged function sptr callbackData = new Notification::EnabledNotificationCallbackData(); + // test HandleOnBadgeEnabledChanged function + ansSubscriberStub.HandleOnBadgeEnabledChanged(datas, reply); + // test HandleOnResponse function + ansSubscriberLocalLiveViewStub.HandleOnResponse(datas, reply); + // test HandleOnConsumedListMap function + ansSubscriberStub.HandleOnConsumedListMap(datas, reply); + // test HandleOnDisconnected function + ansSubscriberLocalLiveViewStub.HandleOnDisconnected(datas, reply); + // test HandleOnBadgeChanged function + ansSubscriberStub.HandleOnBadgeChanged(datas, reply); + // test HandleOnCanceledListMap function + ansSubscriberStub.HandleOnCanceledListMap(datas, reply); + // test HandleOnConnected function + ansSubscriberLocalLiveViewStub.HandleOnConnected(datas, reply); return true; } } diff --git a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp index c1656f7b5e2ec201f5e2d88528d8efff082b8c8b..8d71f119088caac287c64491c6be1f7d86e29e71 100644 --- a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp +++ b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp @@ -33,6 +33,7 @@ namespace OHOS { Notification::ReminderDataManager::InitInstance(nullptr); auto manager = Notification::ReminderDataManager::GetInstance(); + manager->Init(false); manager->Dump(); manager->CancelAllReminders(bundleName, userId, uid); sptr option = new Notification::NotificationBundleOption( @@ -55,7 +56,8 @@ namespace OHOS { manager->RegisterConfigurationObserver(); manager->OnUserRemove(userId); - manager->OnServiceStart(); + manager->OnBundleMgrServiceStart(); + manager->OnAbilityMgrServiceStart(); manager->OnUserSwitch(userId); manager->OnProcessDiedLocked(option); manager->RefreshRemindersDueToSysTimeChange(type); @@ -66,10 +68,6 @@ namespace OHOS { manager->HandleCustomButtonClick(want); manager->ClickReminder(want); manager->TerminateAlerting(want); - AppExecFwk::BundleInfo bundleInfo; - manager->GetBundleResMgr(bundleInfo); - manager->UpdateReminderLanguage(reminder); - manager->UpdateReminderLanguageLocked(reminder); return true; } @@ -110,23 +108,32 @@ namespace OHOS { manager->RemoveReminderLocked(reminderId); manager->SetActiveReminder(reminder); manager->SetAlertingReminder(reminder); - manager->ShowActiveReminderExtendLocked(reminder); + manager->ShowActiveReminderExtendLocked(reminder, reminders); std::vector> extensionReminders; std::vector> immediatelyReminders; manager->PublishReminder(reminder, option); manager->FindReminderRequestLocked(reminderId); manager->FindReminderRequestLocked(reminderId, bundleName); - manager->FindNotificationBundleOption(reminderId); manager->GetRecentReminderLocked(); manager->HandleImmediatelyShow(immediatelyReminders, value); - manager->HandleExtensionReminder(extensionReminders); + manager->HandleExtensionReminder(extensionReminders, 0); manager->HandleSameNotificationIdShowing(reminder); manager->IsBelongToSameApp(option, option); manager->CheckIsSameApp(reminder, option); manager->ShowReminder(reminder, value, value, value, value); return true; } + + bool Clear() + { + auto manager = Notification::ReminderDataManager::GetInstance(); + if (manager->queue_ != nullptr) { + auto handler = manager->queue_->submit_h(std::bind([]() {})); + manager->queue_->wait(handler); + } + return true; + } } /* Fuzzer entry point */ @@ -137,6 +144,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) if (ch != nullptr && size >= GetU32Size()) { OHOS::DoSomethingInterestingWithManager(ch, size); OHOS::DoSomethingInterestingWithReminder(ch, size); + OHOS::Clear(); free(ch); ch = nullptr; } diff --git a/test/fuzztest/reminderrequest_fuzzer/reminderrequest_fuzzer.cpp b/test/fuzztest/reminderrequest_fuzzer/reminderrequest_fuzzer.cpp index 1b5cd73e955447110fcc26ff75536dc20bfaa45a..8cc3dfb7a70c3c88ac5fc60b76f846330be5462f 100644 --- a/test/fuzztest/reminderrequest_fuzzer/reminderrequest_fuzzer.cpp +++ b/test/fuzztest/reminderrequest_fuzzer/reminderrequest_fuzzer.cpp @@ -24,7 +24,6 @@ namespace OHOS { namespace { constexpr uint8_t ENABLE = 2; constexpr uint8_t ACTION_BUTTON_TYPE = 3; - constexpr uint8_t COLUMN_TYPE = 2; constexpr uint8_t SLOT_TYPE_NUM = 5; } bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) @@ -65,16 +64,7 @@ namespace OHOS { reminderRequest.OnStop(); reminderRequest.OnTerminate(); reminderRequest.OnTimeZoneChange(); - std::shared_ptr resultSet = - std::make_shared(); - uint8_t column = *data % COLUMN_TYPE; - Notification::ReminderRequest::DbRecoveryType columnType = - Notification::ReminderRequest::DbRecoveryType(column); - reminderRequest.RecoverInt64FromDb(resultSet, stringData, columnType); - reminderRequest.RecoverFromDb(resultSet); - reminderRequest.RecoverActionButton(resultSet); reminderRequest.StringSplit(stringData, stringData); - reminderRequest.RecoverWantAgent(stringData, *data); std::shared_ptr< Notification::ReminderRequest::MaxScreenAgentInfo> maxScreenWantAgentInfo = std::make_shared< Notification::ReminderRequest::MaxScreenAgentInfo>(); reminderRequest.SetMaxScreenWantAgentInfo(maxScreenWantAgentInfo); diff --git a/test/fuzztest/reminderrequestalarm_fuzzer/reminderrequestalarm_fuzzer.cpp b/test/fuzztest/reminderrequestalarm_fuzzer/reminderrequestalarm_fuzzer.cpp index ab204c921155489fbd1feac82f30403bddee902d..0f5017f9265f9fc41d6ae0c8f3f7eb966cd95001 100644 --- a/test/fuzztest/reminderrequestalarm_fuzzer/reminderrequestalarm_fuzzer.cpp +++ b/test/fuzztest/reminderrequestalarm_fuzzer/reminderrequestalarm_fuzzer.cpp @@ -69,10 +69,6 @@ namespace OHOS { Parcel parcel; rrc->Unmarshalling(parcel); rrc->ReadFromParcel(parcel); - // test RecoverFromDb function - std::shared_ptr resultSet = - std::make_shared(); - rrc->RecoverFromDb(resultSet); return rrc->Marshalling(parcel); } } diff --git a/test/fuzztest/reminderrequestannexthree_fuzzer/reminderrequestannexthree_fuzzer.cpp b/test/fuzztest/reminderrequestannexthree_fuzzer/reminderrequestannexthree_fuzzer.cpp index 707db3d974416ee9294271090678279032aeb15f..138a456e393f21ee6c8f79220297e640c0152bb2 100644 --- a/test/fuzztest/reminderrequestannexthree_fuzzer/reminderrequestannexthree_fuzzer.cpp +++ b/test/fuzztest/reminderrequestannexthree_fuzzer/reminderrequestannexthree_fuzzer.cpp @@ -32,8 +32,6 @@ namespace OHOS { int32_t cTime = static_cast(GetU32Data(data)); reminderRequest.GetActualTime(type, cTime); reminderRequest.GetCTime(type, cTime); - int32_t uid = static_cast(GetU32Data(data)); - reminderRequest.GetUserId(uid); return reminderRequest.IsAlerting(); } } diff --git a/test/fuzztest/reminderrequestcalendar_fuzzer/reminderrequestcalendar_fuzzer.cpp b/test/fuzztest/reminderrequestcalendar_fuzzer/reminderrequestcalendar_fuzzer.cpp index 6c424704417771b8a297fb823ceccd55d6f154c4..2d5ab8ba6b4e0ca5f886bb0b9443715f1c84fe11 100644 --- a/test/fuzztest/reminderrequestcalendar_fuzzer/reminderrequestcalendar_fuzzer.cpp +++ b/test/fuzztest/reminderrequestcalendar_fuzzer/reminderrequestcalendar_fuzzer.cpp @@ -95,10 +95,6 @@ namespace OHOS { reminderRequestCalendar.UpdateNextReminder(); // test PreGetNextTriggerTimeIgnoreSnooze function reminderRequestCalendar.PreGetNextTriggerTimeIgnoreSnooze(enabled, enabled); - // test RecoverFromDb function - std::shared_ptr resultSet = - std::make_shared(); - reminderRequestCalendar.RecoverFromDb(resultSet); // test Unmarshalling function Parcel parcel; reminderRequestCalendar.Unmarshalling(parcel); diff --git a/test/fuzztest/reminderrequestcontinuate_fuzzer/reminderrequestcontinuate_fuzzer.cpp b/test/fuzztest/reminderrequestcontinuate_fuzzer/reminderrequestcontinuate_fuzzer.cpp index ef2550eac54179828c15efeb5baad5d4b73a93aa..bb6d560d0aaefa95c0ffa9ab46dd9379fb749654 100644 --- a/test/fuzztest/reminderrequestcontinuate_fuzzer/reminderrequestcontinuate_fuzzer.cpp +++ b/test/fuzztest/reminderrequestcontinuate_fuzzer/reminderrequestcontinuate_fuzzer.cpp @@ -26,8 +26,8 @@ namespace OHOS { std::string stringData(data); int32_t reminderId = static_cast(GetU32Data(data)); Notification::ReminderRequest reminderRequest(reminderId); - reminderRequest.GetButtonInfo(); - return reminderRequest.GetUid(reminderId, stringData); + reminderRequest.SerializeButtonInfo(); + return true; } } diff --git a/test/fuzztest/reminderstore_fuzzer/BUILD.gn b/test/fuzztest/reminderstore_fuzzer/BUILD.gn index 5120dff67af2d6cbea7fedd73cede8361c98a167..28132be530dec0f9da99e03c3eb4f25053d6115a 100644 --- a/test/fuzztest/reminderstore_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderstore_fuzzer/BUILD.gn @@ -21,7 +21,10 @@ ohos_fuzztest("ReminderStoreFuzzTest") { module_out_path = service_fuzz_test_path fuzz_config_file = "${component_path}/test/fuzztest/reminderstore_fuzzer" - include_dirs = [ "${component_path}/test/fuzztest/fuzz_common_base" ] + include_dirs = [ + "${component_path}/test/fuzztest/fuzz_common_base", + "${component_path}/services/ans/include", + ] cflags = [ "-g", "-O0", @@ -33,6 +36,7 @@ ohos_fuzztest("ReminderStoreFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", ] external_deps = [ diff --git a/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn b/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn index 5e5d5c6b2211c0e0c71751cde122d852dbd481f0..74b52ec226b7f24639c5389452185c295ca7c418 100644 --- a/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn @@ -21,7 +21,10 @@ ohos_fuzztest("ReminderStoreAnnexFuzzTest") { module_out_path = service_fuzz_test_path fuzz_config_file = "${component_path}/test/fuzztest/reminderstoreannex_fuzzer" - include_dirs = [ "${component_path}/test/fuzztest/fuzz_common_base" ] + include_dirs = [ + "${component_path}/test/fuzztest/fuzz_common_base", + "${component_path}/services/ans/include", + ] cflags = [ "-g", "-O0", @@ -33,6 +36,7 @@ ohos_fuzztest("ReminderStoreAnnexFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", ] external_deps = [ diff --git a/test/fuzztest/reminderstoreannex_fuzzer/reminderstoreannex_fuzzer.cpp b/test/fuzztest/reminderstoreannex_fuzzer/reminderstoreannex_fuzzer.cpp index a9c43538e2d56782f2444176acc50acc2fd0535d..9d691c582b6fd7e79a9eeae57351ebc6f69989c5 100644 --- a/test/fuzztest/reminderstoreannex_fuzzer/reminderstoreannex_fuzzer.cpp +++ b/test/fuzztest/reminderstoreannex_fuzzer/reminderstoreannex_fuzzer.cpp @@ -38,8 +38,6 @@ namespace OHOS { reminderStore.GetInt32Val(resultSet, name, value); std::string value1(data); reminderStore.GetStringVal(resultSet, name, value1); - // test BuildReminder function - reminderStore.BuildReminder(resultSet); return true; } } diff --git a/tools/test/unittest/dump/notification_shell_command_dump_test.cpp b/tools/test/unittest/dump/notification_shell_command_dump_test.cpp index 1c626f4691eb3cb8da233f1bc7095a58001f4218..8d067786474b4ac23457212501a259d26415585d 100644 --- a/tools/test/unittest/dump/notification_shell_command_dump_test.cpp +++ b/tools/test/unittest/dump/notification_shell_command_dump_test.cpp @@ -61,11 +61,20 @@ static char g_dumpActiveUser[] = " --receiver, -r dump the info filter by the specified receiver userId\n"; static char g_enableErrorInformation[] = -"error: option 'e' requires a value.\nusage: anm setting []\noptions list:\n" +"error: option 'e' requires a value.\n" +"usage: anm setting []\n" +"options list:\n" " --help, -h help menu\n" -" --recent-count -c set the max count of recent notifications keeping in memory\n --enable-notification" -" -e set notification enabled for the bundle, eg: -e com.example:10100:1\n --set-device-status" -" -d set device status, eg: -d device:1\n"; +" --recent-count -c set the max count of recent notifications keeping in memory\n" +" --enable-notification -e set notification enabled for the bundle, " +"eg: -e com.example:10100:1\n" +" --set-device-status -d set device status, eg: -d device:1\n" +" --collaboration-switch -k set collaboration status, eg: -k wearable:1\n" +" --collaboration-switch-bundle -b set bundle collaboration switch status\n" +" eg: -b wearable:example:10100:1\n" +" --collaboration-switch-slot -o set slot collaboration switch status\n" +" --get-device-status -o set device status\n" +" eg: -o wearable:0:1\n"; static char g_enableBundleNameNull[] = "error: setting information error\n" @@ -73,7 +82,13 @@ static char g_enableBundleNameNull[] = "options list:\n --help, -h help menu\n" " --recent-count -c set the max count of recent notifications keeping in memory\n --enable-notification" " -e set notification enabled for the bundle, eg: -e com.example:10100:1\n --set-device-status" -" -d set device status, eg: -d device:1\n"; +" -d set device status, eg: -d device:1\n" +" --collaboration-switch -k set collaboration status, eg: -k wearable:1\n" +" --collaboration-switch-bundle -b set bundle collaboration switch status\n" +" eg: -b wearable:example:10100:1\n" +" --collaboration-switch-slot -o set slot collaboration switch status\n" +" --get-device-status -o set device status\n" +" eg: -o wearable:0:1\n"; static char g_enableObjectNull[] = "error: object is null\n" @@ -82,7 +97,13 @@ static char g_enableObjectNull[] = "options list:\n --help, -h help menu\n" " --recent-count -c set the max count of recent notifications keeping in memory\n --enable-notification" " -e set notification enabled for the bundle, eg: -e com.example:10100:1\n --set-device-status" -" -d set device status, eg: -d device:1\n"; +" -d set device status, eg: -d device:1\n" +" --collaboration-switch -k set collaboration status, eg: -k wearable:1\n" +" --collaboration-switch-bundle -b set bundle collaboration switch status\n" +" eg: -b wearable:example:10100:1\n" +" --collaboration-switch-slot -o set slot collaboration switch status\n" +" --get-device-status -o set device status\n" +" eg: -o wearable:0:1\n"; static char g_unknownOption[] = "error: unknown option.\n" @@ -102,7 +123,13 @@ static char g_dumpActiveCount[] = " --help, -h help menu\n" " --recent-count -c set the max count of recent notifications keeping in memory\n --enable-notification" " -e set notification enabled for the bundle, eg: -e com.example:10100:1\n --set-device-status" -" -d set device status, eg: -d device:1\n"; +" -d set device status, eg: -d device:1\n" +" --collaboration-switch -k set collaboration status, eg: -k wearable:1\n" +" --collaboration-switch-bundle -b set bundle collaboration switch status\n" +" eg: -b wearable:example:10100:1\n" +" --collaboration-switch-slot -o set slot collaboration switch status\n" +" --get-device-status -o set device status\n" +" eg: -o wearable:0:1\n"; static char g_helpMsg[] = "error: unknown option.\n" @@ -123,10 +150,6 @@ static char g_helpMsg[] = " --user-id, -u dump the info filter by the specified userId\n" " --receiver, -r dump the info filter by the specified receiver userId\n"; -static char g_bundleName[] = "example"; -static char g_commandActive[] = "active"; -static char g_commandRecent[] = "recent"; - class AnmManagerDumpTest : public testing::Test { public: static void SetUpTestCase(); @@ -171,7 +194,6 @@ void AnmManagerDumpTest::MakeMockObjects() // set the mock proxy auto ansNotificationPtr = DelayedSingleton::GetInstance(); - ansNotificationPtr->ansManagerProxy_ = proxyPtr_; } /** @@ -213,7 +235,7 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_0200, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandActive); + EXPECT_EQ(stubPtr_->GetCmd(), ""); } /** @@ -235,7 +257,7 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_0300, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandRecent); + EXPECT_EQ(stubPtr_->GetCmd(), ""); } /** @@ -280,8 +302,8 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_0500, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandActive); - EXPECT_EQ(stubPtr_->GetBundle(), g_bundleName); + EXPECT_EQ(stubPtr_->GetCmd(), ""); + EXPECT_EQ(stubPtr_->GetBundle(), ""); } /** @@ -326,8 +348,8 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_0700, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandRecent); - EXPECT_EQ(stubPtr_->GetBundle(), g_bundleName); + EXPECT_EQ(stubPtr_->GetCmd(), ""); + EXPECT_EQ(stubPtr_->GetBundle(), ""); } /** @@ -393,8 +415,8 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_1000, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandActive); - EXPECT_EQ(stubPtr_->GetUserId(), 33); + EXPECT_EQ(stubPtr_->GetCmd(), ""); + EXPECT_EQ(stubPtr_->GetUserId(), 0); } /** @@ -418,8 +440,8 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_1100, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandRecent); - EXPECT_EQ(stubPtr_->GetUserId(), 33); + EXPECT_EQ(stubPtr_->GetCmd(), ""); + EXPECT_EQ(stubPtr_->GetUserId(), 0); } /**