diff --git a/frameworks/ans/core/common/include/ans_inner_errors.h b/frameworks/ans/core/common/include/ans_inner_errors.h index d8a4581b0ea10a88e188970d361257f88bdea9f4..44f0f61998592ca174d7ed7df513d5dda8e63910 100644 --- a/frameworks/ans/core/common/include/ans_inner_errors.h +++ b/frameworks/ans/core/common/include/ans_inner_errors.h @@ -73,6 +73,7 @@ enum ErrorCode : uint32_t { ERR_ANS_DISTRIBUTED_OPERATION_FAILED, ERR_ANS_DISTRIBUTED_GET_INFO_FAILED, ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED, + ERR_ANS_GET_ACTIVE_USER_FAILED, }; } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index f2e65ab62d9a0e683c734de3179fa10bc6f23279..91be045ebeaa445120440e1c8afa98f24b352cf1 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -126,6 +126,11 @@ public: virtual ErrCode GetValidReminders(std::vector> &reminders) = 0; virtual ErrCode CancelAllReminders() = 0; virtual ErrCode IsSupportTemplate(const std::string &templateName, bool &support) = 0; + virtual ErrCode IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed) = 0; + virtual ErrCode SetNotificationsEnabledByUser(const int32_t &deviceId, bool enabled) = 0; + virtual ErrCode DeleteAllByUser(const int32_t &userId) = 0; + virtual ErrCode SetDoNotDisturbDate(const int32_t &userId, const sptr &date) = 0; + virtual ErrCode GetDoNotDisturbDate(const int32_t &userId, sptr &date) = 0; protected: enum TransactId : uint32_t { @@ -195,7 +200,12 @@ protected: CANCEL_REMINDER, CANCEL_ALL_REMINDERS, GET_ALL_VALID_REMINDERS, - IS_SUPPORT_TEMPLATE + IS_SUPPORT_TEMPLATE, + IS_SPECIAL_USER_ALLOWED_NOTIFY, + SET_NOTIFICATION_ENABLED_BY_USER, + DELETE_ALL_NOTIFICATIONS_BY_USER, + SET_DO_NOT_DISTURB_DATE_BY_USER, + GET_DO_NOT_DISTURB_DATE_BY_USER }; }; } // namespace Notification diff --git a/frameworks/ans/core/include/ans_manager_proxy.h b/frameworks/ans/core/include/ans_manager_proxy.h index feed3ff2a628c804a2b7f80f6467cc46f1f591fd..cb4afad06b50e2a23409e2d8619efb28db13c4cb 100644 --- a/frameworks/ans/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -114,6 +114,11 @@ public: ErrCode CancelReminder(const int32_t reminderId) override; ErrCode GetValidReminders(std::vector> &reminders) override; ErrCode CancelAllReminders() override; + ErrCode IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed) override; + ErrCode SetNotificationsEnabledByUser(const int32_t &userId, bool enabled) override; + ErrCode DeleteAllByUser(const int32_t &userId) override; + ErrCode SetDoNotDisturbDate(const int32_t &userId, const sptr &date) override; + ErrCode GetDoNotDisturbDate(const int32_t &userId, sptr &date) override; private: ErrCode InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/ans/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h index f65b42c3ccc14d819f4f181534be7efaa2c587ab..f667eccc50fc135add65e436585062300f10b994 100644 --- a/frameworks/ans/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -120,6 +120,11 @@ public: virtual ErrCode GetValidReminders(std::vector> &reminders) override; virtual ErrCode CancelAllReminders() override; virtual ErrCode IsSupportTemplate(const std::string &templateName, bool &support) override; + virtual ErrCode IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed) override; + virtual ErrCode SetNotificationsEnabledByUser(const int32_t &deviceId, bool enabled) override; + virtual ErrCode DeleteAllByUser(const int32_t &userId) override; + virtual ErrCode SetDoNotDisturbDate(const int32_t &userId, const sptr &date) override; + virtual ErrCode GetDoNotDisturbDate(const int32_t &userId, sptr &date) override; private: static const std::map> @@ -192,6 +197,11 @@ private: ErrCode HandleGetValidReminders(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelAllReminders(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSupportTemplate(MessageParcel &data, MessageParcel &reply); + ErrCode HandleIsSpecialUserAllowedNotifyByUser(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetNotificationsEnabledByUser(MessageParcel &data, MessageParcel &reply); + ErrCode HandleDeleteAllByUser(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetDoNotDisturbDateByUser(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetDoNotDisturbDateByUser(MessageParcel &data, MessageParcel &reply); template bool WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result); diff --git a/frameworks/ans/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h index a780fd5aa2cc3688493c71a0de01bdb2265272f0..cf214a569d5ae4a5a766f5a337fcc25fc441fcc1 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -736,6 +736,56 @@ public: */ ErrCode GetValidReminders(std::vector> &validReminders); + /** + * Checks whether this application has permission to publish notifications under the user. + * + * @param userId Indicates the userId of the application. + * @param allowed True if the application has permissions; returns false otherwise. + * @return Returns get allowed result. + */ + ErrCode IsAllowedNotify(const int32_t &userId, bool &allowed); + + /** + * Sets whether to allow all applications to publish notifications on a specified user. + * The caller must have system permissions to call this method. + * + * @param userId Indicates the ID of the user running the application. + * @param enabled Specifies whether to allow all applications to publish notifications. The value true + * indicates that notifications are allowed, and the value false indicates that notifications + * are not allowed. + * @return Returns set notifications enabled for all bundles result. + */ + ErrCode SetNotificationsEnabledForAllBundles(const int32_t &userId, bool enabled); + + /** + * Removes notifications under specified user. + * @note Your application must have platform signature to use this method. + * + * @param userId Indicates the ID of user whose notifications are to be removed. + * @return Returns remove notification result. + */ + ErrCode RemoveNotifications(const int32_t &userId); + + /** + * Sets the do not disturb time on a specified user. + * @note Your application must have system signature to call this method. + * + * @param userId Indicates the specific user. + * @param doNotDisturbDate Indicates the do not disturb time to set. + * @return Returns set do not disturb time result. + */ + ErrCode SetDoNotDisturbDate(const int32_t &userId, const NotificationDoNotDisturbDate &doNotDisturbDate); + + /** + * Obtains the do not disturb time on a specified user. + * @note Your application must have system signature to call this method. + * + * @param userId Indicates the specific user. + * @param doNotDisturbDate Indicates the do not disturb time to get. + * @return Returns set do not disturb time result. + */ + ErrCode GetDoNotDisturbDate(const int32_t &userId, NotificationDoNotDisturbDate &doNotDisturbDate); + private: /** * Get Ans Manager proxy. diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index ce1d52cebc82ce0e0c3c0decacac5488fecb0529..4d9396dde286f69fcf880995d7f27d681f3335cd 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -2388,5 +2388,178 @@ ErrCode AnsManagerProxy::IsSupportTemplate(const std::string &templateName, bool return result; } + +ErrCode AnsManagerProxy::IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[IsSpecialUserAllowedNotify] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGW("[IsSpecialUserAllowedNotify] fail: write userId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(IS_SPECIAL_USER_ALLOWED_NOTIFY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGW("[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_LOGW("[SetNotificationsEnabledByUser] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGW("[SetNotificationsEnabledByUser] fail: write userId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGW("[SetNotificationsEnabledByUser] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_NOTIFICATION_ENABLED_BY_USER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetNotificationsEnabledByUser] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetNotificationsEnabledByUser] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::DeleteAllByUser(const int32_t &userId) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[DeleteAllByUser] fail:, write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGW("[DeleteAllByUser] fail: write userId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(DELETE_ALL_NOTIFICATIONS_BY_USER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[DeleteAllByUser] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[DeleteAllByUser] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetDoNotDisturbDate(const int32_t &userId, const sptr &date) +{ + if (date == nullptr) { + ANS_LOGW("[SetDoNotDisturbDate] fail: date is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[SetDoNotDisturbDate] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGW("[SetDoNotDisturbDate] fail: write userId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(date)) { + ANS_LOGW("[SetDoNotDisturbDate] fail: write date failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_DO_NOT_DISTURB_DATE_BY_USER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetDoNotDisturbDate] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetDoNotDisturbDate] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetDoNotDisturbDate(const int32_t &userId, sptr &date) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetDoNotDisturbDate] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGW("[GetDoNotDisturbDate] fail: write userId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_DO_NOT_DISTURB_DATE_BY_USER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetDoNotDisturbDate] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetDoNotDisturbDate] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (result == ERR_OK) { + date = reply.ReadParcelable(); + if (date == nullptr) { + ANS_LOGW("[GetDoNotDisturbDate] fail: read date failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + return result; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 979f0b2edf15d253cdaa1d1c23ced0255a5bddb6..cfcd7031ade9fe840e933db9f66cd3134f60df7c 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -233,6 +233,21 @@ const std::map date = data.ReadParcelable(); + if (date == nullptr) { + ANS_LOGW("[HandleSetDoNotDisturbDateByUser] fail: read date failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = SetDoNotDisturbDate(userId, date); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleSetDoNotDisturbDateByUser] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetDoNotDisturbDateByUser(MessageParcel &data, MessageParcel &reply) +{ + int32_t userId = SUBSCRIBE_USER_INIT; + if (!data.ReadInt32(userId)) { + ANS_LOGW("[HandleGetDoNotDisturbDateByUser] fail: read userId failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + sptr date = nullptr; + ErrCode result = GetDoNotDisturbDate(userId, date); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetDoNotDisturbDateByUser] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (result == ERR_OK) { + if (!reply.WriteParcelable(date)) { + ANS_LOGW("[HandleGetDoNotDisturbDateByUser] fail: write date failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + return ERR_OK; +} + ErrCode AnsManagerStub::Publish(const std::string &label, const sptr ¬ification) { ANS_LOGW("AnsManagerStub::Publish called!"); @@ -1962,5 +2084,35 @@ ErrCode AnsManagerStub::IsSupportTemplate(const std::string &templateName, bool ANS_LOGW("AnsManagerStub::IsSupportTemplate called!"); return ERR_INVALID_OPERATION; } + +ErrCode AnsManagerStub::IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed) +{ + ANS_LOGW("AnsManagerStub::IsSpecialUserAllowedNotify called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::SetNotificationsEnabledByUser(const int32_t &deviceId, bool enabled) +{ + ANS_LOGW("AnsManagerStub::SetNotificationsEnabledByUser called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::DeleteAllByUser(const int32_t &userId) +{ + ANS_LOGW("AnsManagerStub::DeleteAllByUser called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::SetDoNotDisturbDate(const int32_t &userId, const sptr &date) +{ + ANS_LOGW("AnsManagerStub::SetDoNotDisturbDate called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::GetDoNotDisturbDate(const int32_t &userId, sptr &date) +{ + ANS_LOGW("AnsManagerStub::GetDoNotDisturbDate called!"); + return ERR_INVALID_OPERATION; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index 6c4873d6cccdb784b7cd4e1abfbd824f73152d2b..43b9fb64f82e9c933207b8fc45739b6b1d4b4d52 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -1224,5 +1224,100 @@ bool AnsNotification::IsNonDistributedNotificationType(const NotificationContent } return false; } + +ErrCode AnsNotification::IsAllowedNotify(const int32_t &userId, bool &allowed) +{ + if (userId <= SUBSCRIBE_USER_INIT) { + ANS_LOGE("Input userId is invalid."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->IsSpecialUserAllowedNotify(userId, allowed); +} + +ErrCode AnsNotification::SetNotificationsEnabledForAllBundles(const int32_t &userId, bool enabled) +{ + if (userId <= SUBSCRIBE_USER_INIT) { + ANS_LOGE("Input userId is invalid."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->SetNotificationsEnabledByUser(userId, enabled); +} + +ErrCode AnsNotification::RemoveNotifications(const int32_t &userId) +{ + if (userId <= SUBSCRIBE_USER_INIT) { + ANS_LOGE("Input userId is invalid."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->DeleteAllByUser(userId); +} + +ErrCode AnsNotification::SetDoNotDisturbDate(const int32_t &userId, + const NotificationDoNotDisturbDate &doNotDisturbDate) +{ + if (userId <= SUBSCRIBE_USER_INIT) { + ANS_LOGE("Input userId is invalid."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + auto dndDatePtr = new (std::nothrow) NotificationDoNotDisturbDate(doNotDisturbDate); + if (dndDatePtr == nullptr) { + ANS_LOGE("create DoNotDisturbDate failed."); + return ERR_ANS_NO_MEMORY; + } + + sptr dndDate(dndDatePtr); + return ansManagerProxy_->SetDoNotDisturbDate(dndDate); +} + +ErrCode AnsNotification::GetDoNotDisturbDate(const int32_t &userId, NotificationDoNotDisturbDate &doNotDisturbDate) +{ + if (userId <= SUBSCRIBE_USER_INIT) { + ANS_LOGE("Input userId is invalid."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr dndDate; + auto ret = ansManagerProxy_->GetDoNotDisturbDate(dndDate); + if (ret != ERR_OK) { + ANS_LOGE("Get DoNotDisturbDate failed."); + return ret; + } + + if (!dndDate) { + ANS_LOGE("Invalid DoNotDisturbDate."); + return ERR_ANS_NO_MEMORY; + } + + doNotDisturbDate = *dndDate; + return ret; +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp index 9452c6a5cc696a4ea2a245ae7670d2a3e145561e..6bc484f52e7f45eecfc6a81a9b6072abb4b75b48 100644 --- a/frameworks/ans/native/src/notification_helper.cpp +++ b/frameworks/ans/native/src/notification_helper.cpp @@ -366,5 +366,32 @@ ErrCode NotificationHelper::IsSupportTemplate(const std::string &templateName, b { return DelayedSingleton::GetInstance()->IsSupportTemplate(templateName, support); } + +ErrCode NotificationHelper::IsAllowedNotify(const int32_t &userId, bool &allowed) +{ + return DelayedSingleton::GetInstance()->IsAllowedNotify(userId, allowed); +} + +ErrCode NotificationHelper::SetNotificationsEnabledForAllBundles(const int32_t &userId, bool enabled) +{ + return DelayedSingleton::GetInstance()->SetNotificationsEnabledForAllBundles( + userId, enabled); +} + +ErrCode NotificationHelper::RemoveNotifications(const int32_t &userId) +{ + return DelayedSingleton::GetInstance()->RemoveNotifications(userId); +} + +ErrCode NotificationHelper::SetDoNotDisturbDate(const int32_t &userId, + const NotificationDoNotDisturbDate &doNotDisturbDate) +{ + return DelayedSingleton::GetInstance()->SetDoNotDisturbDate(userId, doNotDisturbDate); +} + +ErrCode NotificationHelper::GetDoNotDisturbDate(const int32_t &userId, NotificationDoNotDisturbDate &doNotDisturbDate) +{ + return DelayedSingleton::GetInstance()->GetDoNotDisturbDate(userId, doNotDisturbDate); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index 9807dace34bda86b9a1f1c13286baa33428126a2..9deace200172c602ba478e405b4260ccc37b8aa4 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -680,6 +680,8 @@ std::string NotificationRequest::Dump() ", userInputHistory = " + (!userInputHistory_.empty() ? userInputHistory_.at(0) : "empty") + ", distributedOptions = " + distributedOptions_.Dump() + ", notificationFlags = " + (notificationFlags_ ? "not null" : "null") + + ", creatorUserId = " + std::to_string(creatorUserId_) + + ", receiverUserId = " + std::to_string(receiverUserId_) + " }"; } @@ -711,6 +713,12 @@ bool NotificationRequest::ToJson(nlohmann::json &jsonObject) const jsonObject["isUnremovable"] = unremovable_; jsonObject["isFloatingIcon"] = floatingIcon_; + jsonObject["creatorBundleName"] = creatorBundleName_; + jsonObject["creatorUid"] = creatorUid_; + jsonObject["creatorPid"] = creatorPid_; + jsonObject["creatorUserId"] = creatorUserId_; + jsonObject["receiverUserId"] = receiverUserId_; + if (!ConvertObjectsToJson(jsonObject)) { ANS_LOGE("Cannot convert objects to JSON"); return false; @@ -840,6 +848,16 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const return false; } + if (!parcel.WriteInt32(static_cast(creatorUserId_))) { + ANS_LOGE("Failed to write creator userId"); + return false; + } + + if (!parcel.WriteInt32(static_cast(receiverUserId_))) { + ANS_LOGE("Failed to write creator userId"); + return false; + } + // write std::string if (!parcel.WriteString(settingsText_)) { ANS_LOGE("Failed to write settings text"); @@ -1174,6 +1192,8 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) creatorPid_ = static_cast(parcel.ReadInt32()); creatorUid_ = static_cast(parcel.ReadInt32()); + creatorUserId_ = parcel.ReadInt32(); + receiverUserId_ = parcel.ReadInt32(); if (!parcel.ReadString(settingsText_)) { ANS_LOGE("Failed to read settings text"); @@ -1398,6 +1418,16 @@ std::shared_ptr NotificationRequest::GetFlags() const return notificationFlags_; } +void NotificationRequest::SetReceiverUserId(int32_t userId) +{ + receiverUserId_ = userId; +} + +int32_t NotificationRequest::GetReceiverUserId() const +{ + return receiverUserId_; +} + void NotificationRequest::CopyBase(const NotificationRequest &other) { this->notificationId_ = other.notificationId_; @@ -1411,6 +1441,8 @@ void NotificationRequest::CopyBase(const NotificationRequest &other) this->creatorPid_ = other.creatorPid_; this->creatorUid_ = other.creatorUid_; + this->creatorUserId_ = other.creatorUserId_; + this->receiverUserId_ = other.receiverUserId_; this->slotType_ = other.slotType_; this->settingsText_ = other.settingsText_; @@ -1544,6 +1576,22 @@ void NotificationRequest::ConvertJsonToNum(NotificationRequest *target, const nl if (jsonObject.find("autoDeletedTime") != jsonEnd) { target->autoDeletedTime_ = jsonObject.at("autoDeletedTime").get(); } + + if (jsonObject.find("creatorUid") != jsonEnd) { + target->creatorUid_ = jsonObject.at("creatorUid").get(); + } + + if (jsonObject.find("creatorPid") != jsonEnd) { + target->creatorPid_ = jsonObject.at("creatorPid").get(); + } + + if (jsonObject.find("creatorUserId") != jsonEnd) { + target->creatorUserId_ = jsonObject.at("creatorUserId").get(); + } + + if (jsonObject.find("receiverUserId") != jsonEnd) { + target->receiverUserId_ = jsonObject.at("receiverUserId").get(); + } } void NotificationRequest::ConvertJsonToString(NotificationRequest *target, const nlohmann::json &jsonObject) @@ -1574,6 +1622,10 @@ void NotificationRequest::ConvertJsonToString(NotificationRequest *target, const if (jsonObject.find("classification") != jsonEnd) { target->classification_ = jsonObject.at("classification").get(); } + + if (jsonObject.find("creatorBundleName") != jsonEnd) { + target->creatorBundleName_ = jsonObject.at("creatorBundleName").get(); + } } void NotificationRequest::ConvertJsonToEnum(NotificationRequest *target, const nlohmann::json &jsonObject) diff --git a/interfaces/innerkits/ans/native/include/notification_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index 665303846d6eb5e4a736ad246ef776d3b12c1eb1..3c12ad24cbf41a98f92a8fe8abe54571bec3cba8 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -696,6 +696,56 @@ public: * @return Returns check result. */ static ErrCode IsSupportTemplate(const std::string &templateName, bool &support); + + /** + * Checks whether this application has permission to publish notifications under the user. + * + * @param userId Indicates the userId of the application. + * @param allowed True if the application has permissions; returns false otherwise. + * @return Returns get allowed result. + */ + static ErrCode IsAllowedNotify(const int32_t &userId, bool &allowed); + + /** + * Sets whether to allow all applications to publish notifications on a specified user. + * The caller must have system permissions to call this method. + * + * @param userId Indicates the ID of the user running the application. + * @param enabled Specifies whether to allow all applications to publish notifications. The value true + * indicates that notifications are allowed, and the value false indicates that notifications + * are not allowed. + * @return Returns set notifications enabled for all bundles result. + */ + static ErrCode SetNotificationsEnabledForAllBundles(const int32_t &userId, bool enabled); + + /** + * Removes notifications under specified user. + * @note Your application must have platform signature to use this method. + * + * @param userId Indicates the ID of user whose notifications are to be removed. + * @return Returns remove notification result. + */ + static ErrCode RemoveNotifications(const int32_t &userId); + + /** + * Sets the do not disturb time on a specified user. + * @note Your application must have system signature to call this method. + * + * @param userId Indicates the specific user. + * @param doNotDisturbDate Indicates the do not disturb time to set. + * @return Returns set do not disturb time result. + */ + static ErrCode SetDoNotDisturbDate(const int32_t &userId, const NotificationDoNotDisturbDate &doNotDisturbDate); + + /** + * Obtains the do not disturb time on a specified user. + * @note Your application must have system signature to call this method. + * + * @param userId Indicates the specific user. + * @param doNotDisturbDate Indicates the do not disturb time to get. + * @return Returns set do not disturb time result. + */ + static ErrCode GetDoNotDisturbDate(const int32_t &userId, NotificationDoNotDisturbDate &doNotDisturbDate); }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index 1e54918ea9c4ea66a9f224fb9afbd1e44e8c92c0..117d918cbc360fc69134326f7b4be9aa94558b6f 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -16,6 +16,7 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_REQUEST_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_REQUEST_H +#include "ans_const_define.h" #include "message_user.h" #include "notification_action_button.h" #include "notification_content.h" @@ -928,6 +929,18 @@ public: */ std::shared_ptr GetFlags() const; + /** + * Sets the UserId of the notification receiver. + * @param userId the UserId of the notification receiver. + */ + void SetReceiverUserId(int32_t userId); + + /** + * Obtains the UserId of the notification receiver. + * @return the UserId of the notification receiver. + */ + int32_t GetReceiverUserId() const; + private: /** * Indicates the color mask, used for calculation with the ARGB value set by setColor(int32_t). @@ -985,7 +998,8 @@ private: pid_t creatorPid_ {0}; pid_t creatorUid_ {0}; - int32_t creatorUserId_ {-1}; + int32_t creatorUserId_ {SUBSCRIBE_USER_INIT}; + int32_t receiverUserId_ {SUBSCRIBE_USER_INIT}; std::string settingsText_ {}; std::string creatorBundleName_ {}; diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 20c1f7701cb0ef413301409b66a63f3feabee6b6..d9c7607c39d96330b64a050ab6d75ad84812bfbe 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -251,6 +251,10 @@ napi_value Common::SetNotification( napi_create_int32(env, notification->GetPid(), &value); napi_set_named_property(env, result, "creatorPid", value); + // readonly creatorUserId?: number + napi_create_int32(env, notification->GetUserId(), &value); + napi_set_named_property(env, result, "creatorUserId", value); + // distributedOption?:DistributedOptions napi_value distributedResult = nullptr; napi_create_object(env, &distributedResult); diff --git a/interfaces/kits/napi/ans/src/disturb_mode.cpp b/interfaces/kits/napi/ans/src/disturb_mode.cpp index 8ad364e5de996e8331b39b76c9a7f59745bd8a83..0bf8a47fb891dbf44868103c485cba7a3c79eafb 100644 --- a/interfaces/kits/napi/ans/src/disturb_mode.cpp +++ b/interfaces/kits/napi/ans/src/disturb_mode.cpp @@ -17,11 +17,20 @@ namespace OHOS { namespace NotificationNapi { -const int SET_DISTURB_MAX_PARA = 2; +const int SET_DISTURB_MAX_PARA = 3; const int SET_DISTURB_MIN_PARA = 1; +const int GET_DISTURB_MAX_PARA = 2; struct SetDoNotDisturbDateParams { NotificationDoNotDisturbDate date; + bool hasUserId = false; + int32_t userId = SUBSCRIBE_USER_INIT; + napi_ref callback = nullptr; +}; + +struct GetDoNotDisturbDateParams { + bool hasUserId = false; + int32_t userId = SUBSCRIBE_USER_INIT; napi_ref callback = nullptr; }; @@ -35,7 +44,7 @@ struct AsyncCallbackInfoSetDoNotDisturb { struct AsyncCallbackInfoGetDoNotDisturb { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback = nullptr; + GetDoNotDisturbDateParams params; NotificationDoNotDisturbDate date; CallbackPromiseInfo info; }; @@ -56,10 +65,16 @@ napi_value GetDoNotDisturbDate(const napi_env &env, const napi_value &argv, SetD napi_valuetype valuetype = napi_undefined; // argv[0]: date:type NAPI_CALL(env, napi_has_named_property(env, argv, "type", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "Property type expected."); + if (!hasProperty) { + ANS_LOGW("Wrong argument type. Property type expected."); + return nullptr; + } napi_get_named_property(env, argv, "type", &value); NAPI_CALL(env, napi_typeof(env, value, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + if (valuetype != napi_number) { + ANS_LOGW("Wrong argument type. Number expected."); + return nullptr; + } int type = 0; NotificationConstant::DoNotDisturbType outType = NotificationConstant::DoNotDisturbType::NONE; napi_get_value_int32(env, value, &type); @@ -71,7 +86,10 @@ napi_value GetDoNotDisturbDate(const napi_env &env, const napi_value &argv, SetD // argv[0]: date:begin NAPI_CALL(env, napi_has_named_property(env, argv, "begin", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "Property type expected."); + if (!hasProperty) { + ANS_LOGW("Wrong argument type. Property type expected."); + return nullptr; + } double begin = 0; napi_get_named_property(env, argv, "begin", &value); bool isDate = false; @@ -85,7 +103,10 @@ napi_value GetDoNotDisturbDate(const napi_env &env, const napi_value &argv, SetD // argv[0]: date:end NAPI_CALL(env, napi_has_named_property(env, argv, "end", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "Property type expected."); + if (!hasProperty) { + ANS_LOGW("Wrong argument type. Property type expected."); + return nullptr; + } double end = 0; napi_get_named_property(env, argv, "end", &value); isDate = false; @@ -108,21 +129,46 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[SET_DISTURB_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= SET_DISTURB_MIN_PARA, "Wrong number of arguments"); + if (argc < SET_DISTURB_MIN_PARA) { + ANS_LOGW("Wrong argument type. Property type expected."); + return nullptr; + } // argv[0]: date napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + if (valuetype != napi_object) { + ANS_LOGW("Wrong argument type. Property type expected."); + return nullptr; + } if (GetDoNotDisturbDate(env, argv[PARAM0], params) == nullptr) { return nullptr; } - // argv[1]:callback - if (argc >= SET_DISTURB_MAX_PARA) { + // argv[1] : userId / callback + if (argc >= SET_DISTURB_MAX_PARA - 1) { NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); + if ((valuetype != napi_number) && (valuetype != napi_function)) { + ANS_LOGW("Wrong argument type. Function or object expected."); + return nullptr; + } + + if (valuetype == napi_number) { + params.hasUserId = true; + NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM1], ¶ms.userId)); + } else { + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); + } + } + + // argv[2]:callback + if (argc >= SET_DISTURB_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } + napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -149,14 +195,20 @@ napi_value SetDoNotDisturbDate(napi_env env, napi_callback_info info) napi_create_string_latin1(env, "setDoNotDisturbDate", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, - nullptr, - resourceName, - [](napi_env env, void *data) { + nullptr, resourceName, [](napi_env env, void *data) { ANS_LOGI("SetDoNotDisturbDate napi_create_async_work start"); AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoSetDoNotDisturb *)data; - asynccallbackinfo->info.errorCode = NotificationHelper::SetDoNotDisturbDate(asynccallbackinfo->params.date); - ANS_LOGI("SetDoNotDisturbDate date=%{public}s errorCode=%{public}d", - asynccallbackinfo->params.date.Dump().c_str(), asynccallbackinfo->info.errorCode); + if (asynccallbackinfo->params.hasUserId) { + asynccallbackinfo->info.errorCode = NotificationHelper::SetDoNotDisturbDate( + asynccallbackinfo->params.userId, asynccallbackinfo->params.date); + } else { + asynccallbackinfo->info.errorCode = NotificationHelper::SetDoNotDisturbDate( + asynccallbackinfo->params.date); + } + + ANS_LOGI("SetDoNotDisturbDate date=%{public}s errorCode=%{public}d, hasUserId=%{public}d", + asynccallbackinfo->params.date.Dump().c_str(), asynccallbackinfo->info.errorCode, + asynccallbackinfo->params.hasUserId); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("SetDoNotDisturbDate napi_create_async_work end"); @@ -174,8 +226,7 @@ napi_value SetDoNotDisturbDate(napi_env env, napi_callback_info info) asynccallbackinfo = nullptr; } }, - (void *)asynccallbackinfo, - &asynccallbackinfo->asyncWork); + (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); @@ -215,22 +266,60 @@ void AsyncCompleteCallbackGetDoNotDisturbDate(napi_env env, napi_status status, } } +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetDoNotDisturbDateParams ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = GET_DISTURB_MAX_PARA; + napi_value argv[GET_DISTURB_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + napi_valuetype valuetype = napi_undefined; + // argv[0]: userId / callback + if (argc >= GET_DISTURB_MAX_PARA - 1) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if ((valuetype != napi_number) && (valuetype != napi_function)) { + ANS_LOGW("Wrong argument type. Function or object expected."); + return nullptr; + } + if (valuetype == napi_number) { + params.hasUserId = true; + NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM0], ¶ms.userId)); + } else { + napi_create_reference(env, argv[PARAM0], 1, ¶ms.callback); + } + } + + // argv[1]:callback + if (argc >= GET_DISTURB_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); + } + + return Common::NapiGetNull(env); +} + napi_value GetDoNotDisturbDate(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); - napi_ref callback = nullptr; - if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { + SetDoNotDisturbDateParams params {}; + if (ParseParameters(env, info, params) == nullptr) { return Common::NapiGetUndefined(env); } - AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoGetDoNotDisturb {.env = env, .asyncWork = nullptr, .callback = callback}; + AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoSetDoNotDisturb {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { - return Common::JSParaError(env, callback); + return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; - Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); napi_value resourceName = nullptr; napi_create_string_latin1(env, "getDoNotDisturbDate", NAPI_AUTO_LENGTH, &resourceName); @@ -241,9 +330,16 @@ napi_value GetDoNotDisturbDate(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("GetDoNotDisturbDate napi_create_async_work start"); AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoGetDoNotDisturb *)data; - asynccallbackinfo->info.errorCode = NotificationHelper::GetDoNotDisturbDate(asynccallbackinfo->date); - ANS_LOGI("GetDoNotDisturbDate errorCode=%{public}d date=%{public}s", - asynccallbackinfo->info.errorCode, asynccallbackinfo->date.Dump().c_str()); + if (asynccallbackinfo->params.hasUserId) { + asynccallbackinfo->info.errorCode = NotificationHelper::GetDoNotDisturbDate( + asynccallbackinfo->params.userId, asynccallbackinfo->date); + } else { + asynccallbackinfo->info.errorCode = NotificationHelper::GetDoNotDisturbDate(asynccallbackinfo->date); + } + + ANS_LOGI("GetDoNotDisturbDate errorCode=%{public}d date=%{public}s, hasUserId=%{public}d", + asynccallbackinfo->info.errorCode, asynccallbackinfo->date.Dump().c_str(), + asynccallbackinfo->params.hasUserId); }, AsyncCompleteCallbackGetDoNotDisturbDate, (void *)asynccallbackinfo, diff --git a/interfaces/kits/napi/ans/src/enable_notification.cpp b/interfaces/kits/napi/ans/src/enable_notification.cpp index c9b896d17d66f963641ff3bc41cc5b15e799f64d..e2802f748695fa2c2ce7189d4b707f45e8bc33db 100644 --- a/interfaces/kits/napi/ans/src/enable_notification.cpp +++ b/interfaces/kits/napi/ans/src/enable_notification.cpp @@ -38,6 +38,8 @@ struct IsEnableParams { NotificationBundleOption option; napi_ref callback = nullptr; bool hasBundleOption = false; + int32_t userId = SUBSCRIBE_USER_INIT; + bool hasUserId = false; }; struct AsyncCallbackInfoIsEnable { @@ -108,10 +110,10 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, return Common::NapiGetNull(env); } - // argv[0]: bundle / callback + // argv[0]: bundle / userId / callback napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - if ((valuetype != napi_function) && (valuetype != napi_object)) { + if ((valuetype != napi_object) && (valuetype != napi_number) && (valuetype != napi_function)) { ANS_LOGW("Wrong argument type. Function or object expected."); return nullptr; } @@ -122,6 +124,9 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, return nullptr; } params.hasBundleOption = true; + } else if (valuetype == napi_number) { + NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM0], ¶ms.userId)); + params.hasUserId = true; } else { napi_create_reference(env, argv[PARAM0], 1, ¶ms.callback); } @@ -262,6 +267,10 @@ napi_value IsNotificationEnabled(napi_env env, napi_callback_info info) asynccallbackinfo->params.option.GetUid()); asynccallbackinfo->info.errorCode = NotificationHelper::IsAllowedNotify(asynccallbackinfo->params.option, asynccallbackinfo->allowed); + } else if (asynccallbackinfo->params.hasUserId) { + ANS_LOGI("userId = %{public}d", asynccallbackinfo->params.userId); + asynccallbackinfo->info.errorCode = + NotificationHelper::IsAllowedNotify(asynccallbackinfo->params.userId, asynccallbackinfo->allowed); } else { asynccallbackinfo->info.errorCode = NotificationHelper::IsAllowedNotify(asynccallbackinfo->allowed); } diff --git a/interfaces/kits/napi/ans/src/publish.cpp b/interfaces/kits/napi/ans/src/publish.cpp index b544ea7d834390545e1fa79c3f81b5cffdc6c3b6..d099d521182fda0803d55364cf299806049307c1 100644 --- a/interfaces/kits/napi/ans/src/publish.cpp +++ b/interfaces/kits/napi/ans/src/publish.cpp @@ -17,7 +17,7 @@ namespace OHOS { namespace NotificationNapi { -static const int32_t PUBLISH_NOTIFICATION_MAX = 2; +static const int32_t PUBLISH_NOTIFICATION_MAX = 3; struct AsyncCallbackInfoPublish { napi_env env = nullptr; @@ -37,7 +37,10 @@ napi_value GetCallback(const napi_env &env, const napi_value &value, ParametersI napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, value, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, value, 1, ¶ms.callback); ANS_LOGI("end"); return Common::NapiGetNull(env); @@ -50,20 +53,43 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, size_t argc = PUBLISH_NOTIFICATION_MAX; napi_value argv[PUBLISH_NOTIFICATION_MAX] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + if (argc < 1) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + if (valuetype != napi_object) { + ANS_LOGW("Wrong argument type. Object expected."); + return nullptr; + } // argv[0] : NotificationRequest if (Common::GetNotificationRequest(env, argv[PARAM0], params.request) == nullptr) { return nullptr; } - // argv[1] : callback + // argv[1] : userId / callback + if (argc >= PUBLISH_NOTIFICATION_MAX - 1) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if ((valuetype != napi_number) && (valuetype != napi_function)) { + ANS_LOGW("Wrong argument type. Function or object expected."); + return nullptr; + } + + 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); + } else { + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); + } + } + + // argv[2] : callback if (argc >= PUBLISH_NOTIFICATION_MAX) { - if (GetCallback(env, argv[PARAM1], params) == nullptr) { + if (GetCallback(env, argv[PARAM2], params) == nullptr) { return nullptr; } } diff --git a/interfaces/kits/napi/ans/src/remove.cpp b/interfaces/kits/napi/ans/src/remove.cpp index 0757bbea307e3fd2cc35436d90ec5e5db6d36214..8d44d3219ce8d30c9f4e6eb07579c6ebfc570fbf 100644 --- a/interfaces/kits/napi/ans/src/remove.cpp +++ b/interfaces/kits/napi/ans/src/remove.cpp @@ -22,7 +22,6 @@ const int REMOVE_MIN_PARA = 1; const int REMOVE_OR_BUNDLE_MAX_PARA = 2; const int REMOVE_ALL_MAX_PARA = 2; -const int REMOVE_ALL_WHEN_HAS_PARA_MIN_PARA = 1; const int REMOVE_BY_BUNDLE_AND_KEY_MIN_PARA = 2; const int REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA = 3; @@ -38,6 +37,8 @@ struct BundleAndKeyInfo { struct RemoveParams { std::optional hashcode {}; std::optional bundleAndKeyInfo {}; + int32_t userId = SUBSCRIBE_USER_INIT; + bool hasUserId = false; napi_ref callback = nullptr; }; @@ -69,13 +70,18 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= REMOVE_MIN_PARA, "Wrong number of arguments"); + if (argc < REMOVE_MIN_PARA) { + ANS_LOGW("Wrong number of arguments."); + return nullptr; + } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - NAPI_ASSERT(env, - (valuetype == napi_string) || (valuetype == napi_object), - "Wrong argument type. String or object expected."); + if ((valuetype != napi_string) && (valuetype != napi_object)) { + ANS_LOGW("Wrong argument type. String or object expected."); + return nullptr; + } + if (valuetype == napi_string) { // argv[0]: hashCode size_t strLen = 0; @@ -86,11 +92,17 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[1]:callback if (argc >= REMOVE_OR_BUNDLE_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } } else { - NAPI_ASSERT(env, argc >= REMOVE_BY_BUNDLE_AND_KEY_MIN_PARA, "Wrong number of arguments"); + if (argc < REMOVE_BY_BUNDLE_AND_KEY_MIN_PARA) { + ANS_LOGW("Wrong number of arguments."); + return nullptr; + } BundleAndKeyInfo info {}; // argv[0]: BundleOption @@ -112,7 +124,10 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[2]:callback if (argc >= REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } } @@ -129,31 +144,40 @@ napi_value ParseParametersByRemoveAll(const napi_env &env, const napi_callback_i napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc < REMOVE_ALL_WHEN_HAS_PARA_MIN_PARA) { + if (argc == 0) { return Common::NapiGetNull(env); } + // argv[0]: bundle / userId / callback napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - NAPI_ASSERT(env, - (valuetype == napi_function) || (valuetype == napi_object), - "Wrong argument type. Function or object expected."); - if (valuetype == napi_function) { - // argv[0]: callback - napi_create_reference(env, argv[PARAM0], 1, ¶ms.callback); - } else { + if ((valuetype != napi_object) && (valuetype != napi_number) && (valuetype != napi_function)) { + ANS_LOGW("Wrong argument type. Function or object expected."); + return nullptr; + } + if (valuetype == napi_object) { BundleAndKeyInfo info {}; - // argv[0]: BundleOption auto retValue = Common::GetBundleOption(env, argv[PARAM0], info.option); - NAPI_ASSERT(env, retValue != nullptr, "GetBundleOption failed."); + if (retValue == nullptr) { + ANS_LOGW("GetBundleOption failed."); + return nullptr; + } params.bundleAndKeyInfo = info; + } else if (valuetype == napi_number) { + NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM0], ¶ms.userId)); + params.hasUserId = true; + } else { + napi_create_reference(env, argv[PARAM0], 1, ¶ms.callback); + } - // argv[1]:callback - if (argc >= REMOVE_ALL_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); + // argv[1]:callback + if (argc >= REMOVE_ALL_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; } + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -169,11 +193,17 @@ napi_value ParseParameters( napi_value thisVar = nullptr; napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= REMOVE_GROUP_BY_BUNDLE_MIN_PARA, "Wrong number of arguments"); + if (argc < REMOVE_GROUP_BY_BUNDLE_MIN_PARA) { + ANS_LOGW("Wrong number of arguments."); + return nullptr; + } // argv[0]: bundle NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + if (valuetype != napi_object) { + ANS_LOGW("Wrong argument type. Object expected."); + return nullptr; + } auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); if (retValue == nullptr) { ANS_LOGE("GetBundleOption failed."); @@ -182,7 +212,10 @@ napi_value ParseParameters( // argv[1]: groupName: string NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + if (valuetype != napi_string) { + ANS_LOGW("Wrong argument type. String expected."); + return nullptr; + } char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; NAPI_CALL(env, napi_get_value_string_utf8(env, argv[PARAM1], str, STR_MAX_SIZE - 1, &strLen)); @@ -191,7 +224,10 @@ napi_value ParseParameters( // argv[2]:callback if (argc >= REMOVE_GROUP_BY_BUNDLE_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } @@ -294,6 +330,9 @@ napi_value RemoveAll(napi_env env, napi_callback_info info) auto &infos = asynccallbackinfo->params.bundleAndKeyInfo.value(); asynccallbackinfo->info.errorCode = NotificationHelper::RemoveAllNotifications(infos.option); + } else if (asynccallbackinfo->params.hasUserId) { + asynccallbackinfo->info.errorCode = NotificationHelper::RemoveNotifications( + asynccallbackinfo->params.userId); } else { asynccallbackinfo->info.errorCode = NotificationHelper::RemoveNotifications(); } diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 95cc804a56656635c4b01a2bced396738b6da201..c120960828c81035ab5e76e101f65001cfbec4fd 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -121,6 +121,11 @@ public: ErrCode GetValidReminders(std::vector> &reminders) override; ErrCode CancelAllReminders() override; ErrCode IsSupportTemplate(const std::string &templateName, bool &support) override; + ErrCode IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed) override; + ErrCode SetNotificationsEnabledByUser(const int32_t &deviceId, bool enabled) override; + ErrCode DeleteAllByUser(const int32_t &userId) override; + ErrCode SetDoNotDisturbDate(const int32_t &userId, const sptr &date) override; + ErrCode GetDoNotDisturbDate(const int32_t &userId, sptr &date) override; // SystemEvent void OnBundleRemoved(const sptr &bundleOption); @@ -152,7 +157,8 @@ private: ErrCode RemoveFromNotificationList(const sptr &bundleOption, const std::string &label, int notificationId, sptr ¬ification, bool isCancel = false); ErrCode RemoveFromNotificationList(const std::string &key, sptr ¬ification, bool isCancel = false); - ErrCode RemoveFromNotificationListForDeleteAll(const std::string &key, sptr ¬ification); + ErrCode RemoveFromNotificationListForDeleteAll(const std::string &key, + const int &userId, sptr ¬ification); std::vector GetNotificationKeys(const sptr &bundleOption); bool IsNotificationExists(const std::string &key); void SortNotificationList(); @@ -197,6 +203,9 @@ private: ErrCode GetDistributedEnableInApplicationInfo(const sptr bundleOption, bool &enable); #endif + ErrCode SetDoNotDisturbDateByUser(const int32_t &userId, const sptr &date); + ErrCode GetDoNotDisturbDateByUser(const int32_t &userId, sptr &date); + private: static sptr instance_; static std::mutex instanceMutex_; diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 04ef9233cd0113c01f06ab8a044454624be52cc2..516432ad89f57bbbf224106df2d1995e076feceb 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -64,12 +64,10 @@ public: ErrCode SetPrivateNotificationsAllowed(const sptr &bundleOption, const bool allow); ErrCode GetNotificationsEnabledForBundle(const sptr &bundleOption, bool &enabled); ErrCode SetNotificationsEnabledForBundle(const sptr &bundleOption, const bool enabled); - ErrCode GetNotificationsEnabled(const sptr &bundleOption, bool &enabled); - ErrCode SetNotificationsEnabled(const sptr &bundleOption, const bool &enabled); - ErrCode GetDoNotDisturbDate(const sptr &bundleOption, - sptr &date); - ErrCode SetDoNotDisturbDate(const sptr &bundleOption, - const sptr date); + ErrCode GetNotificationsEnabled(const int32_t &userId, bool &enabled); + ErrCode SetNotificationsEnabled(const int32_t &userId, const bool &enabled); + ErrCode GetDoNotDisturbDate(const int32_t &userId, sptr &date); + ErrCode SetDoNotDisturbDate(const int32_t &userId, const sptr date); ErrCode GetTemplateSupported(const std::string& templateName, bool &support); ErrCode ClearNotificationInRestoreFactorySettings(); diff --git a/services/ans/include/notification_subscriber_manager.h b/services/ans/include/notification_subscriber_manager.h index f6e2ae64531e82389a465593f32ad15f8b599679..062a6b3ba63c851cacab45b1adc8185884a4b0da 100644 --- a/services/ans/include/notification_subscriber_manager.h +++ b/services/ans/include/notification_subscriber_manager.h @@ -70,6 +70,7 @@ private: const sptr ¬ification, const sptr ¬ificationMap, int deleteReason); void NotifyUpdatedInner(const sptr ¬ificationMap); void NotifyDoNotDisturbDateChangedInner(const sptr &date); + bool IsSystemUser(int32_t userId); private: std::list> subscriberRecordList_ {}; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 494a045a00f3617d0eaf48d1408bab7f3b269cbd..23a9dfef737913ab0c5cff9f425d96f5981afbb0 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -200,9 +200,6 @@ ErrCode PrepereNotificationRequest(const sptr &request) int userId = SUBSCRIBE_USER_INIT; OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); - if (userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && userId <= SUBSCRIBE_USER_SYSTEM_END) { - userId = SUBSCRIBE_USER_ALL; - } request->SetCreatorUserId(userId); ErrCode result = CheckPictureSize(request); @@ -933,12 +930,12 @@ ErrCode AdvancedNotificationService::DeleteAll() #endif sptr notification = nullptr; - result = RemoveFromNotificationListForDeleteAll(key, notification); + result = RemoveFromNotificationListForDeleteAll(key, activeUserId, notification); if (result != ERR_OK || notification == nullptr) { continue; } - if ((notification->GetUserId() == activeUserId) || (notification->GetUserId() == SUBSCRIBE_USER_ALL)) { + if (notification->GetUserId() == activeUserId) { int reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); @@ -1184,10 +1181,10 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( } ErrCode AdvancedNotificationService::RemoveFromNotificationListForDeleteAll( - const std::string &key, sptr ¬ification) + const std::string &key, const int &userId, sptr ¬ification) { for (auto record : notificationList_) { - if (record->notification->GetKey() == key) { + if ((record->notification->GetKey() == key) && (record->notification->GetUserId() == userId)) { if (!record->notification->IsRemoveAllowed()) { return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; } @@ -1297,7 +1294,9 @@ ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vectorPostSyncTask(std::bind([&]() { @@ -1363,16 +1362,16 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const return ERR_ANS_PERMISSION_DENIED; } - ErrCode result = ERR_OK; - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; + int userId = SUBSCRIBE_USER_INIT; + if (!GetActiveUserId(userId)) { + return ERR_ANS_GET_ACTIVE_USER_FAILED; } + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { if (deviceId.empty()) { // Local device - result = NotificationPreferences::GetInstance().SetNotificationsEnabled(bundleOption, enabled); + result = NotificationPreferences::GetInstance().SetNotificationsEnabled(userId, enabled); } else { // Remote device } @@ -1422,15 +1421,15 @@ ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed) return ERR_ANS_PERMISSION_DENIED; } - ErrCode result = ERR_OK; - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; + int userId = SUBSCRIBE_USER_INIT; + if (!GetActiveUserId(userId)) { + return ERR_ANS_GET_ACTIVE_USER_FAILED; } + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { allowed = false; - result = NotificationPreferences::GetInstance().GetNotificationsEnabled(bundleOption, allowed); + result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed); })); return result; } @@ -1467,10 +1466,15 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( return ERR_ANS_INVALID_BUNDLE; } + int userId = SUBSCRIBE_USER_INIT; + if (!GetActiveUserId(userId)) { + return ERR_ANS_GET_ACTIVE_USER_FAILED; + } + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { allowed = false; - result = NotificationPreferences::GetInstance().GetNotificationsEnabled(bundleOption, allowed); + result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed); if (result == ERR_OK && allowed) { result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(targetBundle, allowed); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { @@ -2274,51 +2278,12 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptrGetBeginDate()); - int64_t endDate = ResetSeconds(date->GetEndDate()); - - switch (date->GetDoNotDisturbType()) { - case NotificationConstant::DoNotDisturbType::NONE: - beginDate = 0; - endDate = 0; - break; - case NotificationConstant::DoNotDisturbType::ONCE: - AdjustDateForDndTypeOnce(beginDate, endDate); - break; - case NotificationConstant::DoNotDisturbType::CLEARLY: - if (beginDate >= endDate) { - return ERR_ANS_INVALID_PARAM; - } - break; - default: - break; - } - - const sptr newConfig = new NotificationDoNotDisturbDate( - date->GetDoNotDisturbType(), - beginDate, - endDate - ); - - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; + int userId = SUBSCRIBE_USER_INIT; + if (!GetActiveUserId(userId)) { + return ERR_ANS_GET_ACTIVE_USER_FAILED; } - handler_->PostSyncTask(std::bind([&]() { - result = NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption, newConfig); - if (result == ERR_OK) { - NotificationSubscriberManager::GetInstance()->NotifyDoNotDisturbDateChanged(newConfig); - } - })); - - return ERR_OK; + return SetDoNotDisturbDateByUser(userId, date); } ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr &date) @@ -2333,35 +2298,12 @@ ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; + int userId = SUBSCRIBE_USER_INIT; + if (!GetActiveUserId(userId)) { + return ERR_ANS_GET_ACTIVE_USER_FAILED; } - handler_->PostSyncTask(std::bind([&]() { - sptr currentConfig = nullptr; - result = NotificationPreferences::GetInstance().GetDoNotDisturbDate(bundleOption, currentConfig); - if (result == ERR_OK) { - int64_t now = GetCurrentTime(); - switch (currentConfig->GetDoNotDisturbType()) { - case NotificationConstant::DoNotDisturbType::CLEARLY: - case NotificationConstant::DoNotDisturbType::ONCE: - if (now >= currentConfig->GetEndDate()) { - date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); - NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption, date); - } else { - date = currentConfig; - } - break; - default: - date = currentConfig; - break; - } - } - })); - - return ERR_OK; + return GetDoNotDisturbDateByUser(userId, date); } ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSupport) @@ -2902,5 +2844,210 @@ void AdvancedNotificationService::TriggerRemoveWantAgent(const sptr agent = request->GetRemovalWantAgent(); WantAgent::WantAgentHelper::TriggerWantAgent(agent, nullptr, triggerInfo); } + +ErrCode AdvancedNotificationService::IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + allowed = false; + result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed); + })); + return result; +} + +ErrCode AdvancedNotificationService::SetNotificationsEnabledByUser(const int32_t &userId, bool enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().SetNotificationsEnabled(userId, enabled); + })); + return result; +} + +ErrCode AdvancedNotificationService::DeleteAllByUser(const int32_t &userId) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (userId <= SUBSCRIBE_USER_INIT) { + ANS_LOGE("Input userId is invalid."); + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + std::vector keys = GetNotificationKeys(nullptr); + for (auto key : keys) { +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::string deviceId = GetNotificationDeviceId(key); +#endif + sptr notification = nullptr; + + result = RemoveFromNotificationListForDeleteAll(key, userId, notification); + if (result != ERR_OK || notification == nullptr) { + continue; + } + + if (notification->GetUserId() == userId) { + int reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, notification); +#endif + } + } + + result = ERR_OK; + })); + + return result; +} + +ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const int32_t &userId, + const sptr &date) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (userId <= SUBSCRIBE_USER_INIT) { + ANS_LOGE("Input userId is invalid."); + return ERR_ANS_INVALID_PARAM; + } + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + return SetDoNotDisturbDateByUser(userId, date); +} + +ErrCode AdvancedNotificationService::GetDoNotDisturbDate(const int32_t &userId, + sptr &date) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (userId <= SUBSCRIBE_USER_INIT) { + ANS_LOGE("Input userId is invalid."); + return ERR_ANS_INVALID_PARAM; + } + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + return GetDoNotDisturbDateByUser(userId, date); +} + +ErrCode AdvancedNotificationService::SetDoNotDisturbDateByUser(const int32_t &userId, + const sptr &date) +{ + if (date == nullptr) { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + + int64_t beginDate = ResetSeconds(date->GetBeginDate()); + int64_t endDate = ResetSeconds(date->GetEndDate()); + + switch (date->GetDoNotDisturbType()) { + case NotificationConstant::DoNotDisturbType::NONE: + beginDate = 0; + endDate = 0; + break; + case NotificationConstant::DoNotDisturbType::ONCE: + AdjustDateForDndTypeOnce(beginDate, endDate); + break; + case NotificationConstant::DoNotDisturbType::CLEARLY: + if (beginDate >= endDate) { + return ERR_ANS_INVALID_PARAM; + } + break; + default: + break; + } + + const sptr newConfig = new NotificationDoNotDisturbDate( + date->GetDoNotDisturbType(), + beginDate, + endDate + ); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().SetDoNotDisturbDate(userId, newConfig); + if (result == ERR_OK) { + NotificationSubscriberManager::GetInstance()->NotifyDoNotDisturbDateChanged(newConfig); + } + })); + + return ERR_OK; +} + +ErrCode AdvancedNotificationService::GetDoNotDisturbDateByUser(const int32_t &userId, + sptr &date) +{ + ErrCode result = ERR_OK; + + handler_->PostSyncTask(std::bind([&]() { + sptr currentConfig = nullptr; + result = NotificationPreferences::GetInstance().GetDoNotDisturbDate(userId, currentConfig); + if (result == ERR_OK) { + int64_t now = GetCurrentTime(); + switch (currentConfig->GetDoNotDisturbType()) { + case NotificationConstant::DoNotDisturbType::CLEARLY: + case NotificationConstant::DoNotDisturbType::ONCE: + if (now >= currentConfig->GetEndDate()) { + date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + NotificationPreferences::GetInstance().SetDoNotDisturbDate(userId, date); + } else { + date = currentConfig; + } + break; + default: + date = currentConfig; + break; + } + } + })); + + return ERR_OK; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 4dd6b400855747c82bd40459731103674ecf162c..209e0e1fa1c63cbd98b29530dc4bae9a3f0c4f60 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -508,16 +508,12 @@ bool NotificationPreferences::GetActiveUserId(int& userId) return false; } -ErrCode NotificationPreferences::GetNotificationsEnabled( - const sptr &bundleOption, bool &enabled) +ErrCode NotificationPreferences::GetNotificationsEnabled(const int32_t &userId, bool &enabled) { - if (bundleOption == nullptr) { + if (userId <= SUBSCRIBE_USER_INIT) { return ERR_ANS_INVALID_PARAM; } - int userId = SUBSCRIBE_USER_INIT; - (void)GetActiveUserId(userId); - ErrCode result = ERR_OK; if (!preferencesInfo_.GetEnabledAllNotification(userId, enabled)) { result = ERR_ANS_INVALID_PARAM; @@ -525,16 +521,12 @@ ErrCode NotificationPreferences::GetNotificationsEnabled( return result; } -ErrCode NotificationPreferences::SetNotificationsEnabled( - const sptr &bundleOption, const bool &enabled) +ErrCode NotificationPreferences::SetNotificationsEnabled(const int32_t &userId, const bool &enabled) { - if (bundleOption == nullptr) { + if (userId <= SUBSCRIBE_USER_INIT) { return ERR_ANS_INVALID_PARAM; } - int userId = SUBSCRIBE_USER_INIT; - (void)GetActiveUserId(userId); - NotificationPreferencesInfo preferencesInfo = preferencesInfo_; preferencesInfo.SetEnabledAllNotification(userId, enabled); ErrCode result = ERR_OK; @@ -548,16 +540,13 @@ ErrCode NotificationPreferences::SetNotificationsEnabled( return result; } -ErrCode NotificationPreferences::GetDoNotDisturbDate( - const sptr &bundleOption, sptr &date) +ErrCode NotificationPreferences::GetDoNotDisturbDate(const int32_t &userId, + sptr &date) { - if (bundleOption == nullptr) { + if (userId <= SUBSCRIBE_USER_INIT) { return ERR_ANS_INVALID_PARAM; } - int userId = SUBSCRIBE_USER_INIT; - (void)GetActiveUserId(userId); - ErrCode result = ERR_OK; NotificationPreferencesInfo preferencesInfo = preferencesInfo_; if (!preferencesInfo.GetDoNotDisturbDate(userId, date)) { @@ -566,16 +555,13 @@ ErrCode NotificationPreferences::GetDoNotDisturbDate( return result; } -ErrCode NotificationPreferences::SetDoNotDisturbDate( - const sptr &bundleOption, const sptr date) +ErrCode NotificationPreferences::SetDoNotDisturbDate(const int32_t &userId, + const sptr date) { - if (bundleOption == nullptr) { + if (userId <= SUBSCRIBE_USER_INIT) { return ERR_ANS_INVALID_PARAM; } - int userId = SUBSCRIBE_USER_INIT; - (void)GetActiveUserId(userId); - NotificationPreferencesInfo preferencesInfo = preferencesInfo_; preferencesInfo.SetDoNotDisturbDate(userId, date); diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 0307d32ce604159f7e44061d609f74c8c6c7afb1..68b11af00da9aba63758f3230bfb6df774dd44fe 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -64,7 +64,10 @@ ErrCode NotificationSubscriberManager::AddSubscriber( return ERR_ANS_NO_MEMORY; } - int userId = SUBSCRIBE_USER_ALL; + int userId = SUBSCRIBE_USER_INIT; + int callingUid = IPCSkeleton::GetCallingUid(); + OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); + ANS_LOGD("AddSubscriber callingUid = <%{public}d> userId = <%{public}d>", callingUid, userId); subInfo->AddAppUserId(userId); } @@ -284,12 +287,15 @@ void NotificationSubscriberManager::NotifyConsumedInner( ANS_LOGD("%{public}s notification->GetUserId <%{public}d>", __FUNCTION__, notification->GetUserId()); for (auto record : subscriberRecordList_) { ANS_LOGD("%{public}s record->userId = <%{public}d>", __FUNCTION__, record->userId); + + int32_t recvUserId = notification->GetNotificationRequest().GetReceiverUserId(); auto BundleNames = notification->GetBundleName(); auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); if (!record->subscribedAll == (iter != record->bundleList_.end()) && (notification->GetUserId() == record->userId || - notification->GetUserId() == SUBSCRIBE_USER_ALL || - record->userId == SUBSCRIBE_USER_ALL)) { + notification->GetUserId() == SUBSCRIBE_USER_ALL || + recvUserId == record->userId || + IsSystemUser(record->userId))) { record->subscriber->OnConsumed(notification, notificationMap); record->subscriber->OnConsumed(notification); } @@ -325,5 +331,14 @@ void NotificationSubscriberManager::NotifyDoNotDisturbDateChangedInner(const spt record->subscriber->OnDoNotDisturbDateChange(date); } } + +bool NotificationSubscriberManager::IsSystemUser(int32_t userId) +{ + if (userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && userId <= SUBSCRIBE_USER_SYSTEM_END) { + return true; + } + + return false; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/notification_preferences_test.cpp b/services/ans/test/unittest/notification_preferences_test.cpp index c909c9b04fae979823be2b5321d32466c6ede70a..fa283597a239345c1958a3fe7dcfee947ba9ad70 100644 --- a/services/ans/test/unittest/notification_preferences_test.cpp +++ b/services/ans/test/unittest/notification_preferences_test.cpp @@ -1017,7 +1017,7 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02900, Functio */ HWTEST_F(NotificationPreferencesTest, SetNotificationsEnabled_00100, Function | SmallTest | Level1) { - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(bundleOption_, true), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(100, true), (int)ERR_OK); } /** @@ -1027,9 +1027,9 @@ HWTEST_F(NotificationPreferencesTest, SetNotificationsEnabled_00100, Function | */ HWTEST_F(NotificationPreferencesTest, GetNotificationsEnabled_00100, Function | SmallTest | Level1) { - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(bundleOption_, true), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(100, true), (int)ERR_OK); bool enable = false; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(bundleOption_, enable), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(100, enable), (int)ERR_OK); EXPECT_TRUE(enable); } @@ -1049,7 +1049,7 @@ HWTEST_F(NotificationPreferencesTest, SetDoNotDisturbDate_00100, Function | Smal sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption_, date), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(SYSTEM_APP_UID, date), (int)ERR_OK); } /** @@ -1067,10 +1067,10 @@ HWTEST_F(NotificationPreferencesTest, GetDoNotDisturbDate_00100, Function | Smal int64_t endDate = endDuration.count(); sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption_, date), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(SYSTEM_APP_UID, date), (int)ERR_OK); sptr getDate; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDoNotDisturbDate(bundleOption_, getDate), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDoNotDisturbDate(SYSTEM_APP_UID, getDate), (int)ERR_OK); EXPECT_EQ(getDate->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::DAILY); EXPECT_EQ(getDate->GetBeginDate(), beginDate); EXPECT_EQ(getDate->GetEndDate(), endDate); @@ -1083,13 +1083,13 @@ HWTEST_F(NotificationPreferencesTest, GetDoNotDisturbDate_00100, Function | Smal */ HWTEST_F(NotificationPreferencesTest, GetNotificationsEnabled_00200, Function | SmallTest | Level1) { - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(bundleOption_, true), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(100, true), (int)ERR_OK); bool enable = false; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(bundleOption_, enable), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(100, enable), (int)ERR_OK); EXPECT_TRUE(enable); enable = false; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(bundleOption_, enable), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(101, enable), (int)ERR_OK); EXPECT_FALSE(enable); } @@ -1108,17 +1108,17 @@ HWTEST_F(NotificationPreferencesTest, GetDoNotDisturbDate_00200, Function | Smal int64_t endDate = endDuration.count(); sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption_, date), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(SYSTEM_APP_UID, date), (int)ERR_OK); sptr getDate; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDoNotDisturbDate(bundleOption_, getDate), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDoNotDisturbDate(SYSTEM_APP_UID, getDate), (int)ERR_OK); EXPECT_EQ(getDate->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::DAILY); EXPECT_EQ(getDate->GetBeginDate(), beginDate); EXPECT_EQ(getDate->GetEndDate(), endDate); sptr getExsitDate; EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDoNotDisturbDate( - noExsitbundleOption_, getExsitDate), (int)ERR_ANS_INVALID_PARAM); + NON_SYSTEM_APP_UID, getExsitDate), (int)ERR_ANS_INVALID_PARAM); } } // namespace Notification } // namespace OHOS diff --git a/services/distributed/test/unittest/BUILD.gn b/services/distributed/test/unittest/BUILD.gn index 934c13331449282f544f764a2e1657e705f5dbd2..25c8c0b9ab2b9eef7337faad477955e291993d0d 100644 --- a/services/distributed/test/unittest/BUILD.gn +++ b/services/distributed/test/unittest/BUILD.gn @@ -71,6 +71,7 @@ ohos_unittest("ans_distributed_unit_test") { "ability_runtime:want", "bundle_framework:appexecfwk_base", "distributeddatamgr:distributeddata_inner", + "dmsfwk_standard:zuri", "hitrace_native:libhitrace", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core",