From bfe90132dfbd677055c66f28b70bb343e68957c2 Mon Sep 17 00:00:00 2001 From: chensi10 Date: Fri, 13 Aug 2021 17:21:42 +0800 Subject: [PATCH] Update openharmony code Signed-off-by: chensi10 --- .../ans/core/include/ans_manager_interface.h | 14 +- .../ans/core/include/ans_manager_proxy.h | 9 +- .../ans/core/include/ans_manager_stub.h | 16 +- .../ans/core/include/ans_notification.h | 38 + frameworks/ans/core/src/ans_manager_proxy.cpp | 154 ++- frameworks/ans/core/src/ans_manager_stub.cpp | 130 ++- frameworks/ans/core/src/ans_notification.cpp | 37 + frameworks/ans/native/src/message_user.cpp | 4 +- frameworks/ans/native/src/notification.cpp | 19 +- .../native/src/notification_action_button.cpp | 65 +- .../native/src/notification_bundle_option.cpp | 90 ++ .../ans/native/src/notification_helper.cpp | 21 + .../ans/native/src/notification_request.cpp | 6 +- .../ans/native/src/notification_slot.cpp | 14 +- .../native/src/notification_slot_group.cpp | 2 +- .../ans/native/src/notification_sorting.cpp | 4 +- .../native/src/notification_user_input.cpp | 16 + frameworks/ans/test/moduletest/BUILD.gn | 91 +- .../test/moduletest/ans_fw_module_test.cpp | 14 + .../moduletest/ans_innerkits_module_test.cpp | 332 +++++++ frameworks/ans/test/moduletest/mock/blob.cpp | 211 ++++ .../mock/distributed_kv_data_manager.cpp | 65 ++ .../mock/include/mock_bundle_manager.h | 129 +++ .../mock/include/mock_single_kv_store.h | 250 +++++ .../moduletest/mock/mock_single_kv_store.cpp | 311 ++++++ .../pending_want_test/pending_want_test.cpp | 4 +- .../ans/native/include/notification.h | 4 +- .../include/notification_action_button.h | 48 +- .../include/notification_bundle_option.h | 100 ++ .../native/include/notification_constant.h | 16 +- .../ans/native/include/notification_helper.h | 38 + .../ans/native/include/notification_request.h | 6 +- .../ans/native/include/notification_slot.h | 6 +- interfaces/kits/js/@ohos.notification.d.ts | 170 ++++ interfaces/kits/js/@ohos.wantAgent.d.ts | 153 +++ .../js/notification/notificationContent.d.ts | 77 ++ .../js/notification/notificationRequest.d.ts | 74 ++ .../js/notification/notificationSlot.d.ts | 104 ++ .../js/notification/notificationSorting.d.ts | 31 + .../notification/notificationSortingMap.d.ts | 30 + interfaces/kits/js/wantAgent/triggerInfo.d.ts | 32 + .../kits/js/wantAgent/wantAgentInfo.d.ts | 34 + interfaces/kits/napi/ans/include/common.h | 33 +- interfaces/kits/napi/ans/include/constant.h | 1 + interfaces/kits/napi/ans/include/slot.h | 1 + interfaces/kits/napi/ans/src/cancel.cpp | 133 +-- interfaces/kits/napi/ans/src/common.cpp | 919 +++++++++++------- interfaces/kits/napi/ans/src/constant.cpp | 22 + .../kits/napi/ans/src/create_subscriber.cpp | 39 +- interfaces/kits/napi/ans/src/get_active.cpp | 233 ++--- interfaces/kits/napi/ans/src/init.cpp | 5 + interfaces/kits/napi/ans/src/publish.cpp | 147 +-- interfaces/kits/napi/ans/src/remove.cpp | 289 +++--- interfaces/kits/napi/ans/src/slot.cpp | 538 +++++----- interfaces/kits/napi/ans/src/subscribe.cpp | 88 +- interfaces/kits/napi/ans/src/unsubscribe.cpp | 82 +- .../kits/napi/wantagent/napi_want_agent.cpp | 2 +- ohos.build | 1 + .../include/advanced_notification_service.h | 6 + services/ans/include/bundle_manager_helper.h | 4 +- .../ans/include/notification_preferences.h | 4 +- .../notification_preferences_database.h | 35 +- .../include/notification_preferences_info.h | 11 +- services/ans/include/preferences_constant.h | 82 +- .../ans/src/advanced_notification_service.cpp | 223 ++++- services/ans/src/bundle_manager_helper.cpp | 4 +- services/ans/src/disturb_filter.cpp | 3 + services/ans/src/notification_preferences.cpp | 149 ++- .../src/notification_preferences_database.cpp | 589 ++++++----- .../ans/src/notification_preferences_info.cpp | 5 + services/ans/src/notification_slot_filter.cpp | 14 +- .../unittest/bundle_manager_helper_test.cpp | 4 +- .../unittest/mock/include/mock_ipc_skeleton.h | 6 +- .../mock/mock_bundle_manager_helper.cpp | 4 +- services/ans/test/unittest/mock/mock_ipc.cpp | 8 +- ...notification_preferences_database_test.cpp | 28 +- services/test/moduletest/ans_module_test.cpp | 14 + .../mock/mock_bundle_manager_helper.cpp | 4 +- services/test/moduletest/mock/mock_ipc.cpp | 4 +- 79 files changed, 4935 insertions(+), 1768 deletions(-) create mode 100644 frameworks/ans/native/src/notification_bundle_option.cpp create mode 100644 frameworks/ans/test/moduletest/ans_innerkits_module_test.cpp create mode 100644 frameworks/ans/test/moduletest/mock/blob.cpp create mode 100644 frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp create mode 100644 frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h create mode 100644 frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp create mode 100644 interfaces/innerkits/ans/native/include/notification_bundle_option.h create mode 100644 interfaces/kits/js/@ohos.notification.d.ts create mode 100644 interfaces/kits/js/@ohos.wantAgent.d.ts create mode 100644 interfaces/kits/js/notification/notificationContent.d.ts create mode 100644 interfaces/kits/js/notification/notificationRequest.d.ts create mode 100644 interfaces/kits/js/notification/notificationSlot.d.ts create mode 100644 interfaces/kits/js/notification/notificationSorting.d.ts create mode 100644 interfaces/kits/js/notification/notificationSortingMap.d.ts create mode 100644 interfaces/kits/js/wantAgent/triggerInfo.d.ts create mode 100644 interfaces/kits/js/wantAgent/wantAgentInfo.d.ts diff --git a/frameworks/ans/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index 136bf8cd1..adac10a1f 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -42,11 +42,12 @@ public: virtual ErrCode PublishToDevice(const sptr ¬ification, const std::string &deviceId) = 0; virtual ErrCode Cancel(int notificationId, const std::string &label) = 0; virtual ErrCode CancelAll() = 0; + virtual ErrCode AddSlotByType(NotificationConstant::SlotType slotType) = 0; virtual ErrCode AddSlots(const std::vector> &slots) = 0; - virtual ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) = 0; + virtual ErrCode RemoveSlotByType(NotificationConstant::SlotType slotType) = 0; virtual ErrCode RemoveAllSlots() = 0; virtual ErrCode AddSlotGroups(std::vector> groups) = 0; - virtual ErrCode GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) = 0; + virtual ErrCode GetSlotByType(NotificationConstant::SlotType slotType, sptr &slot) = 0; virtual ErrCode GetSlots(std::vector> &slots) = 0; virtual ErrCode GetSlotGroup(const std::string &groupId, sptr &group) = 0; virtual ErrCode GetSlotGroups(std::vector> &groups) = 0; @@ -69,6 +70,9 @@ public: virtual ErrCode SetPrivateNotificationsAllowed(bool allow) = 0; virtual ErrCode GetPrivateNotificationsAllowed(bool &allow) = 0; virtual ErrCode Delete(const std::string &key) = 0; + virtual ErrCode RemoveNotification( + const std::string &bundle, int uid, int notificationId, const std::string &label) = 0; + virtual ErrCode RemoveAllNotifications(const std::string &bundle, int uid) = 0; virtual ErrCode DeleteByBundle(const std::string &bundle) = 0; virtual ErrCode DeleteAll() = 0; virtual ErrCode GetSlotsByBundle(const std::string &bundle, std::vector> &slots) = 0; @@ -81,6 +85,7 @@ public: const std::string &deviceId, const std::string &bundleName, bool enabled) = 0; virtual ErrCode SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) = 0; virtual ErrCode GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) = 0; + virtual ErrCode GetShowBadgeEnabled(bool &enabled) = 0; virtual ErrCode Subscribe(const sptr &subscriber, const sptr &info) = 0; virtual ErrCode Unsubscribe( const sptr &subscriber, const sptr &info) = 0; @@ -90,12 +95,14 @@ public: virtual ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) = 0; virtual ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) = 0; + protected: enum TransactId : uint32_t { PUBLISH_NOTIFICATION = FIRST_CALL_TRANSACTION, PUBLISH_NOTIFICATION_TO_DEVICE, CANCEL_NOTIFICATION, CANCEL_ALL_NOTIFICATIONS, + ADD_SLOT_BY_TYPE, ADD_SLOTS, REMOVE_SLOT_BY_TYPE, REMOVE_ALL_SLOTS, @@ -120,6 +127,8 @@ protected: IS_NOTIFICATION_POLICY_ACCESS_GRANTED, SET_PRIVATIVE_NOTIFICATIONS_ALLOWED, GET_PRIVATIVE_NOTIFICATIONS_ALLOWED, + REMOVE_NOTIFICATION, + REMOVE_ALL_NOTIFICATIONS, DELETE_NOTIFICATION, DELETE_NOTIFICATION_BY_BUNDLE, DELETE_ALL_NOTIFICATIONS, @@ -131,6 +140,7 @@ protected: SET_NOTIFICATION_ENABLED_FOR_SPECIAL_BUNDLE, SET_SHOW_BADGE_ENABLED_FOR_BUNDLE, GET_SHOW_BADGE_ENABLED_FOR_BUNDLE, + GET_SHOW_BADGE_ENABLED, SUBSCRIBE_NOTIFICATION, UNSUBSCRIBE_NOTIFICATION, ARE_NOTIFICATION_SUSPENDED, diff --git a/frameworks/ans/core/include/ans_manager_proxy.h b/frameworks/ans/core/include/ans_manager_proxy.h index d3221d4a0..306693233 100644 --- a/frameworks/ans/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -32,11 +32,12 @@ public: ErrCode PublishToDevice(const sptr ¬ification, const std::string &deviceId) override; ErrCode Cancel(int notificationId, const std::string &label) override; ErrCode CancelAll() override; + ErrCode AddSlotByType(NotificationConstant::SlotType slotType) override; ErrCode AddSlots(const std::vector> &slots) override; - ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) override; + ErrCode RemoveSlotByType(NotificationConstant::SlotType slotType) override; ErrCode RemoveAllSlots() override; ErrCode AddSlotGroups(std::vector> groups) override; - ErrCode GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) override; + ErrCode GetSlotByType(NotificationConstant::SlotType slotType, sptr &slot) override; ErrCode GetSlots(std::vector> &slots) override; ErrCode GetSlotGroup(const std::string &groupId, sptr &group) override; ErrCode GetSlotGroups(std::vector> &groups) override; @@ -58,6 +59,9 @@ public: ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; ErrCode SetPrivateNotificationsAllowed(bool allow) override; ErrCode GetPrivateNotificationsAllowed(bool &allow) override; + ErrCode RemoveNotification( + const std::string &bundle, int uid, int notificationId, const std::string &label) override; + ErrCode RemoveAllNotifications(const std::string &bundle, int uid) override; ErrCode Delete(const std::string &key) override; ErrCode DeleteByBundle(const std::string &bundle) override; ErrCode DeleteAll() override; @@ -71,6 +75,7 @@ public: const std::string &deviceId, const std::string &bundleName, bool enabled) override; ErrCode SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) override; ErrCode GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) override; + ErrCode GetShowBadgeEnabled(bool &enabled) override; ErrCode Subscribe(const sptr &subscriber, const sptr &info) override; ErrCode Unsubscribe(const sptr &subscriber, const sptr &info) override; ErrCode AreNotificationsSuspended(bool &suspended) override; diff --git a/frameworks/ans/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h index bc9f3b356..1cba1b3c6 100644 --- a/frameworks/ans/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -38,11 +38,12 @@ public: const sptr ¬ification, const std::string &deviceId) override; virtual ErrCode Cancel(int notificationId, const std::string &label) override; virtual ErrCode CancelAll() override; + virtual ErrCode AddSlotByType(NotificationConstant::SlotType slotType) override; virtual ErrCode AddSlots(const std::vector> &slots) override; - virtual ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) override; + virtual ErrCode RemoveSlotByType(NotificationConstant::SlotType slotType) override; virtual ErrCode RemoveAllSlots() override; virtual ErrCode AddSlotGroups(std::vector> groups) override; - virtual ErrCode GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) override; + virtual ErrCode GetSlotByType(NotificationConstant::SlotType slotType, sptr &slot) override; virtual ErrCode GetSlots(std::vector> &slots) override; virtual ErrCode GetSlotGroup(const std::string &groupId, sptr &group) override; virtual ErrCode GetSlotGroups(std::vector> &groups) override; @@ -64,6 +65,9 @@ public: virtual ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; virtual ErrCode SetPrivateNotificationsAllowed(bool allow) override; virtual ErrCode GetPrivateNotificationsAllowed(bool &allow) override; + virtual ErrCode RemoveNotification( + const std::string &bundle, int uid, int notificationId, const std::string &label) override; + virtual ErrCode RemoveAllNotifications(const std::string &bundle, int uid) override; virtual ErrCode Delete(const std::string &key) override; virtual ErrCode DeleteByBundle(const std::string &bundle) override; virtual ErrCode DeleteAll() override; @@ -77,6 +81,7 @@ public: const std::string &deviceId, const std::string &bundleName, bool enabled) override; virtual ErrCode SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) override; virtual ErrCode GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) override; + virtual ErrCode GetShowBadgeEnabled(bool &enabled) override; virtual ErrCode Subscribe( const sptr &subscriber, const sptr &info) override; virtual ErrCode Unsubscribe( @@ -89,12 +94,14 @@ public: virtual ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; private: - static const std::map> interfaces_; + static const std::map> + interfaces_; ErrCode HandlePublish(MessageParcel &data, MessageParcel &reply); ErrCode HandlePublishToDevice(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancel(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelAll(MessageParcel &data, MessageParcel &reply); + ErrCode HandleAddSlotByType(MessageParcel &data, MessageParcel &reply); ErrCode HandleAddSlots(MessageParcel &data, MessageParcel &reply); ErrCode HandleRemoveSlotByType(MessageParcel &data, MessageParcel &reply); ErrCode HandleRemoveAllSlots(MessageParcel &data, MessageParcel &reply); @@ -119,6 +126,8 @@ private: ErrCode HandleIsNotificationPolicyAccessGranted(MessageParcel &data, MessageParcel &reply); ErrCode HandleSetPrivateNotificationsAllowed(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetPrivateNotificationsAllowed(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveNotification(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveAllNotifications(MessageParcel &data, MessageParcel &reply); ErrCode HandleDelete(MessageParcel &data, MessageParcel &reply); ErrCode HandleDeleteByBundle(MessageParcel &data, MessageParcel &reply); ErrCode HandleDeleteAll(MessageParcel &data, MessageParcel &reply); @@ -130,6 +139,7 @@ private: ErrCode HandleSetNotificationsEnabledForSpecialBundle(MessageParcel &data, MessageParcel &reply); ErrCode HandleSetShowBadgeEnabledForBundle(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetShowBadgeEnabledForBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetShowBadgeEnabled(MessageParcel &data, MessageParcel &reply); ErrCode HandleSubscribe(MessageParcel &data, MessageParcel &reply); ErrCode HandleUnsubscribe(MessageParcel &data, MessageParcel &reply); ErrCode HandleAreNotificationsSuspended(MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/ans/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h index bea2c2c7f..c8c88c0b2 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -45,6 +45,14 @@ public: */ ErrCode AddNotificationSlot(const NotificationSlot &slot); + /** + * Adds a notification slot by type. + * + * @param slotType Indicates the notification slot type to be added. + * @return Returns add notification slot result. + */ + ErrCode AddSlotByType(const NotificationConstant::SlotType &slotType); + /** * Creates multiple notification slots. * @@ -62,6 +70,13 @@ public: */ ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType); + /** + * Deletes all notification slots. + * + * @return Returns remove all slots result. + */ + ErrCode RemoveAllSlots(); + /** * Queries a created notification slot. * @@ -382,6 +397,29 @@ public: */ ErrCode RemoveNotification(const std::string &key); + /** + * Removes a specified removable notification of other applications. + * @note Your application must have platform signature to use this method. + * + * @param bundleName Indicates the bundle name of the application whose notifications are to be removed. + * @param uid Indicates the uid of the application whose notifications are to be removed. + * @param notificationId Indicates the id of the notification to remove. + * @param label Indicates the label of the notification to remove. + * @return Returns remove notification result. + */ + ErrCode RemoveNotification( + const std::string &bundleName, const int32_t uid, const int32_t notificationId, const std::string &label); + + /** + * Removes a specified removable notification of other applications. + * @note Your application must have platform signature to use this method. + * + * @param bundleName Indicates the bundle name of the application whose notifications are to be removed. + * @param uid Indicates the uid of the application whose notifications are to be removed. + * @return Returns remove notification result. + */ + ErrCode RemoveNotifications(const std::string &bundleName, const int32_t uid); + /** * Removes all removable notifications of a specified bundle. * @note Your application must have platform signature to use this method. diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index c113a2589..dbb571f1a 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -167,6 +167,35 @@ ErrCode AnsManagerProxy::CancelAll() return result; } +ErrCode AnsManagerProxy::AddSlotByType(NotificationConstant::SlotType slotType) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[AddSlotByType] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(slotType)) { + ANS_LOGW("[AddSlotByType] fail:: write slotIds failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(ADD_SLOT_BY_TYPE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[AddSlotByType] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[AddSlotByType] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + ErrCode AnsManagerProxy::AddSlots(const std::vector> &slots) { if (slots.empty()) { @@ -207,7 +236,7 @@ ErrCode AnsManagerProxy::AddSlots(const std::vector> &slo return result; } -ErrCode AnsManagerProxy::RemoveSlotByType(const NotificationConstant::SlotType slotType) +ErrCode AnsManagerProxy::RemoveSlotByType(NotificationConstant::SlotType slotType) { MessageParcel data; if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { @@ -257,7 +286,7 @@ ErrCode AnsManagerProxy::RemoveAllSlots() return ERR_ANS_PARCELABLE_FAILED; } - return result; + return result; } ErrCode AnsManagerProxy::AddSlotGroups(std::vector> groups) @@ -300,7 +329,7 @@ ErrCode AnsManagerProxy::AddSlotGroups(std::vector> return result; } -ErrCode AnsManagerProxy::GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) +ErrCode AnsManagerProxy::GetSlotByType(NotificationConstant::SlotType slotType, sptr &slot) { MessageParcel data; if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { @@ -922,6 +951,95 @@ ErrCode AnsManagerProxy::GetPrivateNotificationsAllowed(bool &allow) return result; } +ErrCode AnsManagerProxy::RemoveNotification( + const std::string &bundle, int uid, int notificationId, const std::string &label) +{ + if (bundle.empty()) { + ANS_LOGW("[RemoveNotification] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[RemoveNotification] fail:, write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundle)) { + ANS_LOGW("[RemoveNotification] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(uid)) { + ANS_LOGW("[RemoveNotification] fail: write uid failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(notificationId)) { + ANS_LOGW("[RemoveNotification] fail: write notificationId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(label)) { + ANS_LOGW("[RemoveNotification] fail: write label failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(REMOVE_NOTIFICATION, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[RemoveNotification] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[RemoveNotification] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::RemoveAllNotifications(const std::string &bundle, int uid) +{ + if (bundle.empty()) { + ANS_LOGW("[RemoveAllNotifications] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[RemoveAllNotifications] fail:, write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundle)) { + ANS_LOGW("[RemoveAllNotifications] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(uid)) { + ANS_LOGW("[RemoveAllNotifications] fail:: write uid failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(REMOVE_ALL_NOTIFICATIONS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[RemoveNotification] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[RemoveNotification] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + ErrCode AnsManagerProxy::Delete(const std::string &key) { if (key.empty()) { @@ -1340,6 +1458,36 @@ ErrCode AnsManagerProxy::GetShowBadgeEnabledForBundle(const std::string &bundle, return result; } +ErrCode AnsManagerProxy::GetShowBadgeEnabled(bool &enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetShowBadgeEnabled] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_SHOW_BADGE_ENABLED, option, data, reply); + + if (result != ERR_OK) { + ANS_LOGW("[GetShowBadgeEnabled] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetShowBadgeEnabled] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(enabled)) { + ANS_LOGW("[GetShowBadgeEnabled] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + ErrCode AnsManagerProxy::Subscribe(const sptr &subscriber, const sptr &info) { if (subscriber == nullptr) { diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 484dd0a49..ab5e3020d 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -39,6 +39,9 @@ const std::map(data.ReadInt32()); + + ErrCode result = AddSlotByType(slotType); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleAddSlotByType] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleAddSlots(MessageParcel &data, MessageParcel &reply) { std::vector> slots; @@ -667,6 +695,62 @@ ErrCode AnsManagerStub::HandleGetPrivateNotificationsAllowed(MessageParcel &data return ERR_OK; } +ErrCode AnsManagerStub::HandleRemoveNotification(MessageParcel &data, MessageParcel &reply) +{ + std::string bundle; + if (!data.ReadString(bundle)) { + ANS_LOGW("[HandleRemoveNotification] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + int uid = 0; + if (!data.ReadInt32(uid)) { + ANS_LOGW("[HandleRemoveNotification] fail: read uid failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + int notificationId = 0; + if (!data.ReadInt32(notificationId)) { + ANS_LOGW("[HandleRemoveNotification] fail: read notificationId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::string label; + if (!data.ReadString(label)) { + ANS_LOGW("[HandleRemoveNotification] fail: read label failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = RemoveNotification(bundle, uid, notificationId, label); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleRemoveNotification] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleRemoveAllNotifications(MessageParcel &data, MessageParcel &reply) +{ + std::string bundle; + if (!data.ReadString(bundle)) { + ANS_LOGW("[HandleRemoveAllNotifications] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + int uid = 0; + if (!data.ReadInt32(uid)) { + ANS_LOGW("[HandleRemoveAllNotifications] fail: read uid failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = RemoveAllNotifications(bundle, uid); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleRemoveAllNotifications] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleDelete(MessageParcel &data, MessageParcel &reply) { std::string key; @@ -888,6 +972,23 @@ ErrCode AnsManagerStub::HandleGetShowBadgeEnabledForBundle(MessageParcel &data, return ERR_OK; } +ErrCode AnsManagerStub::HandleGetShowBadgeEnabled(MessageParcel &data, MessageParcel &reply) +{ + bool enabled = false; + ErrCode result = GetShowBadgeEnabled(enabled); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetShowBadgeEnabled] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(enabled)) { + ANS_LOGW("[HandleGetShowBadgeEnabled] fail: write enabled failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleSubscribe(MessageParcel &data, MessageParcel &reply) { sptr subscriber = data.ReadRemoteObject(); @@ -1116,13 +1217,19 @@ ErrCode AnsManagerStub::CancelAll() return ERR_OK; } +ErrCode AnsManagerStub::AddSlotByType(NotificationConstant::SlotType slotType) +{ + ANS_LOGW("AnsManagerStub::AddSlotByType called!"); + return ERR_OK; +} + ErrCode AnsManagerStub::AddSlots(const std::vector> &slots) { ANS_LOGW("AnsManagerStub::AddSlots called!"); return ERR_OK; } -ErrCode AnsManagerStub::RemoveSlotByType(const NotificationConstant::SlotType slotType) +ErrCode AnsManagerStub::RemoveSlotByType(NotificationConstant::SlotType slotType) { ANS_LOGW("AnsManagerStub::RemoveSlotByType called!"); return ERR_OK; @@ -1140,7 +1247,7 @@ ErrCode AnsManagerStub::AddSlotGroups(std::vector> g return ERR_OK; } -ErrCode AnsManagerStub::GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) +ErrCode AnsManagerStub::GetSlotByType(NotificationConstant::SlotType slotType, sptr &slot) { ANS_LOGW("AnsManagerStub::GetSlotByType called!"); return ERR_OK; @@ -1262,6 +1369,19 @@ ErrCode AnsManagerStub::GetPrivateNotificationsAllowed(bool &allow) return ERR_OK; } +ErrCode AnsManagerStub::RemoveNotification( + const std::string &bundle, int uid, int notificationId, const std::string &label) +{ + ANS_LOGW("AnsManagerStub::RemoveNotification called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::RemoveAllNotifications(const std::string &bundle, int uid) +{ + ANS_LOGW("AnsManagerStub::RemoveAllNotifications called!"); + return ERR_OK; +} + ErrCode AnsManagerStub::Delete(const std::string &key) { ANS_LOGW("AnsManagerStub::Delete called!"); @@ -1330,6 +1450,12 @@ ErrCode AnsManagerStub::GetShowBadgeEnabledForBundle(const std::string &bundle, return ERR_OK; } +ErrCode AnsManagerStub::GetShowBadgeEnabled(bool &enabled) +{ + ANS_LOGW("AnsManagerStub::GetShowBadgeEnabled called!"); + return ERR_OK; +} + ErrCode AnsManagerStub::Subscribe(const sptr &subscriber, const sptr &info) { ANS_LOGW("AnsManagerStub::Subscribe called!"); diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index 57abd5718..670ee1166 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -30,6 +30,15 @@ ErrCode AnsNotification::AddNotificationSlot(const NotificationSlot &slot) return AddNotificationSlots(slots); } +ErrCode AnsNotification::AddSlotByType(const NotificationConstant::SlotType &slotType) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->AddSlotByType(slotType); +} + ErrCode AnsNotification::AddNotificationSlots(const std::vector &slots) { if (slots.size() == 0) { @@ -63,6 +72,15 @@ ErrCode AnsNotification::RemoveNotificationSlot(const NotificationConstant::Slot return ansManagerProxy_->RemoveSlotByType(slotType); } +ErrCode AnsNotification::RemoveAllSlots() +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->RemoveAllSlots(); +} + ErrCode AnsNotification::GetNotificationSlot( const NotificationConstant::SlotType &slotType, sptr &slot) { @@ -462,6 +480,25 @@ ErrCode AnsNotification::RemoveNotification(const std::string &key) return ansManagerProxy_->Delete(key); } +ErrCode AnsNotification::RemoveNotification( + const std::string &bundleName, const int32_t uid, const int32_t notificationId, const std::string &label) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->RemoveNotification(bundleName, uid, notificationId, label); +} + +ErrCode AnsNotification::RemoveNotifications(const std::string &bundleName, const int32_t uid) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->RemoveAllNotifications(bundleName, uid); +} + ErrCode AnsNotification::RemoveNotifications(const std::string &bundleName) { if (!GetAnsManagerProxy()) { diff --git a/frameworks/ans/native/src/message_user.cpp b/frameworks/ans/native/src/message_user.cpp index d91769912..161d72387 100644 --- a/frameworks/ans/native/src/message_user.cpp +++ b/frameworks/ans/native/src/message_user.cpp @@ -91,8 +91,8 @@ std::string MessageUser::Dump() const ", name = " + name_ + ", pixelMap = " + (pixelMap_ ? "not null" : "null") + ", uri = " + uri_.ToString() + - ", isMachine = " + std::to_string(isMachine_) + - ", isUserImportant = " + std::to_string(isUserImportant_) + "]"; + ", isMachine = " + (isMachine_ ? "true" : "false") + + ", isUserImportant = " + (isUserImportant_ ? "true" : "false") + "]"; } bool MessageUser::Marshalling(Parcel &parcel) const diff --git a/frameworks/ans/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp index 31b376365..399a18b20 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -42,26 +42,17 @@ Notification::Notification(const Notification &other) bool Notification::EnableLight() const { - if (ledLightColor_ == -1) { - return false; - } - return true; + return enableLight_; } bool Notification::EnableSound() const { - if (sound_ == nullptr) { - return false; - } - return true; + return enableSound_; } bool Notification::EnableVibrate() const { - if (!vibrationStyle_.size()) { - return false; - } - return true; + return enableViration_; } std::string Notification::GetBundleName() const @@ -137,7 +128,7 @@ Uri Notification::GetSound() const return Uri(""); } -uid_t Notification::GetUid() const +pid_t Notification::GetUid() const { if (request_ == nullptr) { return 0; @@ -145,7 +136,7 @@ uid_t Notification::GetUid() const return request_->GetCreatorUid(); } -uid_t Notification::GetPid() const +pid_t Notification::GetPid() const { if (request_ == nullptr) { return 0; diff --git a/frameworks/ans/native/src/notification_action_button.cpp b/frameworks/ans/native/src/notification_action_button.cpp index 80f7e40c9..a22d8c340 100644 --- a/frameworks/ans/native/src/notification_action_button.cpp +++ b/frameworks/ans/native/src/notification_action_button.cpp @@ -23,7 +23,8 @@ namespace Notification { std::shared_ptr NotificationActionButton::Create(const std::shared_ptr &icon, const std::string &title, const std::shared_ptr &wantAgent, const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, - bool autoCreatedReplies, const std::vector> &userInputs, bool isContextual) + bool autoCreatedReplies, const std::vector> &mimeTypeOnlyInputs, + const std::vector> &userInputs, bool isContextual) { if (isContextual && (!icon || !wantAgent)) { ANS_LOGE("icon or wantAgent can not be null when isContextual is true"); @@ -33,10 +34,29 @@ std::shared_ptr NotificationActionButton::Create(const auto realExtras = extras; if (!realExtras) { realExtras = std::make_shared(); + + if (!realExtras) { + ANS_LOGE("create PacMap object failed"); + return {}; + } + } + + std::vector> onlyInputs = mimeTypeOnlyInputs; + std::vector> textInputs{}; + for (auto &userInput : userInputs) { + if (!userInput) { + continue; + } + + if (userInput->IsMimeTypeOnly()) { + onlyInputs.push_back(userInput); + } else { + textInputs.push_back(userInput); + } } auto pActionButton = new (std::nothrow) NotificationActionButton( - icon, title, wantAgent, realExtras, semanticActionButton, autoCreatedReplies, userInputs, isContextual); + icon, title, wantAgent, realExtras, semanticActionButton, autoCreatedReplies, onlyInputs, textInputs, isContextual); if (pActionButton == nullptr) { ANS_LOGE("create NotificationActionButton object failed"); return {}; @@ -45,9 +65,24 @@ std::shared_ptr NotificationActionButton::Create(const return std::shared_ptr(pActionButton); } +std::shared_ptr NotificationActionButton::Create( + const std::shared_ptr &actionButton) +{ + return NotificationActionButton::Create(actionButton->GetIcon(), + actionButton->GetTitle(), + actionButton->GetWantAgent(), + actionButton->GetAdditionalData(), + actionButton->GetSemanticActionButton(), + actionButton->IsAutoCreatedReplies(), + actionButton->GetMimeTypeOnlyUserInputs(), + actionButton->GetUserInputs(), + actionButton->IsContextDependent()); +} + NotificationActionButton::NotificationActionButton(const std::shared_ptr &icon, const std::string &title, const std::shared_ptr &wantAgent, const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, + const std::vector> &mimeTypeOnlyInputs, const std::vector> &userInputs, bool isContextual) : icon_(icon), title_(title), @@ -55,6 +90,7 @@ NotificationActionButton::NotificationActionButton(const std::shared_ptr &userInput) +{ + if (!userInput) { + ANS_LOGE("The userInput is invalid."); + return; + } + + if (!userInput->IsMimeTypeOnly()) { + ANS_LOGE("The userInput is not a particular MIME types."); + return; + } + + mimeTypeOnlyUserInputs_.emplace_back(userInput); +} + +std::vector> NotificationActionButton::GetMimeTypeOnlyUserInputs() const +{ + return mimeTypeOnlyUserInputs_; +} + void NotificationActionButton::AddNotificationUserInput(const std::shared_ptr &userInput) { if (!userInput) { @@ -109,11 +165,6 @@ std::vector> NotificationActionButton::Ge return userInputs_; } -std::vector> NotificationActionButton::GetMimeTypeOnlyUserInputs() const -{ - return {}; -} - void NotificationActionButton::SetAutoCreatedReplies(bool autoCreatedReplies) { autoCreatedReplies_ = autoCreatedReplies; diff --git a/frameworks/ans/native/src/notification_bundle_option.cpp b/frameworks/ans/native/src/notification_bundle_option.cpp new file mode 100644 index 000000000..0a2da883d --- /dev/null +++ b/frameworks/ans/native/src/notification_bundle_option.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c); 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License");; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "notification_bundle_option.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +NotificationBundleOption::NotificationBundleOption(const std::string &bundleName, const int32_t uid) : bundleName_(bundleName), uid_(uid) +{} + +NotificationBundleOption::~NotificationBundleOption() +{} + +void NotificationBundleOption::SetBundleName(const std::string &bundleName) +{ + bundleName_ = bundleName; +} + +std::string NotificationBundleOption::GetBundleName() const +{ + return bundleName_; +} + +void NotificationBundleOption::SetUid(const int32_t uid) +{ + uid_ = uid; +} + +int32_t NotificationBundleOption::GetUid() const +{ + return uid_; +} + +std::string NotificationBundleOption::Dump() +{ + return "NotificationBundleOption[ bundleName = " + bundleName_ +", uid = " + std::to_string(uid_) + " ]"; +} + +bool NotificationBundleOption::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(bundleName_)) { + ANS_LOGE("Failed to write bundle name"); + return false; + } + + if (!parcel.WriteInt32(uid_)) { + ANS_LOGE("Failed to write uid"); + return false; + } + + return true; +} + +NotificationBundleOption *NotificationBundleOption::Unmarshalling(Parcel &parcel) +{ + auto pbundleOption = new NotificationBundleOption(); + if ((nullptr != pbundleOption) && !pbundleOption->ReadFromParcel(parcel)) { + delete pbundleOption; + pbundleOption = nullptr; + } + + return pbundleOption; +} + +bool NotificationBundleOption::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadString(bundleName_)) { + ANS_LOGE("Failed to read bundle name"); + return false; + } + + uid_ = parcel.ReadInt32(); + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/frameworks/ans/native/src/notification_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp index 2570e4d09..3ff373dd9 100644 --- a/frameworks/ans/native/src/notification_helper.cpp +++ b/frameworks/ans/native/src/notification_helper.cpp @@ -24,6 +24,11 @@ ErrCode NotificationHelper::AddNotificationSlot(const NotificationSlot &slot) return DelayedSingleton::GetInstance()->AddNotificationSlot(slot); } +ErrCode NotificationHelper::AddSlotByType(const NotificationConstant::SlotType &slotType) +{ + return DelayedSingleton::GetInstance()->AddSlotByType(slotType); +} + ErrCode NotificationHelper::AddNotificationSlots(const std::vector &slots) { return DelayedSingleton::GetInstance()->AddNotificationSlots(slots); @@ -34,6 +39,11 @@ ErrCode NotificationHelper::RemoveNotificationSlot(const NotificationConstant::S return DelayedSingleton::GetInstance()->RemoveNotificationSlot(slotType); } +ErrCode NotificationHelper::RemoveAllSlots() +{ + return DelayedSingleton::GetInstance()->RemoveAllSlots(); +} + ErrCode NotificationHelper::GetNotificationSlot( const NotificationConstant::SlotType &slotType, sptr &slot) { @@ -194,6 +204,17 @@ ErrCode NotificationHelper::RemoveNotification(const std::string &key) return DelayedSingleton::GetInstance()->RemoveNotification(key); } +ErrCode NotificationHelper::RemoveNotification( + const std::string &bundleName, const int32_t uid, const int32_t notificationId, const std::string &label) +{ + return DelayedSingleton::GetInstance()->RemoveNotification(bundleName, uid, notificationId, label); +} + +ErrCode NotificationHelper::RemoveNotifications(const std::string &bundleName, const int32_t uid) +{ + return DelayedSingleton::GetInstance()->RemoveNotifications(bundleName, uid); +} + ErrCode NotificationHelper::RemoveNotifications(const std::string &bundleName) { return DelayedSingleton::GetInstance()->RemoveNotifications(bundleName); diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index 1b850292c..ff5717b3a 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -727,12 +727,12 @@ pid_t NotificationRequest::GetCreatorPid() const return creatorPid_; } -void NotificationRequest::SetCreatorUid(uid_t uid) +void NotificationRequest::SetCreatorUid(pid_t uid) { creatorUid_ = uid; } -uid_t NotificationRequest::GetCreatorUid() const +pid_t NotificationRequest::GetCreatorUid() const { return creatorUid_; } @@ -1188,7 +1188,7 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) autoDeletedTime_ = parcel.ReadInt64(); creatorPid_ = static_cast(parcel.ReadInt32()); - creatorUid_ = static_cast(parcel.ReadInt32()); + creatorUid_ = static_cast(parcel.ReadInt32()); if (!parcel.ReadString(settingsText_)) { ANS_LOGE("Failed to read settings text"); diff --git a/frameworks/ans/native/src/notification_slot.cpp b/frameworks/ans/native/src/notification_slot.cpp index 05223bd1c..cf83dbca4 100644 --- a/frameworks/ans/native/src/notification_slot.cpp +++ b/frameworks/ans/native/src/notification_slot.cpp @@ -196,15 +196,19 @@ void NotificationSlot::EnableBadge(bool isShowBadge) std::string NotificationSlot::Dump() const { - return "NotificationSlot[id = " + id_ + ", name = " + name_ + ", description = " + description_ + + return "NotificationSlot[ id = " + id_ + + ", name = " + name_ + + ", description = " + description_ + ", type = " + std::to_string(static_cast(type_)) + ", level = " + std::to_string(static_cast(level_)) + - ", isBypassDnd = " + std::to_string(isBypassDnd_) + + ", isBypassDnd = " + (isBypassDnd_ ? "true" : "false") + ", visibleness = " + std::to_string(static_cast(lockScreenVisibleness_)) + - ", sound = " + sound_.ToString() + ", isLightEnabled = " + std::to_string(isLightEnabled_) + - ", lightColor = " + std::to_string(lightColor_) + ", isVibrate = " + std::to_string(isVibrationEnabled_) + + ", sound = " + sound_.ToString() + + ", isLightEnabled = " + (isLightEnabled_ ? "true" : "false") + + ", lightColor = " + std::to_string(lightColor_) + + ", isVibrate = " + (isVibrationEnabled_ ? "true" : "false") + ", vibration = " + MergeVectorToString(vibrationValues_) + - ", isShowBadge = " + std::to_string(isShowBadge_) + ", groupId = " + groupId_ + "]"; + ", isShowBadge = " + (isShowBadge_ ? "true" : "false") + ", groupId = " + groupId_ + "]"; } bool NotificationSlot::Marshalling(Parcel &parcel) const diff --git a/frameworks/ans/native/src/notification_slot_group.cpp b/frameworks/ans/native/src/notification_slot_group.cpp index 6de656121..2e0d98d3e 100644 --- a/frameworks/ans/native/src/notification_slot_group.cpp +++ b/frameworks/ans/native/src/notification_slot_group.cpp @@ -77,7 +77,7 @@ std::string NotificationSlotGroup::Dump() const ", name = " + name_ + ", description = " + description_ + ", slots = " + contents + - ", isDisabled = " + std::to_string(isDisabled_) + "]"; + ", isDisabled = " + (isDisabled_ ? "true" : "false") + "]"; } bool NotificationSlotGroup::Marshalling(Parcel &parcel) const diff --git a/frameworks/ans/native/src/notification_sorting.cpp b/frameworks/ans/native/src/notification_sorting.cpp index 22fbba79b..6315d338d 100644 --- a/frameworks/ans/native/src/notification_sorting.cpp +++ b/frameworks/ans/native/src/notification_sorting.cpp @@ -58,8 +58,8 @@ std::string NotificationSorting::Dump() const return "NotificationSorting[key =" + key_ + ", ranking =" + std::to_string(ranking_) + ", importance =" + std::to_string(importance_) + ", visiblenessOverride =" + std::to_string(visiblenessOverride_) + - ", isDisplayBadge =" + std::to_string(isDisplayBadge_) + - ", isHiddenNotification =" + std::to_string(isHiddenNotification_) + + ", isDisplayBadge =" + (isDisplayBadge_ ? "true" : "false") + + ", isHiddenNotification =" + (isHiddenNotification_ ? "true" : "false") + ", groupKeyOverride =" + groupKeyOverride_ + ", slot_ =" + contents + "]"; } diff --git a/frameworks/ans/native/src/notification_user_input.cpp b/frameworks/ans/native/src/notification_user_input.cpp index 5c6e96027..d0f11e887 100644 --- a/frameworks/ans/native/src/notification_user_input.cpp +++ b/frameworks/ans/native/src/notification_user_input.cpp @@ -202,8 +202,24 @@ bool NotificationUserInput::IsPermitFreeFormInput() const std::string NotificationUserInput::Dump() { + std::string options; + for (std::string option : options_) { + options += option + ", "; + } + options.pop_back(); + options.pop_back(); + + std::string permitMimeTypes; + for (auto permitMimeType : permitMimeTypes_) { + permitMimeTypes += permitMimeType + ", "; + } + permitMimeTypes.pop_back(); + permitMimeTypes.pop_back(); + return "NotificationUserInput[ inputKey = " + inputKey_ + " tag = " + tag_ + + "options = [ " + options + " ]" + " permitFreeFormInput = " + (permitFreeFormInput_ ? "true" : "false") + + " permitMimeTypes = [ " + permitMimeTypes + " ]" + " editType = " + std::to_string(static_cast(editType_)) + " ]"; } diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index cc524695c..72681ca21 100644 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -66,6 +66,7 @@ ohos_moduletest("ans_fw_module_test") { "${interfaces_path}/innerkits/wantAgent/include", "//utils/native/base/include", "//base/notification/ans_standard/frameworks/ans/test/moduletest/mock/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include/", ] sources = [ @@ -94,7 +95,6 @@ ohos_moduletest("ans_fw_module_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", @@ -119,9 +119,96 @@ ohos_moduletest("ans_fw_module_test") { part_name = "ans_standard" } +ohos_moduletest("ans_innerkits_module_test") { + module_out_path = module_output_path + include_dirs = [ + "include", + "${interfaces_path}/ans/native/include", + "${frameworks_path}/ans/core/common/include", + "${frameworks_path}/ans/core/include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "//base/notification/ans_standard/services/ans/include", + "//third_party/json/include", + "//foundation/communication/utils/include", + "//foundation/communication/ipc/ipc/native/src/core/include", + "//foundation/communication/ipc/utils/include", + "//foundation/communication/ipc/ipc/softbus_temp", + "//foundation/distributedschedule/samgr/services/samgr/native/include", + "//foundation/communication/ipc/interfaces/innerkits/libdbinder/include", + "//base/notification/ces_standard/cesfwk/interfaces/innerkits/native/include", + "${core_path}/common/include", + "${core_path}/include", + "${interfaces_path}/innerkits/ans/native/include", + "${interfaces_path}/innerkits/wantAgent/include", + "//utils/native/base/include", + "//base/notification/ans_standard/frameworks/ans/test/moduletest/mock/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/dfx", + "//developtools/bytrace_standard/interfaces/innerkits/native/include", + ] + + sources = [ + #"${core_path}/src/ans_manager_proxy.cpp", + #"${core_path}/src/ans_manager_stub.cpp", + "${core_path}/src/ans_notification.cpp", + "${core_path}/src/ans_subscriber_proxy.cpp", + "${core_path}/src/ans_subscriber_stub.cpp", + "ans_innerkits_module_test.cpp", + "mock/blob.cpp", + "mock/distributed_kv_data_manager.cpp", + "mock/mock_bundle_manager.cpp", + "mock/mock_bundle_mgr_proxy.cpp", + "mock/mock_ipc.cpp", + "mock/mock_ipc_object_proxy.cpp", + "mock/mock_single_kv_store.cpp", + ] + + configs = [ "//utils/native/base:utils_config" ] + + deps = [ + "${frameworks_path}/ans/core:ans_core", + "${frameworks_path}/ans/native:ans_innerkits", + "${frameworks_path}/wantagent:wantagent_innerkits", + "${services_path}/ans:libans", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] + + subsystem_name = "notification" + part_name = "ans_standard" +} + group("moduletest") { testonly = true deps = [] - deps += [ ":ans_fw_module_test" ] + deps += [ + ":ans_fw_module_test", + ":ans_innerkits_module_test", + ] } diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index 6a33dab28..cdb9e9207 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -1,3 +1,17 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #include #include diff --git a/frameworks/ans/test/moduletest/ans_innerkits_module_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_test.cpp new file mode 100644 index 000000000..dc8aff506 --- /dev/null +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_test.cpp @@ -0,0 +1,332 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include + +#include "ans_inner_errors.h" +#include "ans_manager_proxy.h" +#include "advanced_notification_service.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "notification_helper.h" +#include "mock_bundle_manager.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +// static OHOS::sptr bundleObject = nullptr; +static sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + +class AnsInterfaceModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + + +void AnsInterfaceModuleTest::SetUpTestCase() +{ + sptr service = OHOS::Notification::AdvancedNotificationService::GetInstance(); + OHOS::ISystemAbilityManager::SAExtraProp saExtraProp; + systemAbilityManager->AddSystemAbility(OHOS::ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, service, saExtraProp); + + // bundleObject = new OHOS::AppExecFwk::MockBundleMgrService(); + // systemAbilityManager->AddSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject, saExtraProp); +} + +void AnsInterfaceModuleTest::TearDownTestCase() +{} + +void AnsInterfaceModuleTest::SetUp() +{} + +void AnsInterfaceModuleTest::TearDown() +{} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlot_00100 + * @tc.name : + * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), get notification slot and remove notification slot. + * @tc.expected : Add notification slot success, get notification slot correctly and remove notification slot success. + */ +HWTEST_F(AnsInterfaceModuleTest, ANS_Interface_MT_NotificationSlot_00100, Function | MediumTest | Level1) +{ + // bundleObject->MockSetIsSystemApp(false); + NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); + slot.SetEnableLight(true); + slot.SetDescription("description"); + slot.SetLedLightColor(0); + slot.SetLevel(NotificationSlot::NotificationLevel::LEVEL_LOW); + slot.SetSlotGroup("group"); + slot.SetSound(Uri(".")); + std::vector style; + style.push_back(0); + slot.SetVibrationStyle(style); + slot.EnableBypassDnd(true); + slot.EnableBadge(true); + std::cout<<"begain addd slot dump slot information:"< spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::SOCIAL_COMMUNICATION, spSlot)); + + if (spSlot == nullptr) { + std::cout<<"get slot is empty"<Dump()<CanEnableLight()); + EXPECT_EQ(true, spSlot->CanVibrate()); + EXPECT_EQ("description", spSlot->GetDescription()); + EXPECT_EQ("SOCIAL_COMMUNICATION", spSlot->GetId()); + EXPECT_EQ(0, spSlot->GetLedLightColor()); + EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_LOW, spSlot->GetLevel()); + EXPECT_EQ(NotificationConstant::SOCIAL_COMMUNICATION, spSlot->GetType()); + EXPECT_EQ(NotificationConstant::VisiblenessType::PUBLIC, spSlot->GetLockScreenVisibleness()); + EXPECT_EQ("SOCIAL_COMMUNICATION", spSlot->GetName()); + EXPECT_EQ("group", spSlot->GetSlotGroup()); + EXPECT_EQ(Uri("."), spSlot->GetSound()); + for (auto it: spSlot->GetVibrationStyle()) { + EXPECT_EQ(0, it); + } + EXPECT_EQ(Uri("."), spSlot->GetSound()); + EXPECT_EQ(true, spSlot->IsEnableBypassDnd()); + EXPECT_EQ(true, spSlot->IsShowBadge()); + } + EXPECT_EQ(0, NotificationHelper::RemoveNotificationSlot(NotificationConstant::SOCIAL_COMMUNICATION)); + EXPECT_EQ((int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST, + NotificationHelper::GetNotificationSlot(NotificationConstant::SOCIAL_COMMUNICATION,spSlot)); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlot_00200 + * @tc.name : + * @tc.desc : Add notification slot(type is SERVICE_REMINDER), get notification slot and remove notification slot. + * @tc.expected : Add notification slot success, get notification slot correctly and remove notification slot success. + */ +HWTEST_F(AnsInterfaceModuleTest, ANS_Interface_MT_NotificationSlot_00200, Function | MediumTest | Level1) +{ + // bundleObject->MockSetIsSystemApp(false); + NotificationSlot slot(NotificationConstant::SERVICE_REMINDER); + slot.SetEnableLight(true); + slot.SetDescription("description"); + slot.SetLedLightColor(0); + slot.SetLevel(NotificationSlot::NotificationLevel::LEVEL_LOW); + slot.SetSlotGroup("group"); + slot.SetSound(Uri(".")); + std::vector style; + style.push_back(0); + slot.SetVibrationStyle(style); + slot.EnableBypassDnd(true); + slot.EnableBadge(true); + std::cout<<"begain addd slot dump slot information:"< spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::SERVICE_REMINDER, spSlot)); + + if (spSlot == nullptr) { + std::cout<<"get slot is empty"<Dump()<CanEnableLight()); + EXPECT_EQ(true, spSlot->CanVibrate()); + EXPECT_EQ("description", spSlot->GetDescription()); + EXPECT_EQ("SERVICE_REMINDER", spSlot->GetId()); + EXPECT_EQ(0, spSlot->GetLedLightColor()); + EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_LOW, spSlot->GetLevel()); + EXPECT_EQ(NotificationConstant::SERVICE_REMINDER, spSlot->GetType()); + EXPECT_EQ(NotificationConstant::VisiblenessType::PUBLIC, spSlot->GetLockScreenVisibleness()); + EXPECT_EQ("SERVICE_REMINDER", spSlot->GetName()); + EXPECT_EQ("group", spSlot->GetSlotGroup()); + EXPECT_EQ(Uri("."), spSlot->GetSound()); + for (auto it: spSlot->GetVibrationStyle()) { + EXPECT_EQ(0, it); + } + EXPECT_EQ(Uri("."), spSlot->GetSound()); + EXPECT_EQ(true, spSlot->IsEnableBypassDnd()); + EXPECT_EQ(true, spSlot->IsShowBadge()); + } + EXPECT_EQ(0, NotificationHelper::RemoveNotificationSlot(NotificationConstant::SERVICE_REMINDER)); + EXPECT_EQ((int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST, + NotificationHelper::GetNotificationSlot(NotificationConstant::SERVICE_REMINDER,spSlot)); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlot_00300 + * @tc.name : + * @tc.desc : Add notification slot(type is CONTENT_INFORMATION), get notification slot and remove notification slot. + * @tc.expected : Add notification slot success, get notification slot correctly and remove notification slot success. + */ +HWTEST_F(AnsInterfaceModuleTest, ANS_Interface_MT_NotificationSlot_00300, Function | MediumTest | Level1) +{ + // bundleObject->MockSetIsSystemApp(false); + NotificationSlot slot(NotificationConstant::CONTENT_INFORMATION); + slot.SetEnableLight(true); + slot.SetDescription("description"); + slot.SetLedLightColor(0); + slot.SetLevel(NotificationSlot::NotificationLevel::LEVEL_LOW); + slot.SetSlotGroup("group"); + slot.SetSound(Uri(".")); + std::vector style; + style.push_back(0); + slot.SetVibrationStyle(style); + slot.EnableBypassDnd(true); + slot.EnableBadge(true); + std::cout<<"begain addd slot dump slot information:"< spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::CONTENT_INFORMATION, spSlot)); + + if (spSlot == nullptr) { + std::cout<<"get slot is empty"<Dump()<CanEnableLight()); + EXPECT_EQ(true, spSlot->CanVibrate()); + EXPECT_EQ("description", spSlot->GetDescription()); + EXPECT_EQ("CONTENT_INFORMATION", spSlot->GetId()); + EXPECT_EQ(0, spSlot->GetLedLightColor()); + EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_LOW, spSlot->GetLevel()); + EXPECT_EQ(NotificationConstant::CONTENT_INFORMATION, spSlot->GetType()); + EXPECT_EQ(NotificationConstant::VisiblenessType::SECRET, spSlot->GetLockScreenVisibleness()); + EXPECT_EQ("CONTENT_INFORMATION", spSlot->GetName()); + EXPECT_EQ("group", spSlot->GetSlotGroup()); + EXPECT_EQ(Uri("."), spSlot->GetSound()); + for (auto it: spSlot->GetVibrationStyle()) { + EXPECT_EQ(0, it); + } + EXPECT_EQ(Uri("."), spSlot->GetSound()); + EXPECT_EQ(true, spSlot->IsEnableBypassDnd()); + EXPECT_EQ(true, spSlot->IsShowBadge()); + } + EXPECT_EQ(0, NotificationHelper::RemoveNotificationSlot(NotificationConstant::CONTENT_INFORMATION)); + EXPECT_EQ((int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST, + NotificationHelper::GetNotificationSlot(NotificationConstant::CONTENT_INFORMATION,spSlot)); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlot_00400 + * @tc.name : + * @tc.desc : Add notification slot(type is OTHER), get notification slot and remove notification slot. + * @tc.expected : Add notification slot success, get notification slot correctly and remove notification slot success. + */ +HWTEST_F(AnsInterfaceModuleTest, ANS_Interface_MT_NotificationSlot_00400, Function | MediumTest | Level1) +{ + // bundleObject->MockSetIsSystemApp(false); + NotificationSlot slot(NotificationConstant::OTHER); + slot.SetEnableLight(true); + slot.SetDescription("description"); + slot.SetLedLightColor(0); + slot.SetLevel(NotificationSlot::NotificationLevel::LEVEL_LOW); + slot.SetSlotGroup("group"); + slot.SetSound(Uri(".")); + std::vector style; + style.push_back(0); + slot.SetVibrationStyle(style); + slot.EnableBypassDnd(true); + slot.EnableBadge(true); + std::cout<<"begain addd slot dump slot information:"< spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::OTHER, spSlot)); + + if (spSlot == nullptr) { + std::cout<<"get slot is empty"<Dump()<CanEnableLight()); + EXPECT_EQ(true, spSlot->CanVibrate()); + EXPECT_EQ("description", spSlot->GetDescription()); + EXPECT_EQ("OTHER", spSlot->GetId()); + EXPECT_EQ(0, spSlot->GetLedLightColor()); + EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_LOW, spSlot->GetLevel()); + EXPECT_EQ(NotificationConstant::OTHER, spSlot->GetType()); + EXPECT_EQ(NotificationConstant::VisiblenessType::SECRET, spSlot->GetLockScreenVisibleness()); + EXPECT_EQ("OTHER", spSlot->GetName()); + EXPECT_EQ("group", spSlot->GetSlotGroup()); + EXPECT_EQ(Uri("."), spSlot->GetSound()); + for (auto it: spSlot->GetVibrationStyle()) { + EXPECT_EQ(0, it); + } + EXPECT_EQ(Uri("."), spSlot->GetSound()); + EXPECT_EQ(true, spSlot->IsEnableBypassDnd()); + EXPECT_EQ(true, spSlot->IsShowBadge()); + } + EXPECT_EQ(0, NotificationHelper::RemoveNotificationSlot(NotificationConstant::OTHER)); + EXPECT_EQ((int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST, + NotificationHelper::GetNotificationSlot(NotificationConstant::OTHER,spSlot)); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlot_00500 + * @tc.name : + * @tc.desc : Add notification slot(type is CUSTOM), get notification slot and remove notification slot. + * @tc.expected : Add notification slot success, get notification slot correctly and remove notification slot success. + */ +HWTEST_F(AnsInterfaceModuleTest, ANS_Interface_MT_NotificationSlot_00500, Function | MediumTest | Level1) +{ + // bundleObject->MockSetIsSystemApp(false); + NotificationSlot slot(NotificationConstant::CUSTOM); + slot.SetEnableLight(true); + slot.SetDescription("description"); + slot.SetLedLightColor(0); + slot.SetLevel(NotificationSlot::NotificationLevel::LEVEL_LOW); + slot.SetSlotGroup("group"); + slot.SetSound(Uri(".")); + std::vector style; + style.push_back(0); + slot.SetVibrationStyle(style); + slot.EnableBypassDnd(true); + slot.EnableBadge(true); + std::cout<<"begain addd slot dump slot information:"< spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::CUSTOM, spSlot)); + + if (spSlot == nullptr) { + std::cout<<"get slot is empty"<Dump()<CanEnableLight()); + EXPECT_EQ(true, spSlot->CanVibrate()); + EXPECT_EQ("description", spSlot->GetDescription()); + EXPECT_EQ("", spSlot->GetId()); + EXPECT_EQ(0, spSlot->GetLedLightColor()); + EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_LOW, spSlot->GetLevel()); + EXPECT_EQ(NotificationConstant::CUSTOM, spSlot->GetType()); + EXPECT_EQ(NotificationConstant::VisiblenessType::NO_OVERRIDE, spSlot->GetLockScreenVisibleness()); + EXPECT_EQ("", spSlot->GetName()); + EXPECT_EQ("group", spSlot->GetSlotGroup()); + EXPECT_EQ(Uri("."), spSlot->GetSound()); + for (auto it: spSlot->GetVibrationStyle()) { + EXPECT_EQ(0, it); + } + EXPECT_EQ(Uri("."), spSlot->GetSound()); + EXPECT_EQ(true, spSlot->IsEnableBypassDnd()); + EXPECT_EQ(true, spSlot->IsShowBadge()); + } + EXPECT_EQ(0, NotificationHelper::RemoveNotificationSlot(NotificationConstant::CUSTOM)); + EXPECT_EQ((int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST, + NotificationHelper::GetNotificationSlot(NotificationConstant::CUSTOM,spSlot)); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/mock/blob.cpp b/frameworks/ans/test/moduletest/mock/blob.cpp new file mode 100644 index 000000000..93d2c3470 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/blob.cpp @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "Blob" + +#include "blob.h" +#include +#include "log_print.h" + +namespace OHOS { +namespace DistributedKv { +Blob::Blob() { } + +Blob::Blob(const Blob &blob) +{ + blob_ = blob.Data(); +} + +Blob::Blob(Blob &&blob) +{ + blob_.swap(blob.blob_); +} + +Blob &Blob::operator=(const Blob &blob) +{ + // Self-assignment detection + if (&blob == this) { + return *this; + } + + blob_ = blob.Data(); + + return *this; +} + +Blob &Blob::operator=(Blob &&blob) +{ + // Self-assignment detection + if (&blob == this) { + return *this; + } + + blob_.swap(blob.blob_); + + return *this; +} + +Blob::Blob(const char *str, size_t n) + : blob_() +{ + if (str != nullptr) { + blob_ = std::vector(str, str + n); + } +} + +Blob::Blob(const std::string &str) + : blob_(str.begin(), str.end()) +{ +} + +Blob::Blob(const char *str) + : blob_() +{ + if (str != nullptr) { + blob_ = std::vector(str, str + strlen(str)); + } +} + +Blob::Blob(const std::vector &bytes) + : blob_(bytes) +{ +} + +Blob::Blob(std::vector &&bytes) + : blob_(std::move(bytes)) +{ +} + +const std::vector &Blob::Data() const +{ + return blob_; +} + +size_t Blob::Size() const +{ + return blob_.size(); +} + +int Blob::RawSize() const +{ + return sizeof(int) + blob_.size(); +} + +bool Blob::Empty() const +{ + return blob_.empty(); +} + +uint8_t Blob::operator[](size_t n) const +{ + if (n >= Size()) { + ZLOGE("Trying to get a out-of-range Blob member."); + return 0; + } + return blob_[n]; +} + +bool Blob::operator==(const Blob &blob) const +{ + return blob_ == blob.blob_; +} + +void Blob::Clear() +{ + blob_.clear(); +} + +std::string Blob::ToString() const +{ + std::string str(blob_.begin(), blob_.end()); + return str; +} + +int Blob::Compare(const Blob &blob) const +{ + if (blob_ < blob.blob_) { + return -1; + } + if (blob_ == blob.blob_) { + return 0; + } + return 1; +} + +bool Blob::StartsWith(const Blob &blob) const +{ + size_t len = blob.Size(); + if (Size() < len) { + return false; + } + + for (size_t i = 0; i < len; ++i) { + if (blob_[i] != blob.blob_[i]) { + return false; + } + } + return true; +} + +bool Blob::Marshalling(Parcel &parcel) const +{ + return parcel.WriteUInt8Vector(this->blob_); +} + +Blob *Blob::Unmarshalling(Parcel &parcel) +{ + std::vector blobData; + if (!parcel.ReadUInt8Vector(&blobData)) { + return nullptr; + } + return new Blob(blobData); +} + +/* write blob size and data to memory buffer. return error when bufferLeftSize not enough. */ +bool Blob::WriteToBuffer(uint8_t *&cursorPtr, int &bufferLeftSize) const +{ + if (cursorPtr == nullptr || bufferLeftSize < static_cast(blob_.size() + sizeof(int))) { + return false; + } + *reinterpret_cast(cursorPtr) = static_cast(blob_.size()); + bufferLeftSize -= sizeof(int32_t); + cursorPtr += sizeof(int32_t); + errno_t err = memcpy_s(cursorPtr, bufferLeftSize, blob_.data(), blob_.size()); + if (err != EOK) { + return false; + } + cursorPtr += blob_.size(); + bufferLeftSize -= blob_.size(); + return true; +} + +/* read a blob from memory buffer. */ +bool Blob::ReadFromBuffer(const uint8_t *&cursorPtr, int &bufferLeftSize) +{ + if (cursorPtr == nullptr || bufferLeftSize < static_cast(sizeof(int))) { + return false; + } + int blobSize = *reinterpret_cast(cursorPtr); + bufferLeftSize -= sizeof(int) + blobSize; + if (blobSize < 0 || bufferLeftSize < 0) { + return false; + } + cursorPtr += sizeof(int); + blob_ = std::vector(cursorPtr, cursorPtr + blobSize); + cursorPtr += blobSize; + return true; +} +} // namespace DistributedKv +} // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp b/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp new file mode 100644 index 000000000..656932c20 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "DistributedKvDataManager" + +#include "distributed_kv_data_manager.h" +#include "constant.h" +//#include "ikvstore.h" +#include "mock_single_kv_store.h" +#include "types.h" + +namespace OHOS { +namespace DistributedKv { +DistributedKvDataManager::DistributedKvDataManager() +{} + +DistributedKvDataManager::~DistributedKvDataManager() +{} + +void DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, + std::function)> callback) +{ + std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); + Status status = Status::SUCCESS; + std::unique_ptr proxyTmp = std::make_unique(); + callback(status, std::move(proxyTmp)); +} + +Status DistributedKvDataManager::CloseKvStore( + const AppId &appId, const StoreId &storeId, std::unique_ptr kvStorePtr) +{ + return Status::SUCCESS; +} + +Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::unique_ptr kvStorePtr) +{ + return Status::SUCCESS; +} + +Status DistributedKvDataManager::DeleteKvStore(const AppId &appId, const StoreId &storeId) +{ + return Status::SUCCESS; +} + +void DistributedKvDataManager::RegisterKvStoreServiceDeathRecipient( + std::shared_ptr kvStoreDeathRecipient) +{} + +void DistributedKvDataManager::UnRegisterKvStoreServiceDeathRecipient( + std::shared_ptr kvStoreDeathRecipient) +{} +} // namespace DistributedKv +} // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h index 960b2aa7b..de0de2d65 100644 --- a/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h +++ b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h @@ -95,6 +95,16 @@ public: { return 0; } + /** + * @brief Obtains the application ID based on the given bundle name and user ID. + * @param bundleName Indicates the bundle name of the application. + * @param userId Indicates the user ID. + * @return Returns the application ID if successfully obtained; returns empty string otherwise. + */ + virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override + { + return "bundlename"; + } /** * @brief Obtains the bundle name of a specified application based on the given UID. * @param uid Indicates the uid. @@ -106,6 +116,26 @@ public: bundleName = "hello"; return true; } + /** + * @brief Obtains all bundle names of a specified application based on the given application UID. + * @param uid Indicates the uid. + * @param bundleNames Indicates the obtained bundle names. + * @return Returns true if the bundle names is successfully obtained; returns false otherwise. + */ + virtual bool GetBundlesForUid(const int uid, std::vector &bundleNames) override + { + return true; + } + + /* @brief Obtains the formal name associated with the given UID. + * @param uid Indicates the uid. + * @param name Indicates the obtained formal name. + * @return Returns true if the formal name is successfully obtained; returns false otherwise. + */ + virtual bool GetNameForUid(const int uid, std::string &name) override + { + return true; + } /** * @brief Obtains an array of all group IDs associated with a specified bundle. * @param bundleName Indicates the bundle name. @@ -289,6 +319,70 @@ public: { return true; } + /** + * @brief Registers a callback for listening for permission changes of all UIDs. + * @param callback Indicates the callback method to register. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool RegisterAllPermissionsChanged(const sptr &callback) override + { + return true; + } + /** + * @brief Registers a callback for listening for permission changes of specified UIDs. + * @param uids Indicates the list of UIDs whose permission changes will be monitored. + * @param callback Indicates the callback method to register. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool RegisterPermissionsChanged( + const std::vector &uids, const sptr &callback) override + { + return true; + } + /** + * @brief Unregisters a specified callback for listening for permission changes. + * @param callback Indicates the callback method to register. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool UnregisterPermissionsChanged(const sptr &callback) override + { + return true; + } + /** + * @brief Obtains the FormInfo objects provided by all applications on the device. + * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the + * device. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetAllFormsInfo(std::vector &formInfos) override + { + return true; + } + /** + * @brief Obtains the FormInfo objects provided by a specified application on the device. + * @param bundleName Indicates the bundle name of the application. + * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the + * device. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfos) override + { + return true; + } + + /** + * @brief Obtains the FormInfo objects provided by a specified. + * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the + * device. + * @param moduleName Indicates the module name of the application. + * @param bundleName Indicates the bundle name of the application. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetFormsInfoByModule( + const std::string &bundleName, const std::string &moduleName, std::vector &formInfos) override + { + return true; + } /** * @brief Checks whether the system has a specified capability. * @param capName Indicates the name of the system feature to check. @@ -392,6 +486,36 @@ public: { return true; } + /** + * @brief Sets whether to enable a specified ability. + * @param abilityInfo Indicates information about the ability to check. + * @return Returns true if the ability is enabled; returns false otherwise. + */ + virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) override + { + return true; + } + /** + * @brief Obtains the icon of a specified ability. + * @param bundleName Indicates the bundle name. + * @param className Indicates the ability class name. + * @return Returns the icon resource string of the ability if exist; returns empty string otherwise. + */ + virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override + { + return "abilityicon"; + } + /** + * @brief Sets whether to enable a specified ability. + * @param abilityInfo Indicates information about the ability. + * @param isEnabled Specifies whether to enable the ability. + * The value true means to enable it, and the value false means to disable it. + * @return Returns true if the ability is enabled; returns false otherwise. + */ + virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) override + { + return true; + } /** * @brief Obtains the interface used to install and uninstall bundles. * @return Returns a pointer to IBundleInstaller class if exist; returns nullptr otherwise. @@ -403,6 +527,11 @@ public: void MockSetIsSystemApp(bool isSystemApp); + std::string GetBundleNameByUid(pid_t uid) + { + return "bundle"; + } + private: bool isSystemApp_ = false; bool isSystemAppMock_ = false; diff --git a/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h b/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h new file mode 100644 index 000000000..8a777ea02 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANS_MOCK_SINGLE_KV_STORE_H +#define ANS_MOCK_SINGLE_KV_STORE_H + +#include +#include + +#include "kvstore.h" +#include "kvstore_observer.h" +#include "kvstore_result_set.h" +#include "kvstore_sync_callback.h" +#include "types.h" +#include "data_query.h" +#include "single_kvstore.h" + +namespace OHOS { +namespace DistributedKv { +// This is a public interface. Implementation of this class is in AppKvStoreImpl. +// This class provides put, delete, search, sync and subscribe functions of a key-value store. +class AnsTestSingleKvStore : public SingleKvStore { +public: + + // Get all entries in this store which key start with prefixKey. + // Parameters: + // perfixkey: the prefix to be searched. + // entries: entries will be returned in this parameter. + // Return: + // Status of this GetEntries operation. + virtual Status GetEntries(const Key &prefixKey, std::vector &entries) const override; + + // Get all entries in this store by query. + // Parameters: + // query: the query string. + // entries: entries will be returned in this parameter. + // Return: + // Status of this GetEntries operation. + virtual Status GetEntriesWithQuery(const std::string &query, std::vector &entries) const override; + + // Get all entries in this store by query. + // Parameters: + // query: the query object. + // entries: entries will be returned in this parameter. + // Return: + // Status of this GetEntries operation. + virtual Status GetEntriesWithQuery(const DataQuery &query, std::vector &entries) const override; + + // Get ResultSet in this store which key start with prefixKey. + // Parameters: + // perfixkey: the prefix to be searched. + // resultSet: resultSet will be returned in this parameter. + // Return: + // Status of this GetResultSet operation. + virtual void GetResultSet(const Key &prefixKey, + std::function)> callback) const override; + + // Get ResultSet in this store by Query. + // Parameters: + // query: the query string. + // resultSet: resultSet will be returned in this parameter. + // Return: + // Status of this GetResultSet operation. + virtual void GetResultSetWithQuery(const std::string &query, + std::function)> callback) const override; + + // Get ResultSet in this store by Query. + // Parameters: + // query: the query object. + // resultSet: resultSet will be returned in this parameter. + // Return: + // Status of this GetResultSet operation. + virtual void GetResultSetWithQuery(const DataQuery &query, + std::function)> callback) const override; + + // Close the ResultSet returned by GetResultSet. + // Parameters: + // resultSet: resultSet will be returned in this parameter. + // Return: + // Status of this CloseResultSet operation. + virtual Status CloseResultSet(std::unique_ptr resultSet) override; + + // Get the number of result by query. + // Parameters: + // query: the query string. + // result: result will be returned in this parameter. + // Return: + // Status of this CloseResultSet operation. + virtual Status GetCountWithQuery(const std::string &query, int &result) const override; + + // Get the number of result by query. + // Parameters: + // query: the query object. + // result: result will be returned in this parameter. + // Return: + // Status of this CloseResultSet operation. + virtual Status GetCountWithQuery(const DataQuery &query, int &result) const override; + + // Sync store with other devices. This is an asynchronous method, + // sync will fail if there is a syncing operation in progress. + // Parameters: + // deviceIdList: device list to sync. + // mode: mode can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. PUSH_PULL will firstly + // push all not-local store to listed devices, then pull these stores back. + // allowedDelayMs: allowed delay milli-second to sync. default value is 0 for compatibility. + // Return: + // Status of this Sync operation. + virtual Status Sync(const std::vector &deviceIdList, const SyncMode &mode, + uint32_t allowedDelayMs = 0) override; + + // Remove the device data synced from remote. + // Parameters: + // device: device id. + // Return: + // Status of this remove operation. + virtual Status RemoveDeviceData(const std::string &device) override; + + // Get id of this SingleKvStore. + virtual StoreId GetStoreId() const override; + + // Delete an entry by its key. + // Parameters: + // key: key of the entry to be deleted. + // Return: + // Status of this delete operation. + virtual Status Delete(const Key &key) override; + + // Write a pair of key and value to this store. + // Parameters: + // key: key of this entry. Should be less than 1024 bytes. key will be trimmed before store. + // value: value of this entry. Should be less than (4 * 1024 * 1024) bytes. + // Return: + // Status of this put operation. + virtual Status Put(const Key &key, const Value &value) override; + + // Get value from AppKvStore by its key. + // Parameters: + // key: key of this entry. + // value: value will be returned in this parameter. + // Return: + // Status of this get operation. + virtual Status Get(const Key &key, Value &value) override; + + // subscribe change of this kvstore to a client-defined observer. observer->OnChange method will be called when store + // changes. + // Parameters: + // subscribeType: SUBSCRIBE_TYPE_LOCAL means local changes of syncable kv store, + // : SUBSCRIBE_TYPE_REMOTE means synced data changes from remote devices, + // : SUBSCRIBE_TYPE_ALL means both local changes and synced data changes. + // observer: observer to subscribe changes. + // Return: + // Status of this subscribe operation. + virtual Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + + // un-subscribe change of this kvstore to a client-defined observer. + // Parameters: + // subscribeType: SUBSCRIBE_TYPE_LOCAL means local changes of syncable kv store, + // : SUBSCRIBE_TYPE_REMOTE means synced data changes from remote devices, + // : SUBSCRIBE_TYPE_ALL means both local changes and synced data changes. + // observer: observer to subscribe changes. + // Return: + // Status of this subscribe operation. + virtual Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + + // register message for sync operation. + // Parameters: + // callback: callback to register. + // Return: + // Status of this register operation. + virtual Status RegisterSyncCallback(std::shared_ptr callback) override; + + // un-register message for sync operation. + // Parameters: + // callback: callback to register. + // Return: + // Status of this register operation. + virtual Status UnRegisterSyncCallback() override; + + // see Put, PutBatch put a list of entries to kvstore, + // all entries will be put in a transaction, + // if entries contains invalid entry, PutBatch will all fail. + // entries's size should be less than 128 and memory size must be less than IPC transport limit. + virtual Status PutBatch(const std::vector &entries) override; + + // delete a list of entries in the kvstore, + // delete key not exist still return success, + // key length should not be greater than 256, and can not be empty. + // if keys contains invalid key, all delete will fail. + // keys memory size should not be greater than IPC transport limit, and can not be empty. + virtual Status DeleteBatch(const std::vector &keys) override; + + // start transaction. + // all changes to this kvstore will be in a same transaction and will not change the store until Commit() or + // Rollback() is called. + // before this transaction is committed or rollbacked, all attemption to close this store will fail. + virtual Status StartTransaction() override; + + // commit current transaction. all changes to this store will be done after calling this method. + // any calling of this method outside a transaction will fail. + virtual Status Commit() override; + + // rollback current transaction. + // all changes to this store during this transaction will be rollback after calling this method. + // any calling of this method outside a transaction will fail. + virtual Status Rollback() override; + + // set synchronization parameters of this store. + // Parameters: + // syncParam: sync policy parameter. + // Return: + // Status of this operation. + virtual Status SetSyncParam(const KvSyncParam &syncParam) override; + + // get synchronization parameters of this store. + // Parameters: + // syncParam: sync policy parameter. + // Return: + // Status of this operation. + virtual Status GetSyncParam(KvSyncParam &syncParam) override; + + virtual Status SetCapabilityEnabled(bool enabled) const override; + + virtual Status SetCapabilityRange(const std::vector &localLabels, + const std::vector &remoteSupportLabels) const override; + + virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const override; +protected: + // control this store. + // Parameters: + // inputParam: input parameter. + // output: output data, nullptr if no data is returned. + // Return: + // Status of this control operation. + KVSTORE_API virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, sptr &output) override; +}; +} // namespace AppDistributedKv +} // namespace OHOS +#endif // SINGLE_KV_STORE_H diff --git a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp new file mode 100644 index 000000000..4b580d297 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mock_single_kv_store.h" +#include "types.h" + +namespace OHOS { +namespace DistributedKv { +// Get all entries in this store which key start with prefixKey. +// Parameters: +// perfixkey: the prefix to be searched. +// entries: entries will be returned in this parameter. +// Return: +// Status of this GetEntries operation. +Status AnsTestSingleKvStore::GetEntries(const Key &prefixKey, std::vector &entries) const +{ + return Status::SUCCESS; +} + +// Get all entries in this store by query. +// Parameters: +// query: the query string. +// entries: entries will be returned in this parameter. +// Return: +// Status of this GetEntries operation. +Status AnsTestSingleKvStore::GetEntriesWithQuery(const std::string &query, std::vector &entries) const +{ + return Status::SUCCESS; +} + +// Get all entries in this store by query. +// Parameters: +// query: the query object. +// entries: entries will be returned in this parameter. +// Return: +// Status of this GetEntries operation. +Status AnsTestSingleKvStore::GetEntriesWithQuery(const DataQuery &query, std::vector &entries) const +{ + return Status::SUCCESS; +} + +// Get ResultSet in this store which key start with prefixKey. +// Parameters: +// perfixkey: the prefix to be searched. +// resultSet: resultSet will be returned in this parameter. +// Return: +// Status of this GetResultSet operation. +void AnsTestSingleKvStore::GetResultSet(const Key &prefixKey, + std::function)> callback) const +{ + +} + +// Get ResultSet in this store by Query. +// Parameters: +// query: the query string. +// resultSet: resultSet will be returned in this parameter. +// Return: +// Status of this GetResultSet operation. +void AnsTestSingleKvStore::GetResultSetWithQuery(const std::string &query, + std::function)> callback) const +{ + +} + +// Get ResultSet in this store by Query. +// Parameters: +// query: the query object. +// resultSet: resultSet will be returned in this parameter. +// Return: +// Status of this GetResultSet operation. +void AnsTestSingleKvStore::GetResultSetWithQuery(const DataQuery &query, + std::function)> callback) const +{ + +} + +// Close the ResultSet returned by GetResultSet. +// Parameters: +// resultSet: resultSet will be returned in this parameter. +// Return: +// Status of this CloseResultSet operation. +Status AnsTestSingleKvStore::CloseResultSet(std::unique_ptr resultSet) +{ + return Status::SUCCESS; +} + +// Get the number of result by query. +// Parameters: +// query: the query string. +// result: result will be returned in this parameter. +// Return: +// Status of this CloseResultSet operation. +Status AnsTestSingleKvStore::GetCountWithQuery(const std::string &query, int &result) const +{ + return Status::SUCCESS; +} + +// Get the number of result by query. +// Parameters: +// query: the query object. +// result: result will be returned in this parameter. +// Return: +// Status of this CloseResultSet operation. +Status AnsTestSingleKvStore::GetCountWithQuery(const DataQuery &query, int &result) const +{ + return Status::SUCCESS; +} + +// Sync store with other devices. This is an asynchronous method, +// sync will fail if there is a syncing operation in progress. +// Parameters: +// deviceIdList: device list to sync. +// mode: mode can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. PUSH_PULL will firstly +// push all not-local store to listed devices, then pull these stores back. +// allowedDelayMs: allowed delay milli-second to sync. default value is 0 for compatibility. +// Return: +// Status of this Sync operation. +Status AnsTestSingleKvStore::Sync(const std::vector &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs) +{ + return Status::SUCCESS; +} + +// Remove the device data synced from remote. +// Parameters: +// device: device id. +// Return: +// Status of this remove operation. +Status AnsTestSingleKvStore::RemoveDeviceData(const std::string &device) +{ + return Status::SUCCESS; +} + +// Get id of this SingleKvStore. +StoreId AnsTestSingleKvStore::GetStoreId() const +{ + StoreId storeId; + storeId.storeId = ""; + return storeId; +} + +// Delete an entry by its key. +// Parameters: +// key: key of the entry to be deleted. +// Return: +// Status of this delete operation. +Status AnsTestSingleKvStore::Delete(const Key &key) +{ + return Status::SUCCESS; +} + +// Write a pair of key and value to this store. +// Parameters: +// key: key of this entry. Should be less than 1024 bytes. key will be trimmed before store. +// value: value of this entry. Should be less than (4 * 1024 * 1024) bytes. +// Return: +// Status of this put operation. +Status AnsTestSingleKvStore::Put(const Key &key, const Value &value) +{ + return Status::SUCCESS; +} + +// Get value from AppKvStore by its key. +// Parameters: +// key: key of this entry. +// value: value will be returned in this parameter. +// Return: +// Status of this get operation. +Status AnsTestSingleKvStore::Get(const Key &key, Value &value) +{ + return Status::SUCCESS; +} + +// subscribe change of this kvstore to a client-defined observer. observer->OnChange method will be called when store +// changes. +// Parameters: +// subscribeType: SUBSCRIBE_TYPE_LOCAL means local changes of syncable kv store, +// : SUBSCRIBE_TYPE_REMOTE means synced data changes from remote devices, +// : SUBSCRIBE_TYPE_ALL means both local changes and synced data changes. +// observer: observer to subscribe changes. +// Return: +// Status of this subscribe operation. +Status AnsTestSingleKvStore::SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) +{ + return Status::SUCCESS; +} + +// un-subscribe change of this kvstore to a client-defined observer. +// Parameters: +// subscribeType: SUBSCRIBE_TYPE_LOCAL means local changes of syncable kv store, +// : SUBSCRIBE_TYPE_REMOTE means synced data changes from remote devices, +// : SUBSCRIBE_TYPE_ALL means both local changes and synced data changes. +// observer: observer to subscribe changes. +// Return: +// Status of this subscribe operation. +Status AnsTestSingleKvStore::UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) +{ + return Status::SUCCESS; +} + +// register message for sync operation. +// Parameters: +// callback: callback to register. +// Return: +// Status of this register operation. +Status AnsTestSingleKvStore::RegisterSyncCallback(std::shared_ptr callback) +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::UnRegisterSyncCallback() +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::PutBatch(const std::vector &entries) +{ + return Status::SUCCESS; +} + + +// delete a list of entries in the kvstore, +// delete key not exist still return success, +// key length should not be greater than 256, and can not be empty. +// if keys contains invalid key, all delete will fail. +// keys memory size should not be greater than IPC transport limit, and can not be empty. +Status AnsTestSingleKvStore::DeleteBatch(const std::vector &keys) +{ + return Status::SUCCESS; +} + +// start transaction. +// all changes to this kvstore will be in a same transaction and will not change the store until Commit() or +// Rollback() is called. +// before this transaction is committed or rollbacked, all attemption to close this store will fail. +Status AnsTestSingleKvStore::StartTransaction() +{ + return Status::SUCCESS; +} + +// commit current transaction. all changes to this store will be done after calling this method. +// any calling of this method outside a transaction will fail. +Status AnsTestSingleKvStore::Commit() +{ + return Status::SUCCESS; +} + +// rollback current transaction. +// all changes to this store during this transaction will be rollback after calling this method. +// any calling of this method outside a transaction will fail. +Status AnsTestSingleKvStore::Rollback() +{ + return Status::SUCCESS; +} + +// set synchronization parameters of this store. +// Parameters: +// syncParam: sync policy parameter. +// Return: +// Status of this operation. +Status AnsTestSingleKvStore::SetSyncParam(const KvSyncParam &syncParam) +{ + return Status::SUCCESS; +} + +// get synchronization parameters of this store. +// Parameters: +// syncParam: sync policy parameter. +// Return: +// Status of this operation. +Status AnsTestSingleKvStore::GetSyncParam(KvSyncParam &syncParam) +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::SetCapabilityEnabled(bool enabled) const +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::SetCapabilityRange(const std::vector &localLabels, + const std::vector &remoteSupportLabels) const +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::GetSecurityLevel(SecurityLevel &securityLevel) const +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam, sptr &output) +{ + return Status::SUCCESS; +} + + +} // namespace DistributedKv +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp b/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp index 1fd7b5c73..447dc1b20 100644 --- a/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp +++ b/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp @@ -159,7 +159,7 @@ HWTEST_F(PendingWantTest, PendingWant_0200, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_0300, Function | MediumTest | Level1) { - sptr target(new (std::nothrow) WantSender()); + sptr target = nullptr; PendingWant pendingWant(target); EXPECT_EQ(pendingWant.target_, target); EXPECT_EQ(pendingWant.GetType(target), WantAgentConstant::OperationType::UNKNOWN_TYPE); @@ -462,7 +462,7 @@ HWTEST_F(PendingWantTest, PendingWant_1900, Function | MediumTest | Level1) std::shared_ptr pendingWant = std::make_shared(target); sptr target2(nullptr); std::shared_ptr pendingWant2 = std::make_shared(target2); - EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), true); + EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), false); } /* diff --git a/interfaces/innerkits/ans/native/include/notification.h b/interfaces/innerkits/ans/native/include/notification.h index ab91f6690..881f4cb40 100644 --- a/interfaces/innerkits/ans/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -146,14 +146,14 @@ public: * * @return Return the UID of the notification creator. */ - uid_t GetUid() const; + pid_t GetUid() const; /** * @brief Obtains the PID of the notification creator. * * @return Return the PID of the notification creator. */ - uid_t GetPid() const; + pid_t GetPid() const; /** * @brief Obtains the vibration style for this notifications. if diff --git a/interfaces/innerkits/ans/native/include/notification_action_button.h b/interfaces/innerkits/ans/native/include/notification_action_button.h index adda5ae95..6c931b8dd 100644 --- a/interfaces/innerkits/ans/native/include/notification_action_button.h +++ b/interfaces/innerkits/ans/native/include/notification_action_button.h @@ -39,15 +39,31 @@ public: * @param extras Indicates the PacMap object containing the additional data. * @param semanticActionButton Indicates the semantic action to add. * @param autoCreatedReplies Indicates whether to allow the platform to automatically generate possible replies. + * @param mimeTypeOnlyInputs Indicates the NotificationUserInput object to add which allows only values of + * particular MIME types. * @param userInputs Indicates the NotificationUserInput object to add. + * @param isContextual Indicates whether this NotificationActionButton is a contextual action, that is, whether this + * NotificationActionButton is dependent on the notification message body. * @return the shared_ptr object owns the created NotificationActionButton object otherwise return empty object if - * isContextual is true but icon or wantAgent is dempty. + * isContextual is true but icon or wantAgent is empty. */ static std::shared_ptr Create(const std::shared_ptr &icon, const std::string &title, const std::shared_ptr &wantAgent, - const std::shared_ptr &extras, - NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, - const std::vector> &userInputs, bool isContextual); + const std::shared_ptr &extras = {}, + NotificationConstant::SemanticActionButton semanticActionButton = + NotificationConstant::SemanticActionButton::NONE_ACTION_BUTTON, + bool autoCreatedReplies = true, + const std::vector> &mimeTypeOnlyInputs = {}, + const std::vector> &userInputs = {}, bool isContextual = false); + + /** + * A static function used to create a NotificationActionButton instance by copying parameters from an existing + * NotificationActionButton object. + * @param actionButton Indicates the existing NotificationActionButton object. + * @return the shared_ptr object owns the created NotificationActionButton object otherwise return empty object. + */ + static std::shared_ptr Create( + const std::shared_ptr &actionButton); /** * Default deconstructor used to deconstruct. @@ -98,6 +114,19 @@ public: */ NotificationConstant::SemanticActionButton GetSemanticActionButton() const; + /** + * Adds a NotificationUserInput object that only allows values of particular MIME types. + * @param userInput Indicates the NotificationUserInput object to add. + */ + void AddMimeTypeOnlyUserInput(const std::shared_ptr &userInput); + + /** + * Obtains the NotificationUserInput objects that only allow values of particular MIME types + * when this NotificationActionButton is sent. + * @return the list of NotificationUserInput objects allowing only values of particular MIME types. + */ + std::vector> GetMimeTypeOnlyUserInputs() const; + /** * Adds a NotificationUserInput object used to collect user input. * @param userInput Indicates the NotificationUserInput object to add. @@ -111,13 +140,6 @@ public: */ std::vector> GetUserInputs() const; - /** - * Obtains the NotificationUserInput objects that only allow values of particular MIME types - * when this NotificationActionButton is sent. - * @return the list of NotificationUserInput objects allowing only values of particular MIME types. - */ - std::vector> GetMimeTypeOnlyUserInputs() const; - /** * Sets whether to allow the platform to automatically generate possible replies and add them to * NotificationUserInput::getOptions(). @@ -181,12 +203,15 @@ private: * @param extras Indicates the PacMap object containing the additional data. * @param semanticActionButton Indicates the semantic action to add. * @param autoCreatedReplies Indicates whether to allow the platform to automatically generate possible replies. + * @param mimeTypeOnlyInputs Indicates the NotificationUserInput object to add which allows only values of + * particular MIME types. * @param userInputs Indicates the NotificationUserInput object to add. * @param isContextual Indicates whether this NotificationActionButton is a contextual action. */ NotificationActionButton(const std::shared_ptr &icon, const std::string &title, const std::shared_ptr &wantAgent, const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, + const std::vector> &mimeTypeOnlyInputs, const std::vector> &userInputs, bool isContextual); /** @@ -203,6 +228,7 @@ private: NotificationConstant::SemanticActionButton semanticActionButton_{ NotificationConstant::SemanticActionButton::NONE_ACTION_BUTTON}; bool autoCreatedReplies_{true}; + std::vector> mimeTypeOnlyUserInputs_{}; std::vector> userInputs_{}; bool isContextual_{false}; }; diff --git a/interfaces/innerkits/ans/native/include/notification_bundle_option.h b/interfaces/innerkits/ans/native/include/notification_bundle_option.h new file mode 100644 index 000000000..46d1393de --- /dev/null +++ b/interfaces/innerkits/ans/native/include/notification_bundle_option.h @@ -0,0 +1,100 @@ +/* + * Copyright (c); 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License");; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BUNDLE_OPTION_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BUNDLE_OPTION_H + +#include +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationBundleOption : public Parcelable { +public: + /** + * A default constructor used to create a NotificationBundleOption instance. + */ + NotificationBundleOption() = default; + + /** + * A constructor used to create a NotificationBundleOption instance based on the creator bundle name and uid. + * @param bundleName Indicates the creator bundle name. + * @param uid Indicates the creator uid. + */ + NotificationBundleOption(const std::string &bundleName, const int32_t uid); + + /** + * Default deconstructor used to deconstruct. + */ + virtual ~NotificationBundleOption(); + + /** + * Sets the creator bundle name. + * @param bundleName Indicates the creator bundle name. + */ + void SetBundleName(const std::string &bundleName); + + /** + * Obtains the creator bundle name. + * @return the creator bundle name. + */ + std::string GetBundleName() const; + + /** + * Sets the creator uid. + * @param uid Indicates the creator uid. + */ + void SetUid(const int32_t uid); + + /** + * Obtains the creator uid. + * @return the creator uid. + */ + int32_t GetUid() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationBundleOption + */ + static NotificationBundleOption *Unmarshalling(Parcel &parcel); + +private: + /** + * Read data from a Parcel. + * @param parcel the parcel + * @return true if read success; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + +private: + std::string bundleName_{}; + int32_t uid_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONTENT_H diff --git a/interfaces/innerkits/ans/native/include/notification_constant.h b/interfaces/innerkits/ans/native/include/notification_constant.h index 64bbddccd..42c1d7cf0 100644 --- a/interfaces/innerkits/ans/native/include/notification_constant.h +++ b/interfaces/innerkits/ans/native/include/notification_constant.h @@ -47,17 +47,17 @@ public: }; enum SemanticActionButton { - ARCHIVE_ACTION_BUTTON, // Indicates the action of archiving the content associated with the notification. - CALL_ACTION_BUTTON, // Indicates the action of making a call. - DELETE_ACTION_BUTTON, // Indicates the action of deleting the content associated with the notification. - MUTE_ACTION_BUTTON, // Indicates the action of muting the content associated with the notification. NONE_ACTION_BUTTON, // Indicates that no WantAgent is associated. - READ_ACTION_BUTTON, // Indicates the action of marking the content as read. REPLY_ACTION_BUTTON, // Indicates the action of replying to a conversation. - THUMBS_DOWN_ACTION_BUTTON, // Indicates the action of marking the content with a thumbs-down. - THUMBS_UP_ACTION_BUTTON, // Indicates the action of marking the content with a thumbs-up. - UNMUTE_ACTION_BUTTON, // Indicates the action of unmuting the content associated with the notification. + READ_ACTION_BUTTON, // Indicates the action of marking the content as read. UNREAD_ACTION_BUTTON, // Indicates the action of marking the content as unread. + DELETE_ACTION_BUTTON, // Indicates the action of deleting the content associated with the notification. + ARCHIVE_ACTION_BUTTON, // Indicates the action of archiving the content associated with the notification. + MUTE_ACTION_BUTTON, // Indicates the action of muting the content associated with the notification. + UNMUTE_ACTION_BUTTON, // Indicates the action of unmuting the content associated with the notification. + THUMBS_UP_ACTION_BUTTON, // Indicates the action of marking the content with a thumbs-up. + THUMBS_DOWN_ACTION_BUTTON, // Indicates the action of marking the content with a thumbs-down. + CALL_ACTION_BUTTON, // Indicates the action of making a call. }; enum SubscribeResult : uint32_t { diff --git a/interfaces/innerkits/ans/native/include/notification_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index 236b4a41f..da6498cff 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -41,6 +41,14 @@ public: */ static ErrCode AddNotificationSlot(const NotificationSlot &slot); + /** + * Adds a notification slot by type. + * + * @param slotType Indicates the notification slot type to be added. + * @return Returns add notification slot result. + */ + static ErrCode AddSlotByType(const NotificationConstant::SlotType &slotType); + /** * Creates multiple notification slots. * @@ -58,6 +66,13 @@ public: */ static ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType); + /** + * Deletes all notification slots. + * + * @return Returns remove all slots result. + */ + static ErrCode RemoveAllSlots(); + /** * Queries a created notification slot. * @@ -378,6 +393,29 @@ public: */ static ErrCode RemoveNotification(const std::string &key); + /** + * Removes a specified removable notification of other applications. + * @note Your application must have platform signature to use this method. + * + * @param bundleName Indicates the bundle name of the application whose notifications are to be removed. + * @param uid Indicates the uid of the application whose notifications are to be removed. + * @param notificationId Indicates the id of the notification to remove. + * @param label Indicates the label of the notification to remove. + * @return Returns remove notification result. + */ + static ErrCode RemoveNotification( + const std::string &bundleName, const int32_t uid, const int32_t notificationId, const std::string &label); + + /** + * Removes a specified removable notification of other applications. + * @note Your application must have platform signature to use this method. + * + * @param bundleName Indicates the bundle name of the application whose notifications are to be removed. + * @param uid Indicates the uid of the application whose notifications are to be removed. + * @return Returns remove notification result. + */ + static ErrCode RemoveNotifications(const std::string &bundleName, const int32_t uid); + /** * Removes all removable notifications of a specified bundle. * @note Your application must have platform signature to use this method. diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index c6e677199..3dc6be8ae 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -877,13 +877,13 @@ public: * Sets the UID of the notification creator. * @param uid the UID of the notification creator. */ - void SetCreatorUid(uid_t uid); + void SetCreatorUid(pid_t uid); /** * Obtains the UID of the notification creator. * @return the UID of the notification creator. */ - uid_t GetCreatorUid() const; + pid_t GetCreatorUid() const; /** * Sets the label of this notification. @@ -941,7 +941,7 @@ private: int64_t autoDeletedTime_{0}; pid_t creatorPid_{0}; - uid_t creatorUid_{0}; + pid_t creatorUid_{0}; std::string settingsText_{}; std::string creatorBundleName_{}; diff --git a/interfaces/innerkits/ans/native/include/notification_slot.h b/interfaces/innerkits/ans/native/include/notification_slot.h index c5cce6553..72b653f27 100644 --- a/interfaces/innerkits/ans/native/include/notification_slot.h +++ b/interfaces/innerkits/ans/native/include/notification_slot.h @@ -348,10 +348,10 @@ private: private: std::string id_; std::string name_; - bool isLightEnabled_; - bool isVibrationEnabled_; + bool isLightEnabled_ = false; + bool isVibrationEnabled_ = false; bool isShowBadge_ = true; - bool isBypassDnd_; + bool isBypassDnd_ = false; std::string description_; int32_t lightColor_ = 0; NotificationLevel level_ = LEVEL_DEFAULT; diff --git a/interfaces/kits/js/@ohos.notification.d.ts b/interfaces/kits/js/@ohos.notification.d.ts new file mode 100644 index 000000000..de721f0be --- /dev/null +++ b/interfaces/kits/js/@ohos.notification.d.ts @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AsyncCallback } from './basic'; +import { NotificationSlot } from './notification/notificationSlot'; +import { NotificationRequest } from './notification/notificationRequest'; + +/** + * Manages notifications. + * + *

Generally, only system applications have permissions on notification subscription and unsubscription. + * You can specify the content of a notification to be published and the content is carried by + * {@link NotificationRequest}. A notification ID is unique in an application and must be specified + * when using {@link NotificationRequest} to carry the notification content. If a notification + * with this ID has been published and you need to use this ID to publish another notification, + * the original notification will be updated. In addition, the notification ID can be used to cancel + * a notification by calling the {@link #cancel(int)} method. + * + * @name notification + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +declare namespace notification { + /** + * Publishes a notification. + * + *

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 {@link NotificationRequest} object for setting the notification content. + * This parameter must be specified. + * + * @since 7 + */ + function publish(request: NotificationRequest, callback: AsyncCallback): void; + function publish(request: NotificationRequest): Promise; + + /** + * Cancels a published notification. + * + * @param id Indicates the unique notification ID in the application. The value must be the ID + * of a published notification. Otherwise, this method does not take effect. + * + * @since 7 + */ + function cancel(id: number, callback: AsyncCallback): void; + + /** + * Cancels a published notification matching the specified {@code label} and {@code notificationId}. + * + * @param label Indicates the label of the notification to cancel. + * @param id Indicates the ID of the notification to cancel. + * + * @since 7 + */ + function cancel(id: number, label: string, callback: AsyncCallback): void; + function cancel(id: number, label?: string): Promise; + + /** + * Cancels all the published notifications. + * + * @since 7 + */ + function cancelAll(callback: AsyncCallback): void; + function cancelAll(): Promise; + + /** + * Queries a created notification slot. + * + * @param slotType Indicates the type of the slot, which is created by + * + * @return Returns the created {@link NotificationSlot}. + * + * @since 7 + */ + function getSlot(slotType: SlotType, callback: AsyncCallback): void; + function getSlot(slotType: SlotType): Promise; + + /** + * Obtains all notification slots of this application. + * + * @return Returns all notification slots of this application. + * + * @since 7 + */ + function getSlots(callback: AsyncCallback>): void; + function getSlots(): Promise>; + + /** + * Deletes a created notification slot based on the slot type. + * + * @param slotType Indicates the type of the slot. + * + * @since 7 + */ + function removeSlot(slotType: SlotType, callback: AsyncCallback): void; + function removeSlot(slotType: SlotType): Promise; + + /** + * Obtains all active notifications in the current system. The caller must have system permissions to + * call this method. + * + * @systemapi + * @since 7 + */ + function getAllActiveNotifications(callback: AsyncCallback>): void; + function getAllActiveNotifications(): Promise>; + + /** + * Obtains the number of active notifications of the current application in the system. + * + * @since 7 + */ + function getActiveNotificationNums(callback: AsyncCallback): void; + function getActiveNotificationNums(): Promise; + + /** + * Obtains active notifications of the current application in the system. + * + * @since 7 + */ + function getActiveNotifications(callback: AsyncCallback>): void; + function getActiveNotifications(): Promise>; + + /** + * Indicates the type of the slot + * + * @since 7 + */ + export enum SlotType { + UNKNOWN_TYPE = 0, + SOCIAL_COMMUNICATION = 1, + SERVICE_INFORMATION = 2, + CONTENT_INFORMATION = 3, + OTHER_TYPES = 0xFFFF, + } + + /** + * Indicates the type of the content + * + * @name ContentType + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ + export enum ContentType { + NOTIFICATION_CONTENT_BASIC_TEXT, + NOTIFICATION_CONTENT_LONG_TEXT, + NOTIFICATION_CONTENT_MULTILINE + } + + +} + +export default notification; diff --git a/interfaces/kits/js/@ohos.wantAgent.d.ts b/interfaces/kits/js/@ohos.wantAgent.d.ts new file mode 100644 index 000000000..53663513e --- /dev/null +++ b/interfaces/kits/js/@ohos.wantAgent.d.ts @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AsyncCallback , Callback} from './basic'; +import { Want } from './ability/want'; +import { WantAgentInfo } from './wantAgent/wantAgentInfo'; +import { TriggerInfo } from './wantAgent/triggerInfo'; + +/** + * Provide the method obtain trigger, cancel, and compare and to obtain + * the bundle name, UID of an {@link WantAgent} object. + * + * @name wantAgent + * @since 7 + * @devices phone, tablet + * @permission N/A + */ +declare namespace wantAgent { + /** + * Obtains the bundle name of an {@link WantAgent}. + * + * @param agent Indicates the {@link WantAgent} whose bundle name is to be obtained. + * + * @since 7 + */ + function getBundleName(agent: WantAgent, callback: AsyncCallback): void; + function getBundleName(agent: WantAgent): Promise; + + /** + * Obtains the bundle name of an {@link WantAgent}. + * + * @param agent Indicates the {@link WantAgent} whose UID is to be obtained. + * + * @since 7 + */ + function getUid(agent: WantAgent, callback: AsyncCallback): void; + function getUid(agent: WantAgent): Promise; + + /** + * Obtains the {@link Want} of an {@link WantAgent}. + * + * @param agent Indicates the {@link WantAgent} whose UID is to be obtained. + * + * @since 7 + */ + function getWant(agent: WantAgent, callback: AsyncCallback): void; + function getWant(agent: WantAgent): Promise; + + /** + * Cancels an {@link WantAgent}. Only the application that creates the {@link WantAgent} can cancel it. + * + * @param agent Indicates the {@link WantAgent} to cancel. + * + * @since 7 + */ + function cancel(agent: WantAgent, callback: AsyncCallback): void; + function cancel(agent: WantAgent): Promise; + + /** + * Obtains the bundle name of an {@link WantAgent}. + * + * @param agent Indicates the {@link WantAgent} whose bundle name is to be obtained. + * + * @since 7 + */ + function trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback): void; + + /** + * Checks whether two {@link WantAgent} objects are the same. + * + * @param agent Indicates one of the {@link WantAgent} object to compare. + * @param otherAgent Indicates the other {@link WantAgent} object to compare. + * @return Returns {@code true} If the two objects are the same; returns {@code false} otherwise. + * + * @since 7 + */ + function equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback): void; + function equal(agent: WantAgent, otherAgent: WantAgent): Promise; + + /** + * Obtains an {@link WantAgent} object. + * + * @param info Indicates the {@link WantAgentInfo} object that contains parameters of the + * {@link WantAgent} object to create. + * @return Returns the created {@link WantAgent} object. + * + * @since 7 + */ + function getWantAgent(info: WantAgentInfo, callback: AsyncCallback): void; + function getWantAgent(info: WantAgentInfo): Promise; + + /** + * Enumerates flags for using an {@link WantAgent}. + * + * @since 7 + */ + export enum Flags { + ONE_TIME_FLAG = 0, + NO_BUILD_FLAG, + CANCEL_PRESENT_FLAG, + UPDATE_PRESENT_FLAG, + CONSTANT_FLAG, + REPLACE_ELEMENT, + REPLACE_ACTION, + REPLACE_URI, + REPLACE_ENTITIES, + REPLACE_BUNDLE + } + + /** + * Identifies the operation for using an {@link WantAgent}, such as starting an ability or sending a common event. + * + * @since 7 + */ + export enum OperationType { + UNKNOWN_TYPE = 0, + START_ABILITY, + START_ABILITIES, + START_SERVICE, + SEND_COMMON_EVENT, + START_FOREGROUND_SERVICE + } + + /** + * A callback for the {@link trigger()} method. After the method execution is complete, + * the callback process will start. + * + * @since 7 + */ + export interface CompleteData { + info: WantAgent; + want: Want; + finalCode: number; + finalData: string; + extraInfo?: {[key: string]: any}; + } +} + +export type WantAgent = object; + +export default wantAgent; \ No newline at end of file diff --git a/interfaces/kits/js/notification/notificationContent.d.ts b/interfaces/kits/js/notification/notificationContent.d.ts new file mode 100644 index 000000000..f89526b33 --- /dev/null +++ b/interfaces/kits/js/notification/notificationContent.d.ts @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import notification from '../@ohos.notification'; + +/** + * Constructs basic notifications. + * + * @name NotificationBasicContent + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationBasicContent { + title: string; + text: string; + additionalText?: string; +} + +/** + * Constructs notifications that include long text. The long text contains a maximum of 1024 characters. + * + * @name NotificationLongTextContent + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationLongTextContent extends NotificationBasicContent { + longText: string; + briefText: string; + expandedTitle: string; +} + +/** + * Constructs a notification that includes multiple lines of text. + * + * @name NotificationMultiLineContent + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationMultiLineContent extends NotificationBasicContent { + briefText: string; + longTitle: string; + lines: Array; +} + +/** + * Constructs a notification that includes multiple lines of text. + * + * @name NotificationMultiLineContent + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationContent { + contentType: notification.ContentType; + normal?: NotificationBasicContent; + longText?: NotificationLongTextContent; + multiLine?: NotificationMultiLineContent; +} diff --git a/interfaces/kits/js/notification/notificationRequest.d.ts b/interfaces/kits/js/notification/notificationRequest.d.ts new file mode 100644 index 000000000..9fcbc5613 --- /dev/null +++ b/interfaces/kits/js/notification/notificationRequest.d.ts @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http?://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import notification from '../@ohos.notification'; +import { WantAgent } from '../@ohos.wantAgent'; +import { NotificationContent } from './notificationContent'; + +/** + * Carries notifications. + * + * @name NotificationRequest + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationRequest { + content: NotificationContent; + id?: number; + slotType?: notification.SlotType; + isOngoing?: boolean; + isUnremovable?: boolean; + deliveryTime?: number; + tapDismissed?: boolean; + autoDeletedTime?: number; + wantAgent?: WantAgent; + extraInfo?: {[key: string]: any}; + removalWantAgent?: WantAgent; + maxScreenWantAgent?: WantAgent; + color?: number; + colorEnabled?: boolean; + isAlertOnce?: boolean; + isStopwatch?: boolean; + isCountDown?: boolean; + progressValue?: number; + progressMaxValue?: number; + isIndeterminate?: boolean; + statusBarText?: string; + isFloatingIcon?: boolean; + label?: string; + badgeIconStyle?: number; + showDeliveryTime?: boolean; + /** + * Obtains the classification of this notification. + * + * @systemapi + * @since 7 + */ + classification?: string; + + /** + * Obtains the key used for sorting notifications from the same application bundle. + * + * @systemapi + * @since 7 + */ + sortingKey?: string; + readonly hashcode?: string; + readonly creatorBundleName?: string; + readonly creatorUid?: number; + readonly creatorPid?: number; +} diff --git a/interfaces/kits/js/notification/notificationSlot.d.ts b/interfaces/kits/js/notification/notificationSlot.d.ts new file mode 100644 index 000000000..982593a5f --- /dev/null +++ b/interfaces/kits/js/notification/notificationSlot.d.ts @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import notification from '../@ohos.notification'; + +/** + * A constructor used to initialize the type, desc, and level of a {@code NotificationSlot} object. + * + * @name NotificationSlot + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationSlot { + /** + * Obtains the type of a notification slot. + * + * @since 7 + */ + type: notification.SlotType; + + /** + * Obtains the level of a notification slot + * + * @since 7 + */ + level?: number; + + /** + * Obtains the description of a notification slot. + * + * @since 7 + */ + desc?: string; + + /** + * Obtains the application icon badge status of a notification slot. + * + * @since 7 + */ + showBadgeFlag?: boolean; + + /** + * Obtains whether DND mode is bypassed for a notification slot. + * + * @since 7 + */ + bypassDnd?: boolean; + + /** + * Whether and how to display notifications on the lock screen. + * + * @since 7 + */ + lockscreenVisibility?: number; + + /** + * Obtains the vibration status of the notification slot. + * + * @since 7 + */ + vibrationEnabled?: boolean; + + /** + * Obtains the prompt tone of the notification slot. + * + * @since 7 + */ + sound?: string; + + /** + * Obtains whether the notification light is enabled in a notification slot. + * + * @since 7 + */ + lightEnabled?: boolean; + + /** + * Obtains the color of the notification light in a notification slot. + * + * @since 7 + */ + lightColor?: number; + + /** + * Obtains the vibration style of notifications in this notification slot. + * + * @since 7 + */ + vibrationValues?: Array; +} diff --git a/interfaces/kits/js/notification/notificationSorting.d.ts b/interfaces/kits/js/notification/notificationSorting.d.ts new file mode 100644 index 000000000..73fbae19b --- /dev/null +++ b/interfaces/kits/js/notification/notificationSorting.d.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NotificationSlot } from './notificationSlot'; + +/** + * Provides sorting information about an active notification. + * + * @name NotificationSorting + * @sysCap ans + * @devices phone, tablet + * @permission N/A + * @since 7 + */ +export interface NotificationSorting { + readonly slot: NotificationSlot; + readonly hashCode: string; + readonly ranking: number; +} \ No newline at end of file diff --git a/interfaces/kits/js/notification/notificationSortingMap.d.ts b/interfaces/kits/js/notification/notificationSortingMap.d.ts new file mode 100644 index 000000000..f632189de --- /dev/null +++ b/interfaces/kits/js/notification/notificationSortingMap.d.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NotificationSorting } from './notificationSorting'; + +/** + * Provides sorting information about the active notifications among all the notifications that have been subscribed to + * + * @name NotificationSortingMap + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +interface NotificationSortingMap { + readonly sortings: {[key: string]: NotificationSorting}; + readonly sortedHashCode: Array; +} \ No newline at end of file diff --git a/interfaces/kits/js/wantAgent/triggerInfo.d.ts b/interfaces/kits/js/wantAgent/triggerInfo.d.ts new file mode 100644 index 000000000..f12ac8ebe --- /dev/null +++ b/interfaces/kits/js/wantAgent/triggerInfo.d.ts @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Want } from '../ability/want'; + +/** + * the info when object of WantAgent trigger + * + * @name TriggerInfo + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface TriggerInfo { + code: number; + want?: Want; + permission?: string; + extraInfo?: {[key: string]: any}; +} \ No newline at end of file diff --git a/interfaces/kits/js/wantAgent/wantAgentInfo.d.ts b/interfaces/kits/js/wantAgent/wantAgentInfo.d.ts new file mode 100644 index 000000000..675ba97d1 --- /dev/null +++ b/interfaces/kits/js/wantAgent/wantAgentInfo.d.ts @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Want } from '../ability/want'; +import wantAgent from '../@ohos.wantAgent' + +/** + * the info of WantAgent + * + * @name WantAgentInfo + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface WantAgentInfo { + wants: Array; + operationType: wantAgent.OperationType; + requestCode: number; + wantAgentFlags?: Array; + extraInfo?: {[key: string]: any}; +} \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index 9b427c4d4..482638bd8 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -25,6 +25,7 @@ namespace NotificationNapi { using namespace OHOS::Notification; const std::int32_t STR_MAX_SIZE = 64; +const std::int32_t LONG_STR_MAX_SIZE = 1024; const int NO_ERROR = 0; const int ERROR = -1; @@ -45,6 +46,14 @@ enum SlotType { OTHER_TYPES = 0xFFFF, }; +enum SlotLevel { + LEVEL_NONE = 0, + LEVEL_MIN = 1, + LEVEL_LOW = 2, + LEVEL_DEFAULT = 3, + LEVEL_HIGH = 4, +}; + enum NotificationReason { CLICK_REASON_DELETE, CANCEL_REASON_DELETE, @@ -85,6 +94,16 @@ struct NotificationSubscriberInfo { bool hasSubscriberInfo = false; }; +struct BundleOption { + std::string bundle{}; + int uid{}; +}; + +struct NotificationKey { + int id{}; + std::string label{}; +}; + struct CallbackPromiseInfo { napi_ref callback = nullptr; napi_deferred deferred; @@ -93,7 +112,6 @@ struct CallbackPromiseInfo { }; class Common { - Common(); ~Common(); @@ -105,6 +123,9 @@ public: static napi_value GetCallbackErrorValue(napi_env env, int errCode); + static void PaddingCallbackPromiseInfo( + const napi_env &env, const napi_ref &callback, CallbackPromiseInfo &info, napi_value &promise); + static void ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result); static void SetCallback( @@ -166,7 +187,11 @@ public: static napi_value GetNotificationWantAgent( const napi_env &env, const napi_value &value, NotificationRequest &request); - static napi_value GetNotificationSlot(const napi_env &env, NotificationSlot &slot, const napi_value &result); + static napi_value GetNotificationSlot(const napi_env &env, const napi_value &value, NotificationSlot &slot); + + static napi_value GetBundleOption(const napi_env &env, const napi_value &value, BundleOption &option); + + static napi_value GetNotificationKey(const napi_env &env, const napi_value &value, NotificationKey &key); static bool ContentTypeJSToC(const enum ContentType &inType, enum NotificationContent::Type &outType); @@ -176,6 +201,10 @@ public: static bool SlotTypeCToJS(const enum NotificationConstant::SlotType &inType, enum SlotType &outType); + static bool SlotLevelJSToC(const SlotLevel &inLevel, NotificationSlot::NotificationLevel &outLevel); + + static bool SlotLevelCToJS(const NotificationSlot::NotificationLevel &inLevel, SlotLevel &outLevel); + static bool ReasonCToJS(const int &inType, int &outType); static bool DisturbModeJSToC(const enum DisturbMode &inType, enum NotificationConstant::DisturbMode &outType); diff --git a/interfaces/kits/napi/ans/include/constant.h b/interfaces/kits/napi/ans/include/constant.h index 516b4422f..fc2f9b782 100644 --- a/interfaces/kits/napi/ans/include/constant.h +++ b/interfaces/kits/napi/ans/include/constant.h @@ -24,6 +24,7 @@ namespace OHOS { namespace NotificationNapi { napi_value NotificationReasonInit(napi_env env, napi_value exports); napi_value SlotTypeInit(napi_env env, napi_value exports); +napi_value SlotLevelInit(napi_env env, napi_value exports); napi_value SemanticActionButtonInit(napi_env env, napi_value exports); napi_value InputsSourceInit(napi_env env, napi_value exports); napi_value DisturbModeInit(napi_env env, napi_value exports); diff --git a/interfaces/kits/napi/ans/include/slot.h b/interfaces/kits/napi/ans/include/slot.h index 1f851d501..938d2b243 100644 --- a/interfaces/kits/napi/ans/include/slot.h +++ b/interfaces/kits/napi/ans/include/slot.h @@ -26,6 +26,7 @@ napi_value AddSlots(napi_env env, napi_callback_info info); napi_value GetSlot(napi_env env, napi_callback_info info); napi_value GetSlots(napi_env env, napi_callback_info info); napi_value RemoveSlot(napi_env env, napi_callback_info info); +napi_value RemoveAllSlots(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/src/cancel.cpp b/interfaces/kits/napi/ans/src/cancel.cpp index 24fb59675..5dbafbdf8 100644 --- a/interfaces/kits/napi/ans/src/cancel.cpp +++ b/interfaces/kits/napi/ans/src/cancel.cpp @@ -24,64 +24,67 @@ const int CANCEL_ALL_MAX_PARA = 1; struct AsyncCallbackInfoCancel { napi_env env; napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; std::string label; int id; - bool hasLabel = false; - bool isCallback = false; - int errorCode = 0; + CallbackPromiseInfo info; }; -struct paraInfoCancel { +struct ParametersInfoCancel { int id = 0; - std::string label; - bool hasLabel = false; + std::string label = ""; + napi_ref callback = nullptr; }; -napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[CANCEL_MAX_PARA], const size_t &argc, - paraInfoCancel &info, napi_ref &callback) +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, ParametersInfoCancel ¶s) { - ANS_LOGI("ParseParameters start"); + ANS_LOGI("enter"); + size_t argc = CANCEL_MAX_PARA; + napi_value argv[CANCEL_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype; // argv[0]: id: number NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - NAPI_CALL(env, napi_get_value_int32(env, argv[0], &info.id)); + NAPI_CALL(env, napi_get_value_int32(env, argv[0], ¶s.id)); // argv[1]: label: string / callback if (argc >= CANCEL_MAX_PARA - 1) { NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, + (valuetype == napi_string || valuetype == napi_function), + "Wrong argument type. String or function expected."); if (valuetype == napi_string) { char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; NAPI_CALL(env, napi_get_value_string_utf8(env, argv[1], str, STR_MAX_SIZE - 1, &strLen)); - info.label = str; - info.hasLabel = true; - } else if (valuetype == napi_function) { - napi_create_reference(env, argv[1], 1, &callback); + paras.label = str; } else { - return nullptr; + napi_create_reference(env, argv[1], 1, ¶s.callback); } } - // argv[2]:callback + // argv[2]: callback if (argc >= CANCEL_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[CANCEL_MAX_PARA - 1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[CANCEL_MAX_PARA - 1], 1, &callback); + napi_create_reference(env, argv[CANCEL_MAX_PARA - 1], 1, ¶s.callback); } return Common::NapiGetNull(env); } -napi_value ParseParametersByAll( - const napi_env &env, const napi_value (&argv)[CANCEL_ALL_MAX_PARA], const size_t &argc, napi_ref &callback) +napi_value ParseParametersByCancelAll(const napi_env &env, const napi_callback_info &info, napi_ref &callback) { - ANS_LOGI("ParseParametersByAll start"); + ANS_LOGI("enter"); + + size_t argc = CANCEL_ALL_MAX_PARA; + napi_value argv[CANCEL_ALL_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); if (argc >= CANCEL_ALL_MAX_PARA) { napi_valuetype valuetype; @@ -93,44 +96,22 @@ napi_value ParseParametersByAll( return Common::NapiGetNull(env); } -void PaddingAsyncCallbackInfoIs( - const napi_env &env, AsyncCallbackInfoCancel *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) -{ - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); - - if (callback) { - asynccallbackinfo->callback = callback; - asynccallbackinfo->isCallback = true; - } else { - napi_deferred deferred = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; - } -} - napi_value Cancel(napi_env env, napi_callback_info info) { - ANS_LOGI("Cancel start"); + ANS_LOGI("enter"); - size_t argc = CANCEL_MAX_PARA; - napi_value argv[CANCEL_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - napi_ref callback = nullptr; - - paraInfoCancel paraInfo; - if (ParseParameters(env, argv, argc, paraInfo, callback) == nullptr) { - return Common::JSParaError(env, callback); + ParametersInfoCancel paras; + if (ParseParameters(env, info, paras) == nullptr) { + return Common::JSParaError(env, paras.callback); } - ANS_LOGI("Cancel id = %{public}d", paraInfo.id); - ANS_LOGI("Cancel label = %{public}s", paraInfo.label.c_str()); - - AsyncCallbackInfoCancel *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoCancel{ - .env = env, .asyncWork = nullptr, .id = paraInfo.id, .label = paraInfo.label, .hasLabel = paraInfo.hasLabel}; + AsyncCallbackInfoCancel *asynccallbackinfo = new (std::nothrow) + AsyncCallbackInfoCancel{.env = env, .asyncWork = nullptr, .id = paras.id, .label = paras.label}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "cancel", NAPI_AUTO_LENGTH, &resourceName); @@ -142,24 +123,14 @@ napi_value Cancel(napi_env env, napi_callback_info info) ANS_LOGI("Cancel napi_create_async_work start"); AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; - if (asynccallbackinfo->hasLabel) { - asynccallbackinfo->errorCode = - NotificationHelper::CancelNotification(asynccallbackinfo->label, asynccallbackinfo->id); - } else { - asynccallbackinfo->errorCode = NotificationHelper::CancelNotification(asynccallbackinfo->id); - } + asynccallbackinfo->info.errorCode = + NotificationHelper::CancelNotification(asynccallbackinfo->label, asynccallbackinfo->id); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("Cancel napi_create_async_work end"); AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -172,7 +143,7 @@ napi_value Cancel(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; @@ -181,23 +152,20 @@ napi_value Cancel(napi_env env, napi_callback_info info) napi_value CancelAll(napi_env env, napi_callback_info info) { - ANS_LOGI("CancelAll start"); + ANS_LOGI("enter"); - size_t argc = CANCEL_ALL_MAX_PARA; - napi_value argv[CANCEL_ALL_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); napi_ref callback = nullptr; - - if (ParseParametersByAll(env, argv, argc, callback) == nullptr) { + if (ParseParametersByCancelAll(env, info, callback) == nullptr) { return Common::JSParaError(env, callback); } AsyncCallbackInfoCancel *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoCancel{.env = env, .asyncWork = nullptr}; - + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "cancelAll", NAPI_AUTO_LENGTH, &resourceName); @@ -208,18 +176,13 @@ napi_value CancelAll(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("CancelAll napi_create_async_work start"); AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; - asynccallbackinfo->errorCode = NotificationHelper::CancelAllNotifications(); + asynccallbackinfo->info.errorCode = NotificationHelper::CancelAllNotifications(); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("CancelAll napi_create_async_work end"); AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -232,7 +195,7 @@ napi_value CancelAll(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 19ae25e69..736096829 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -17,6 +17,7 @@ #include "napi_common.h" #include "notification_long_text_content.h" #include "notification_multiline_content.h" +#include "notification_slot.h" #include "publish.h" #include "want_agent.h" @@ -64,8 +65,7 @@ static napi_value GetNotificationStatusBarText( const napi_env &env, const napi_value &value, NotificationRequest &request); // static napi_value GetNotificationOnlyLocal( // const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationSortingKey( - const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationSortingKey(const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetNotificationBadgeIconStyle( const napi_env &env, const napi_value &value, NotificationRequest &request); @@ -120,9 +120,25 @@ napi_value Common::GetCallbackErrorValue(napi_env env, int errCode) return result; } +void Common::PaddingCallbackPromiseInfo( + const napi_env &env, const napi_ref &callback, CallbackPromiseInfo &info, napi_value &promise) +{ + ANS_LOGI("enter"); + + if (callback) { + info.callback = callback; + info.isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + info.deferred = deferred; + info.isCallback = false; + } +} + void Common::ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result) { - ANS_LOGI("ReturnCallbackPromise start"); + ANS_LOGI("enter"); if (info.isCallback) { SetCallback(env, info.callback, info.errorCode, result); @@ -172,7 +188,7 @@ napi_value Common::JSParaError(const napi_env &env, const napi_ref &callback) napi_value Common::SetNotification( const napi_env &env, OHOS::Notification::Notification *notification, napi_value &result) { - ANS_LOGI("SetNotification start"); + ANS_LOGI("enter"); if (notification == nullptr) { ANS_LOGE("notification is nullptr"); @@ -554,10 +570,9 @@ napi_value Common::SetNotificationSorting(const napi_env &env, const Notificatio napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSlot &slot, napi_value &result) { - ANS_LOGI("SetNotificationSlot start"); + ANS_LOGI("enter"); napi_value value = 0; - // type: SlotType; enum SlotType outType; if (!SlotTypeCToJS(slot.GetType(), outType)) { @@ -567,7 +582,11 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl napi_set_named_property(env, result, "type", value); // level?: number - napi_create_int32(env, slot.GetLevel(), &value); + enum SlotLevel outLevel { SlotLevel::LEVEL_NONE }; + if (!SlotLevelCToJS(slot.GetLevel(), outLevel)) { + return NapiGetboolean(env, false); + } + napi_create_int32(env, outLevel, &value); napi_set_named_property(env, result, "level", value); // desc?: string @@ -583,8 +602,8 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl napi_set_named_property(env, result, "bypassDnd", value); // lockscreenVisibility?: number - int32_t LockScreenVisibleness = (int32_t)slot.GetLockScreenVisibleness(); - napi_create_int32(env, LockScreenVisibleness, &value); + int32_t lockScreenVisibleness = (int32_t)slot.GetLockScreenVisibleness(); + napi_create_int32(env, lockScreenVisibleness, &value); napi_set_named_property(env, result, "lockscreenVisibility", value); // vibrationEnabled?: boolean @@ -981,61 +1000,65 @@ napi_value Common::SetNotificationActionButton( } napi_value Common::GetNotificationSubscriberInfo( - const napi_env &env, const napi_value &value, NotificationSubscriberInfo &result) + const napi_env &env, const napi_value &value, NotificationSubscriberInfo &subscriberInfo) { uint32_t length = 0; size_t strLen; bool hasProperty = false; + bool isArray = false; napi_valuetype valuetype; + // bundleNames?: Array; NAPI_CALL(env, napi_has_named_property(env, value, "bundleNames", &hasProperty)); if (hasProperty) { - napi_value nbundleNames; - napi_get_named_property(env, value, "bundleNames", &nbundleNames); - napi_get_array_length(env, nbundleNames, &length); - if (length > 0) { - for (uint32_t i = 0; i < length; ++i) { - napi_value nbundleName; - char str[STR_MAX_SIZE] = {0}; - napi_get_element(env, nbundleNames, i, &nbundleName); - NAPI_CALL(env, napi_typeof(env, nbundleName, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, nbundleName, str, STR_MAX_SIZE - 1, &strLen)); - result.bundleNames.emplace_back(str); - result.hasSubscriberInfo = true; - } + napi_value nBundleNames; + napi_get_named_property(env, value, "bundleNames", &nBundleNames); + napi_is_array(env, nBundleNames, &isArray); + NAPI_ASSERT(env, isArray, "Property bundleNames is expected to be an array."); + napi_get_array_length(env, nBundleNames, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + for (uint32_t i = 0; i < length; ++i) { + napi_value nBundleName; + char str[STR_MAX_SIZE] = {0}; + napi_get_element(env, nBundleNames, i, &nBundleName); + NAPI_CALL(env, napi_typeof(env, nBundleName, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, nBundleName, str, STR_MAX_SIZE - 1, &strLen)); + subscriberInfo.bundleNames.emplace_back(str); + subscriberInfo.hasSubscriberInfo = true; } } - // deviceIds?: Array; + // // deviceIds?: Array; // NAPI_CALL(env, napi_has_named_property(env, value, "deviceIds", &hasProperty)); // if (hasProperty) { - // napi_value ndeviceIds; - // napi_get_named_property(env, value, "deviceIds", &ndeviceIds); + // napi_value nDeviceIds; + // napi_get_named_property(env, value, "deviceIds", &nDeviceIds); + // napi_is_array(env, nDeviceIds, &isArray); + // NAPI_ASSERT(env, isArray, "Property bundleNames is expected to be an array."); // napi_get_array_length(env, value, &length); - // if (length > 0) { - // for (uint32_t i = 0; i < length; ++i) { - // napi_value ndeviceId; - // char str[STR_MAX_SIZE] = {0}; - // napi_get_element(env, ndeviceIds, i, &ndeviceId); - // NAPI_CALL(env, napi_typeof(env, ndeviceId, &valuetype)); - // NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - // NAPI_CALL(env, napi_get_value_string_utf8(env, ndeviceId, str, STR_MAX_SIZE - 1, &strLen)); - // result.deviceIds.emplace_back(str); - // result.hasSubscriberInfo = true; - // } + // NAPI_ASSERT(env, length > 0, "The array is empty."); + // for (uint32_t i = 0; i < length; ++i) { + // napi_value nDeviceId; + // char str[STR_MAX_SIZE] = {0}; + // napi_get_element(env, nDeviceIds, i, &nDeviceId); + // NAPI_CALL(env, napi_typeof(env, nDeviceId, &valuetype)); + // NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + // NAPI_CALL(env, napi_get_value_string_utf8(env, nDeviceId, str, STR_MAX_SIZE - 1, &strLen)); + // subscriberInfo.deviceIds.emplace_back(str); + // subscriberInfo.hasSubscriberInfo = true; // } // } // userId?: number; NAPI_CALL(env, napi_has_named_property(env, value, "userId", &hasProperty)); if (hasProperty) { - napi_value nuserId; - napi_get_named_property(env, value, "userId", &nuserId); - NAPI_CALL(env, napi_typeof(env, nuserId, &valuetype)); + napi_value nUserId; + napi_get_named_property(env, value, "userId", &nUserId); + NAPI_CALL(env, napi_typeof(env, nUserId, &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - NAPI_CALL(env, napi_get_value_int32(env, nuserId, &result.userId)); - result.hasSubscriberInfo = true; + NAPI_CALL(env, napi_get_value_int32(env, nUserId, &subscriberInfo.userId)); + subscriberInfo.hasSubscriberInfo = true; } return NapiGetNull(env); @@ -1081,7 +1104,7 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value } // wantAgent?: WantAgent - if (Common::GetNotificationWantAgent(env, value, request) == nullptr) { + if (GetNotificationWantAgent(env, value, request) == nullptr) { return nullptr; } @@ -1167,18 +1190,6 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value return nullptr; } - // progressMaxValue?: number - // if (GetNotificationProgressMaxValueByPublish(env, value, notificationRequestData.progressMaxValue, request) == - // nullptr) { - // return nullptr; - // } - - // isIndeterminate?: boolean - // if (GetNotificationIsIndeterminateByPublish(env, value, notificationRequestData.isIndeterminate, request) == - // nullptr) { - // return nullptr; - // } - // statusBarText?: string if (GetNotificationStatusBarText(env, value, request) == nullptr) { return nullptr; @@ -1232,7 +1243,6 @@ napi_value GetIdByPublish(const napi_env &env, const napi_value &value, Notifica int32_t notificationId; NAPI_CALL(env, napi_has_named_property(env, value, "id", &hasProperty)); - ANS_LOGI("============GetIdByPublish hasProperty = %{public}d", hasProperty); if (hasProperty) { napi_get_named_property(env, value, "id", &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); @@ -1258,7 +1268,6 @@ napi_value GetSlotType(const napi_env &env, const napi_value &value, Notificatio int32_t slotType; NAPI_CALL(env, napi_has_named_property(env, value, "slotType", &hasProperty)); - ANS_LOGI("============GetSlotType hasProperty = %{public}d", hasProperty); if (hasProperty) { napi_get_named_property(env, value, "slotType", &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); @@ -1288,55 +1297,52 @@ napi_value Common::GetNotificationContent(const napi_env &env, const napi_value int32_t type; NAPI_CALL(env, napi_has_named_property(env, value, "content", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, value, "content", &result); - NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - ANS_LOGI("GetNotificationContent valuetype = %{public}d", valuetype); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - if (GetNotificationContentType(env, result, type) == nullptr) { - return nullptr; - } - NotificationContent::Type outType; - if (!ContentTypeJSToC(ContentType(type), outType)) { - return nullptr; - } - switch (outType) { - case NotificationContent::Type::BASIC_TEXT: - ANS_LOGI("============GetNotificationContent================"); - if (GetNotificationBasicContent(env, result, request) == nullptr) { - return nullptr; - } - break; - case NotificationContent::Type::LONG_TEXT: - ANS_LOGI("============GetNotificationLongContentByPublish================"); - if (GetNotificationLongTextContent(env, result, request) == nullptr) { - return nullptr; - } - break; - case NotificationContent::Type::PICTURE: - ANS_LOGI("============GetNotificationPictureContent================"); - if (GetNotificationPictureContent(env, result, request) == nullptr) { - return nullptr; - } - break; - case NotificationContent::Type::CONVERSATION: - ANS_LOGI("============GetNotificationConversationalContent================"); - if (GetNotificationConversationalContent(env, result, request) == nullptr) { - return nullptr; - } - break; - case NotificationContent::Type::MULTILINE: - ANS_LOGI("============GetNotificationMultilineContentByPublish================"); - if (GetNotificationMultiLineContent(env, result, request) == nullptr) { - return nullptr; - } - break; - case NotificationContent::Type::MEDIA: - break; - default: + if (!hasProperty) { + ANS_LOGE("Property content expected."); + return nullptr; + } + + napi_get_named_property(env, value, "content", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + if (GetNotificationContentType(env, result, type) == nullptr) { + return nullptr; + } + NotificationContent::Type outType; + if (!ContentTypeJSToC(ContentType(type), outType)) { + return nullptr; + } + switch (outType) { + case NotificationContent::Type::BASIC_TEXT: + if (GetNotificationBasicContent(env, result, request) == nullptr) { return nullptr; - break; - } + } + break; + case NotificationContent::Type::LONG_TEXT: + if (GetNotificationLongTextContent(env, result, request) == nullptr) { + return nullptr; + } + break; + case NotificationContent::Type::PICTURE: + if (GetNotificationPictureContent(env, result, request) == nullptr) { + return nullptr; + } + break; + case NotificationContent::Type::CONVERSATION: + if (GetNotificationConversationalContent(env, result, request) == nullptr) { + return nullptr; + } + break; + case NotificationContent::Type::MULTILINE: + if (GetNotificationMultiLineContent(env, result, request) == nullptr) { + return nullptr; + } + break; + case NotificationContent::Type::MEDIA: + break; + default: + return nullptr; + break; } ANS_LOGI("end"); @@ -1443,6 +1449,7 @@ napi_value Common::GetNotificationWantAgent(const napi_env &env, const napi_valu NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); napi_unwrap(env, result, (void **)&wantAgent); if (wantAgent == nullptr) { + ANS_LOGE("Invalid object wantAgent"); return nullptr; } std::shared_ptr sWantAgent = std::make_shared(*wantAgent); @@ -1493,6 +1500,7 @@ napi_value GetNotificationRemovalWantAgent(const napi_env &env, const napi_value NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); napi_unwrap(env, result, (void **)&wantAgent); if (wantAgent == nullptr) { + ANS_LOGE("Invalid object removalWantAgent"); return nullptr; } std::shared_ptr removeWantAgent = std::make_shared(*wantAgent); @@ -1518,6 +1526,7 @@ napi_value GetNotificationMaxScreenWantAgent(const napi_env &env, const napi_val NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); napi_unwrap(env, result, (void **)&wantAgent); if (wantAgent == nullptr) { + ANS_LOGE("Invalid object maxScreenWantAgent"); return nullptr; } std::shared_ptr maxScreenWantAgent = std::make_shared(*wantAgent); @@ -1640,8 +1649,7 @@ napi_value GetNotificationAutoDeletedTime(const napi_env &env, const napi_value // return Common::NapiGetNull(env); // } -napi_value GetNotificationClassification( - const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value GetNotificationClassification(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1789,92 +1797,46 @@ napi_value GetNotificationIsCountDown(const napi_env &env, const napi_value &val // return Common::NapiGetNull(env); // } + napi_value GetNotificationProgressBar(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); napi_valuetype valuetype; - napi_value resultProgressValue, resultProgressMaxValue, resultIsIndeterminate; - bool hasPropertyProgressValue = false; - bool hasPropertyProgressMaxValue = false; - bool hasPropertyIsIndeterminate = false; + napi_value result; + bool hasProperty = false; int32_t progressValue = 0; int32_t progressMaxValue = 0; bool isIndeterminate = false; - NAPI_CALL(env, napi_has_named_property(env, value, "progressValue", &hasPropertyProgressValue)); - if (hasPropertyProgressValue) { - NAPI_CALL(env, napi_has_named_property(env, value, "progressMaxValue", &hasPropertyProgressMaxValue)); - if (hasPropertyProgressMaxValue) { - NAPI_CALL(env, napi_has_named_property(env, value, "isIndeterminate", &hasPropertyIsIndeterminate)); - if (hasPropertyIsIndeterminate) { - napi_get_named_property(env, value, "progressValue", &resultProgressValue); - NAPI_CALL(env, napi_typeof(env, resultProgressValue, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, resultProgressValue, &progressValue); - - napi_get_named_property(env, value, "progressMaxValue", &resultProgressMaxValue); - NAPI_CALL(env, napi_typeof(env, resultProgressMaxValue, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, resultProgressMaxValue, &progressMaxValue); - - napi_get_named_property(env, value, "isIndeterminate", &resultIsIndeterminate); - NAPI_CALL(env, napi_typeof(env, resultIsIndeterminate, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. bool expected."); - napi_get_value_bool(env, resultIsIndeterminate, &isIndeterminate); - } - } - request.SetProgressBar(progressValue, progressMaxValue, isIndeterminate); + NAPI_CALL(env, napi_has_named_property(env, value, "progressValue", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "progressValue", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, result, &progressValue); } - return Common::NapiGetNull(env); -} - -// napi_value GetNotificationProgressMaxValueByPublish( -// const napi_env &env, const napi_value &value, int32_t &progressMaxValue, NotificationRequest &request) -// { -// ANS_LOGI("enter"); - -// napi_valuetype valuetype; -// napi_value result; -// bool hasProperty = false; - -// NAPI_CALL(env, napi_has_named_property(env, value, "progressMaxValue", &hasProperty)); -// if (hasProperty) { -// // isSetRequestProperty[PROGRESSMAXVALUE] = true; -// napi_get_named_property(env, value, "progressMaxValue", &result); -// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); -// NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. int expected."); -// napi_get_value_int32(env, result, &progressMaxValue); -// } else { -// // isSetRequestProperty[PROGRESSMAXVALUE] = false; -// } - -// return Common::NapiGetNull(env); -// } - -// napi_value GetNotificationIsIndeterminateByPublish( -// const napi_env &env, const napi_value &value, bool &isIndeterminate, NotificationRequest &request) -// { -// ANS_LOGI("enter"); + NAPI_CALL(env, napi_has_named_property(env, value, "progressMaxValue", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "progressMaxValue", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, result, &progressMaxValue); + } -// napi_valuetype valuetype; -// napi_value result; -// bool hasProperty = false; + NAPI_CALL(env, napi_has_named_property(env, value, "isIndeterminate", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "isIndeterminate", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, result, &isIndeterminate); + } -// NAPI_CALL(env, napi_has_named_property(env, value, "isIndeterminate", &hasProperty)); -// if (hasProperty) { -// // isSetRequestProperty[ISINDETERMINATE] = true; -// napi_get_named_property(env, value, "isIndeterminate", &result); -// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); -// NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. bool expected."); -// napi_get_value_bool(env, result, &isIndeterminate); -// } else { -// // isSetRequestProperty[ISINDETERMINATE] = false; -// } + request.SetProgressBar(progressValue, progressMaxValue, isIndeterminate); -// return Common::NapiGetNull(env); -// } + return Common::NapiGetNull(env); +} napi_value GetNotificationStatusBarText(const napi_env &env, const napi_value &value, NotificationRequest &request) { @@ -1895,7 +1857,6 @@ napi_value GetNotificationStatusBarText(const napi_env &env, const napi_value &v request.SetStatusBarText(str); } - ANS_LOGI("===============GetNotificationStatusBarText====statusBarText = %{public}s end", str); return Common::NapiGetNull(env); } @@ -1921,8 +1882,7 @@ napi_value GetNotificationStatusBarText(const napi_env &env, const napi_value &v // return Common::NapiGetNull(env); // } -napi_value GetNotificationSortingKey( - const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value GetNotificationSortingKey(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1963,7 +1923,6 @@ napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, No request.SetLabel(str); } - ANS_LOGI("===============GetNotificationLabel====label = %{public}s end", str); return Common::NapiGetNull(env); } @@ -2025,7 +1984,7 @@ napi_value GetNotificationShowDeliveryTime(const napi_env &env, const napi_value if (hasProperty) { napi_get_named_property(env, value, "showDeliveryTime", &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. bool expected."); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); napi_get_value_bool(env, result, &showDeliveryTime); request.SetShowDeliveryTime(showDeliveryTime); } @@ -2050,44 +2009,57 @@ napi_value GetNotificationNotificationActionButtons( WantAgent::WantAgent *wantAgentPtr = nullptr; std::shared_ptr wantAgent; + napi_has_named_property(env, value, "actionButtons", &hasProperty); + if (!hasProperty) { + return Common::NapiGetNull(env); + } + napi_get_named_property(env, value, "actionButtons", &actionButtons); napi_is_array(env, actionButtons, &isArray); - if (isArray) { - napi_get_array_length(env, actionButtons, &length); - NAPI_ASSERT(env, length > 0, "The array is empty."); - for (size_t i = 0; i < length; i++) { - napi_value actionButton; - napi_get_element(env, actionButtons, i, &actionButton); - NAPI_CALL(env, napi_typeof(env, actionButton, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + NAPI_ASSERT(env, isArray, "Property actionButtons is expected to be an array."); + napi_get_array_length(env, actionButtons, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + for (size_t i = 0; i < length; i++) { + napi_value actionButton; + napi_get_element(env, actionButtons, i, &actionButton); + NAPI_CALL(env, napi_typeof(env, actionButton, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - NAPI_CALL(env, napi_has_named_property(env, actionButton, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, actionButton, "title", &titelActionButton); - NAPI_CALL(env, napi_typeof(env, titelActionButton, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, titelActionButton, str, STR_MAX_SIZE - 1, &strLen)); - title = str; - } + // title: string; + NAPI_CALL(env, napi_has_named_property(env, actionButton, "title", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, actionButton, "title", &titelActionButton); + NAPI_CALL(env, napi_typeof(env, titelActionButton, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, titelActionButton, str, STR_MAX_SIZE - 1, &strLen)); + title = str; + } else { + ANS_LOGE("Property title expected."); + return nullptr; + } - NAPI_CALL(env, napi_has_named_property(env, actionButton, "wantAgent", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, actionButton, "wantAgent", &wantAgentActionButton); - NAPI_CALL(env, napi_typeof(env, wantAgentActionButton, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - napi_unwrap(env, wantAgentActionButton, (void **)&wantAgentPtr); - if (wantAgentPtr == nullptr) { - return nullptr; - } - wantAgent = std::make_shared(*wantAgentPtr); + // wantAgent: WantAgent; + NAPI_CALL(env, napi_has_named_property(env, actionButton, "wantAgent", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, actionButton, "wantAgent", &wantAgentActionButton); + NAPI_CALL(env, napi_typeof(env, wantAgentActionButton, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + napi_unwrap(env, wantAgentActionButton, (void **)&wantAgentPtr); + if (wantAgentPtr == nullptr) { + ANS_LOGE("Invalid object wantAgent"); + return nullptr; } + wantAgent = std::make_shared(*wantAgentPtr); + } else { + ANS_LOGE("Property wantAgent expected."); + return nullptr; + } - std::vector> vec{nullptr}; + // extras?: {[key: string]: any}; - auto pActionButton = NotificationActionButton::Create( - nullptr, title, wantAgent, nullptr, NotificationConstant::ARCHIVE_ACTION_BUTTON, false, vec, false); - request.AddActionButton(pActionButton); - } + std::vector> vec; + auto pActionButton = NotificationActionButton::Create(nullptr, title, wantAgent); + request.AddActionButton(pActionButton); } return Common::NapiGetNull(env); @@ -2102,13 +2074,16 @@ napi_value GetNotificationContentType(const napi_env &env, const napi_value &res bool hasProperty = false; NAPI_CALL(env, napi_has_named_property(env, result, "contentType", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, result, "contentType", &contentResult); - NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, contentResult, &type); + if (!hasProperty) { + ANS_LOGE("Property contentType expected."); + return nullptr; } + napi_get_named_property(env, result, "contentType", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, contentResult, &type); + return Common::NapiGetNull(env); } @@ -2124,15 +2099,17 @@ napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &re NAPI_CALL(env, napi_has_named_property(env, result, "normal", &hasProperty)); if (hasProperty) { + napi_get_named_property(env, result, "normal", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr normalContent = std::make_shared(); if (normalContent == nullptr) { ANS_LOGE("normalContent is null"); return nullptr; } - napi_get_named_property(env, result, "normal", &contentResult); - NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + // title: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "title", &basicContentResult); @@ -2141,8 +2118,12 @@ napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &re NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); normalContent->SetTitle(str); ANS_LOGI("normal::title = %{public}s", str); + } else { + ANS_LOGE("Property title expected."); + return nullptr; } + // text: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "text", &basicContentResult); @@ -2151,8 +2132,12 @@ napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &re NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); normalContent->SetText(str); ANS_LOGI("normal::text = %{public}s", str); + } else { + ANS_LOGE("Property text expected."); + return nullptr; } + // additionalText?: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); @@ -2162,6 +2147,7 @@ napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &re normalContent->SetAdditionalText(str); ANS_LOGI("normal::additionalText = %{public}s", str); } + request.SetContent(std::make_shared(normalContent)); } @@ -2180,16 +2166,18 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value NAPI_CALL(env, napi_has_named_property(env, result, "longText", &hasProperty)); if (hasProperty) { + napi_get_named_property(env, result, "longText", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr longContent = std::make_shared(); if (longContent == nullptr) { ANS_LOGE("longContent is null"); return nullptr; } - napi_get_named_property(env, result, "longText", &contentResult); - NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + // title: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "title", &basicContentResult); @@ -2198,8 +2186,12 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); longContent->SetTitle(str); ANS_LOGI("longText::title = %{public}s", str); + } else { + ANS_LOGE("Property title expected."); + return nullptr; } + // text: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "text", &basicContentResult); @@ -2208,8 +2200,12 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); longContent->SetText(str); ANS_LOGI("longText::text = %{public}s", str); + } else { + ANS_LOGE("Property text expected."); + return nullptr; } + // additionalText?: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); @@ -2220,16 +2216,21 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value ANS_LOGI("longText::additionalText = %{public}s", str); } + // longText: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "longText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "longText", &longContentResult); NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, LONG_STR_MAX_SIZE - 1, &strLen)); longContent->SetLongText(str); ANS_LOGI("longText::longText = %{public}s", str); + } else { + ANS_LOGE("Property longText expected."); + return nullptr; } + // briefText: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "briefText", &longContentResult); @@ -2238,8 +2239,12 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); longContent->SetBriefText(str); ANS_LOGI("longText::briefText = %{public}s", str); + } else { + ANS_LOGE("Property briefText expected."); + return nullptr; } + // expandedTitle: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "expandedTitle", &longContentResult); @@ -2248,12 +2253,17 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); longContent->SetExpandedTitle(str); ANS_LOGI("longText::expandedTitle = %{public}s", str); + } else { + ANS_LOGE("Property expandedTitle expected."); + return nullptr; } + request.SetContent(std::make_shared(longContent)); } return Common::NapiGetNull(env); } + napi_value GetNotificationPictureContent(const napi_env &env, const napi_value &result, NotificationRequest &request) { ANS_LOGI("enter"); @@ -2268,16 +2278,18 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & NAPI_CALL(env, napi_has_named_property(env, result, "picture", &hasProperty)); if (hasProperty) { + napi_get_named_property(env, result, "picture", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr pictureContent = std::make_shared(); if (pictureContent == nullptr) { ANS_LOGE("pictureContent is null"); return nullptr; } - napi_get_named_property(env, result, "picture", &contentResult); - NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + // title: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "title", &basicContentResult); @@ -2286,8 +2298,12 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); pictureContent->SetTitle(str); ANS_LOGI("pictureText::title = %{public}s", str); + } else { + ANS_LOGE("Property title expected."); + return nullptr; } + // text: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "text", &basicContentResult); @@ -2296,8 +2312,12 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); pictureContent->SetText(str); ANS_LOGI("pictureText::text = %{public}s", str); + } else { + ANS_LOGE("Property text expected."); + return nullptr; } + // additionalText?: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); @@ -2308,17 +2328,7 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & ANS_LOGI("pictureText::additionalText = %{public}s", str); } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "pictureId", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "pictureId", &pictureContentResult); - NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int32_t pictureId = 0; - napi_get_value_int32(env, contentResult, &pictureId); - // pictureContent->SetLongText(str); //do C++没接口 - ANS_LOGI("pictureText::pictureId = %{public}d", pictureId); - } - + // briefText: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "briefText", &pictureContentResult); @@ -2327,8 +2337,12 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, str, STR_MAX_SIZE - 1, &strLen)); pictureContent->SetBriefText(str); ANS_LOGI("pictureText::briefText = %{public}s", str); + } else { + ANS_LOGE("Property briefText expected."); + return nullptr; } + // expandedTitle: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "expandedTitle", &pictureContentResult); @@ -2337,6 +2351,9 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, str, STR_MAX_SIZE - 1, &strLen)); pictureContent->SetExpandedTitle(str); ANS_LOGI("pictureText::expandedTitle = %{public}s", str); + } else { + ANS_LOGE("Property expandedTitle expected."); + return nullptr; } // bigPicture: image.PixelMap do @@ -2347,7 +2364,7 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & return Common::NapiGetNull(env); } -napi_value getMessageUser(const napi_env &env, const napi_value &senderResult, MessageUser &sender) +napi_value GetMessageUser(const napi_env &env, const napi_value &result, MessageUser &messageUser) { ANS_LOGI("enter"); napi_valuetype valuetype; @@ -2356,67 +2373,89 @@ napi_value getMessageUser(const napi_env &env, const napi_value &senderResult, M size_t strLen = 0; // name: string - NAPI_CALL(env, napi_has_named_property(env, senderResult, "name", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, result, "name", &hasProperty)); if (hasProperty) { napi_value nameResult; - napi_get_named_property(env, senderResult, "name", &nameResult); + napi_get_named_property(env, result, "name", &nameResult); NAPI_CALL(env, napi_typeof(env, nameResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); NAPI_CALL(env, napi_get_value_string_utf8(env, nameResult, str, STR_MAX_SIZE - 1, &strLen)); - sender.SetName(str); + messageUser.SetName(str); ANS_LOGI("MessageUser::name = %{public}s", str); + } else { + ANS_LOGE("Property name expected."); + return nullptr; } + // pixelMap: image.PixelMap do + // uri: string - NAPI_CALL(env, napi_has_named_property(env, senderResult, "uri", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, result, "uri", &hasProperty)); if (hasProperty) { napi_value uriResult; - napi_get_named_property(env, senderResult, "uri", &uriResult); + napi_get_named_property(env, result, "uri", &uriResult); NAPI_CALL(env, napi_typeof(env, uriResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); NAPI_CALL(env, napi_get_value_string_utf8(env, uriResult, str, STR_MAX_SIZE - 1, &strLen)); Uri uri(str); - sender.SetUri(uri); + messageUser.SetUri(uri); ANS_LOGI("MessageUser::uri = %{public}s", str); + } else { + ANS_LOGE("Property uri expected."); + return nullptr; } + // important: boolean - NAPI_CALL(env, napi_has_named_property(env, senderResult, "important", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, result, "important", &hasProperty)); if (hasProperty) { napi_value importantResult; - napi_get_named_property(env, senderResult, "important", &importantResult); + napi_get_named_property(env, result, "important", &importantResult); NAPI_CALL(env, napi_typeof(env, importantResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); bool important = false; napi_get_value_bool(env, importantResult, &important); - sender.SetUserAsImportant(important); + messageUser.SetUserAsImportant(important); ANS_LOGI("MessageUser::important = %{public}d", important); + } else { + ANS_LOGE("Property important expected."); + return nullptr; } + // machine: boolean - NAPI_CALL(env, napi_has_named_property(env, senderResult, "machine", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, result, "machine", &hasProperty)); if (hasProperty) { napi_value machineResult; - napi_get_named_property(env, senderResult, "machine", &machineResult); + napi_get_named_property(env, result, "machine", &machineResult); NAPI_CALL(env, napi_typeof(env, machineResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); bool machine = false; napi_get_value_bool(env, machineResult, &machine); - sender.SetMachine(machine); + messageUser.SetMachine(machine); ANS_LOGI("MessageUser::machine = %{public}d", machine); + } else { + ANS_LOGE("Property machine expected."); + return nullptr; } + // key: string - NAPI_CALL(env, napi_has_named_property(env, senderResult, "key", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, result, "key", &hasProperty)); if (hasProperty) { napi_value keyResult; - napi_get_named_property(env, senderResult, "key", &keyResult); + napi_get_named_property(env, result, "key", &keyResult); NAPI_CALL(env, napi_typeof(env, keyResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); NAPI_CALL(env, napi_get_value_string_utf8(env, keyResult, str, STR_MAX_SIZE - 1, &strLen)); - sender.SetKey(str); + messageUser.SetKey(str); ANS_LOGI("MessageUser::key = %{public}s", str); + } else { + ANS_LOGE("Property key expected."); + return nullptr; } + return Common::NapiGetNull(env); } -napi_value getConversationalMessage(const napi_env &env, const napi_value &conversationalMessage, + +napi_value GetConversationalMessage(const napi_env &env, const napi_value &conversationalMessage, std::shared_ptr &message) { ANS_LOGI("enter"); @@ -2424,23 +2463,26 @@ napi_value getConversationalMessage(const napi_env &env, const napi_value &conve bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; - std::string text; int64_t timestamp = 0; std::string mimeType; std::string uri; MessageUser sender; + // text: string NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "text", &hasProperty)); if (hasProperty) { napi_value textResult; - napi_get_named_property(env, conversationalMessage, "title", &textResult); + napi_get_named_property(env, conversationalMessage, "text", &textResult); NAPI_CALL(env, napi_typeof(env, textResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); 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); + } else { + ANS_LOGE("Property text expected."); } + // timestamp: number NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "timestamp", &hasProperty)); if (hasProperty) { @@ -2450,7 +2492,10 @@ napi_value getConversationalMessage(const napi_env &env, const napi_value &conve NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int64(env, timestampResult, ×tamp); ANS_LOGI("conversationalMessage::timestamp = %{public}lld", timestamp); + } else { + ANS_LOGE("Property timestamp expected."); } + // mimeType: string NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "mimeType", &hasProperty)); if (hasProperty) { @@ -2461,7 +2506,10 @@ napi_value getConversationalMessage(const napi_env &env, const napi_value &conve NAPI_CALL(env, napi_get_value_string_utf8(env, mimeTypeResult, str, STR_MAX_SIZE - 1, &strLen)); mimeType = str; ANS_LOGI("conversationalMessage::mimeType = %{public}s", str); + } else { + ANS_LOGE("Property mimeType expected."); } + // uri: string NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "uri", &hasProperty)); if (hasProperty) { @@ -2472,7 +2520,10 @@ napi_value getConversationalMessage(const napi_env &env, const napi_value &conve NAPI_CALL(env, napi_get_value_string_utf8(env, uriResult, str, STR_MAX_SIZE - 1, &strLen)); uri = str; ANS_LOGI("conversationalMessage::uri = %{public}s", str); + } else { + ANS_LOGE("Property uri expected."); } + // sender: MessageUser NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "sender", &hasProperty)); if (hasProperty) { @@ -2480,19 +2531,21 @@ napi_value getConversationalMessage(const napi_env &env, const napi_value &conve napi_get_named_property(env, conversationalMessage, "sender", &senderResult); NAPI_CALL(env, napi_typeof(env, senderResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - if (!getMessageUser(env, senderResult, sender)) { + if (!GetMessageUser(env, senderResult, sender)) { return nullptr; } + } else { + ANS_LOGE("Property sender expected."); } - std::shared_ptr messagePtr = - std::make_shared(text, timestamp, sender); - if (messagePtr == nullptr) { - ANS_LOGE("conversationalMessage is null"); + + message = std::make_shared(text, timestamp, sender); + if (message == nullptr) { + ANS_LOGE("Failed to create NotificationConversationalMessage object."); return nullptr; } std::shared_ptr uriPtr = std::make_shared(uri); - messagePtr->SetData(mimeType, uriPtr); - message = messagePtr; + message->SetData(mimeType, uriPtr); + return Common::NapiGetNull(env); } @@ -2512,7 +2565,6 @@ napi_value GetNotificationConversationalContent( NAPI_CALL(env, napi_has_named_property(env, result, "conversational", &hasProperty)); if (hasProperty) { - napi_get_named_property(env, result, "conversational", &contentResult); NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); @@ -2524,9 +2576,12 @@ napi_value GetNotificationConversationalContent( napi_get_named_property(env, contentResult, "user", &userResult); NAPI_CALL(env, napi_typeof(env, userResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - if (!getMessageUser(env, userResult, user)) { + if (!GetMessageUser(env, userResult, user)) { return nullptr; } + } else { + ANS_LOGE("Property user expected."); + return nullptr; } std::shared_ptr conversationalContent = @@ -2535,6 +2590,8 @@ napi_value GetNotificationConversationalContent( ANS_LOGE("conversationalContent is null"); return nullptr; } + + // title: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "title", &basicContentResult); @@ -2543,8 +2600,12 @@ napi_value GetNotificationConversationalContent( NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); conversationalContent->SetTitle(str); ANS_LOGI("conversationalText::title = %{public}s", str); + } else { + ANS_LOGE("Property title expected."); + return nullptr; } + // text: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "text", &basicContentResult); @@ -2553,8 +2614,12 @@ napi_value GetNotificationConversationalContent( NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); conversationalContent->SetText(str); ANS_LOGI("conversationalText::text = %{public}s", str); + } else { + ANS_LOGE("Property text expected."); + return nullptr; } + // additionalText?: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); @@ -2565,6 +2630,7 @@ napi_value GetNotificationConversationalContent( ANS_LOGI("conversationalText::additionalText = %{public}s", str); } + // conversationTitle: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationTitle", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "conversationTitle", &conversationalContentResult); @@ -2574,8 +2640,12 @@ napi_value GetNotificationConversationalContent( env, napi_get_value_string_utf8(env, conversationalContentResult, str, STR_MAX_SIZE - 1, &strLen)); conversationalContent->SetConversationTitle(str); ANS_LOGI("conversationalText::conversationTitle = %{public}s", str); + } else { + ANS_LOGE("Property conversationTitle expected."); + return nullptr; } + // conversationGroup: boolean; NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationGroup", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "conversationGroup", &conversationalContentResult); @@ -2585,36 +2655,43 @@ napi_value GetNotificationConversationalContent( napi_get_value_bool(env, conversationalContentResult, &conversationGroup); conversationalContent->SetConversationGroup(conversationGroup); ANS_LOGI("conversationalText::conversationGroup = %{public}d", conversationGroup); + } else { + ANS_LOGE("Property conversationGroup expected."); + return nullptr; } + // messages: Array; NAPI_CALL(env, napi_has_named_property(env, contentResult, "messages", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "messages", &conversationalContentResult); bool isArray = false; napi_is_array(env, conversationalContentResult, &isArray); - if (isArray) { - uint32_t length = 0; - napi_get_array_length(env, conversationalContentResult, &length); - NAPI_ASSERT(env, length > 0, "The array is empty."); - for (size_t i = 0; i < length; i++) { - napi_value conversationalMessage; - napi_get_element(env, conversationalContentResult, i, &conversationalMessage); - NAPI_CALL(env, napi_typeof(env, conversationalMessage, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - std::shared_ptr message = nullptr; - if (!getConversationalMessage(env, conversationalMessage, message)) { - return nullptr; - } - conversationalContent->AddConversationalMessage(message); + NAPI_ASSERT(env, isArray, "Property messages is expected to be an array."); + uint32_t length = 0; + napi_get_array_length(env, conversationalContentResult, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + for (size_t i = 0; i < length; i++) { + napi_value conversationalMessage; + napi_get_element(env, conversationalContentResult, i, &conversationalMessage); + NAPI_CALL(env, napi_typeof(env, conversationalMessage, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr message = nullptr; + if (!GetConversationalMessage(env, conversationalMessage, message)) { + return nullptr; } - } else { - return nullptr; + conversationalContent->AddConversationalMessage(message); } + } else { + ANS_LOGE("Property messages expected."); + return nullptr; } + request.SetContent(std::make_shared(conversationalContent)); } + return Common::NapiGetNull(env); } + napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value &result, NotificationRequest &request) { ANS_LOGI("enter"); @@ -2627,12 +2704,18 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value NAPI_CALL(env, napi_has_named_property(env, result, "multiLine", &hasProperty)); if (hasProperty) { - std::shared_ptr multiLineContent = - std::make_shared(); napi_get_named_property(env, result, "multiLine", &contentResult); NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr multiLineContent = + std::make_shared(); + if (multiLineContent == nullptr) { + ANS_LOGE("multiLineContent is null"); + return nullptr; + } + + // title: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "title", &basicContentResult); @@ -2641,8 +2724,12 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); multiLineContent->SetTitle(str); ANS_LOGI("multiLine::title = %{public}s", str); + } else { + ANS_LOGE("Property title expected."); + return nullptr; } + // text: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "text", &basicContentResult); @@ -2651,8 +2738,12 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); multiLineContent->SetText(str); ANS_LOGI("multiLine::text = %{public}s", str); + } else { + ANS_LOGE("Property text expected."); + return nullptr; } + // additionalText?: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); @@ -2663,6 +2754,7 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value ANS_LOGI("multiLine::additionalText = %{public}s", str); } + // briefText: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "briefText", &multiLineContentResult); @@ -2671,8 +2763,12 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); multiLineContent->SetBriefText(str); ANS_LOGI("multiLine: briefText = %{public}s", str); + } else { + ANS_LOGE("Property briefText expected."); + return nullptr; } + // longTitle: string; NAPI_CALL(env, napi_has_named_property(env, contentResult, "longTitle", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "longTitle", &multiLineContentResult); @@ -2681,13 +2777,20 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); multiLineContent->SetExpandedTitle(str); ANS_LOGI("multiLine: longTitle = %{public}s", str); + } else { + ANS_LOGE("Property longTitle expected."); + return nullptr; } + // lines: Array; NAPI_CALL(env, napi_has_named_property(env, contentResult, "lines", &hasProperty)); if (hasProperty) { if (GetNotificationMultiLineContentLines(env, contentResult, multiLineContent) == nullptr) { return nullptr; } + } else { + ANS_LOGE("Property lines expected."); + return nullptr; } request.SetContent(std::make_shared(multiLineContent)); @@ -2710,24 +2813,24 @@ napi_value GetNotificationMultiLineContentLines(const napi_env &env, const napi_ napi_get_named_property(env, result, "lines", &multilines); napi_is_array(env, multilines, &isArray); - if (isArray) { - napi_get_array_length(env, multilines, &length); - NAPI_ASSERT(env, length > 0, "The array is empty."); - for (size_t i = 0; i < length; i++) { - napi_value line; - napi_get_element(env, multilines, i, &line); - NAPI_CALL(env, napi_typeof(env, line, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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_ASSERT(env, isArray, "Property lines is expected to be an array."); + + napi_get_array_length(env, multilines, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + for (size_t i = 0; i < length; i++) { + napi_value line; + napi_get_element(env, multilines, i, &line); + NAPI_CALL(env, napi_typeof(env, line, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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); } return Common::NapiGetNull(env); } -napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &slot, const napi_value &result) +napi_value Common::GetNotificationSlot(const napi_env &env, const napi_value &value, NotificationSlot &slot) { ANS_LOGI("enter"); napi_value nobj = nullptr; @@ -2738,11 +2841,12 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl // type: notification.SlotType int slotType = 0; - napi_get_named_property(env, result, "type", &nobj); + NAPI_CALL(env, napi_has_named_property(env, value, "type", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property type expected."); + napi_get_named_property(env, value, "type", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, nobj, &slotType); - enum NotificationConstant::SlotType outType; if (!SlotTypeJSToC(SlotType(slotType), outType)) { return nullptr; @@ -2750,23 +2854,28 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl slot.SetType(outType); // level?: number - NAPI_CALL(env, napi_has_named_property(env, result, "level", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "level", &hasProperty)); if (hasProperty) { - int level = 0; - napi_get_named_property(env, result, "level", &nobj); + int inLevel = 0; + napi_get_named_property(env, value, "level", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, nobj, &level); - ANS_LOGI("level is: %{public}d", level); - slot.SetLevel(NotificationSlot::NotificationLevel(level)); + napi_get_value_int32(env, nobj, &inLevel); + ANS_LOGI("level is: %{public}d", inLevel); + + NotificationSlot::NotificationLevel outLevel{NotificationSlot::NotificationLevel::LEVEL_NONE}; + if (!SlotLevelJSToC(SlotLevel(inLevel), outLevel)) { + return nullptr; + } + slot.SetLevel(outLevel); } // desc?: string - NAPI_CALL(env, napi_has_named_property(env, result, "desc", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "desc", &hasProperty)); if (hasProperty) { std::string desc; char str[STR_MAX_SIZE] = {0}; - napi_get_named_property(env, result, "desc", &nobj); + napi_get_named_property(env, value, "desc", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); NAPI_CALL(env, napi_get_value_string_utf8(env, nobj, str, STR_MAX_SIZE - 1, &strLen)); @@ -2776,10 +2885,10 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl } // showBadgeFlag?: boolean - NAPI_CALL(env, napi_has_named_property(env, result, "showBadgeFlag", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "showBadgeFlag", &hasProperty)); if (hasProperty) { bool showBadgeFlag = false; - napi_get_named_property(env, result, "showBadgeFlag", &nobj); + napi_get_named_property(env, value, "showBadgeFlag", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); napi_get_value_bool(env, nobj, &showBadgeFlag); @@ -2788,10 +2897,10 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl } // bypassDnd?: boolean - NAPI_CALL(env, napi_has_named_property(env, result, "bypassDnd", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "bypassDnd", &hasProperty)); if (hasProperty) { bool bypassDnd = false; - napi_get_named_property(env, result, "bypassDnd", &nobj); + napi_get_named_property(env, value, "bypassDnd", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); napi_get_value_bool(env, nobj, &bypassDnd); @@ -2800,10 +2909,10 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl } // lockscreenVisibility?: number - NAPI_CALL(env, napi_has_named_property(env, result, "lockscreenVisibility", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "lockscreenVisibility", &hasProperty)); if (hasProperty) { int lockscreenVisibility = 0; - napi_get_named_property(env, result, "lockscreenVisibility", &nobj); + napi_get_named_property(env, value, "lockscreenVisibility", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, nobj, &lockscreenVisibility); @@ -2812,10 +2921,10 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl } // vibrationEnabled?: boolean - NAPI_CALL(env, napi_has_named_property(env, result, "vibrationEnabled", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "vibrationEnabled", &hasProperty)); if (hasProperty) { bool vibrationEnabled = false; - napi_get_named_property(env, result, "vibrationEnabled", &nobj); + napi_get_named_property(env, value, "vibrationEnabled", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); napi_get_value_bool(env, nobj, &vibrationEnabled); @@ -2824,11 +2933,11 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl } // sound?: string - NAPI_CALL(env, napi_has_named_property(env, result, "sound", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "sound", &hasProperty)); if (hasProperty) { std::string sound; char str[STR_MAX_SIZE] = {0}; - napi_get_named_property(env, result, "sound", &nobj); + napi_get_named_property(env, value, "sound", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); NAPI_CALL(env, napi_get_value_string_utf8(env, nobj, str, STR_MAX_SIZE - 1, &strLen)); @@ -2838,10 +2947,10 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl } // lightEnabled?: boolean - NAPI_CALL(env, napi_has_named_property(env, result, "lightEnabled", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "lightEnabled", &hasProperty)); if (hasProperty) { bool lightEnabled = false; - napi_get_named_property(env, result, "lightEnabled", &nobj); + napi_get_named_property(env, value, "lightEnabled", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); napi_get_value_bool(env, nobj, &lightEnabled); @@ -2850,10 +2959,10 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl } // lightColor?: number - NAPI_CALL(env, napi_has_named_property(env, result, "lightColor", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "lightColor", &hasProperty)); if (hasProperty) { int lightColor = 0; - napi_get_named_property(env, result, "lightColor", &nobj); + napi_get_named_property(env, value, "lightColor", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, nobj, &lightColor); @@ -2862,29 +2971,90 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl } // vibrationValues?: Array - NAPI_CALL(env, napi_has_named_property(env, result, "vibrationValues", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "vibrationValues", &hasProperty)); if (hasProperty) { bool isArray = false; - napi_get_named_property(env, result, "vibrationValues", &nobj); + napi_get_named_property(env, value, "vibrationValues", &nobj); napi_is_array(env, nobj, &isArray); - if (isArray) { - napi_get_array_length(env, nobj, &length); - std::vector vibrationValues; - for (size_t i = 0; i < length; i++) { - napi_value nVibrationValue; - int64_t vibrationValue = 0; - napi_get_element(env, nobj, i, &nVibrationValue); - NAPI_CALL(env, napi_typeof(env, nVibrationValue, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int64(env, nVibrationValue, &vibrationValue); - ANS_LOGI("vibrationValue is: %{public}lld", vibrationValue); - vibrationValues.emplace_back(vibrationValue); - } - if (vibrationValues.size() > 0) { - slot.SetVibrationStyle(vibrationValues); - } + NAPI_ASSERT(env, isArray, "Property vibrationValues is expected to be an array."); + napi_get_array_length(env, nobj, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + std::vector vibrationValues; + for (size_t i = 0; i < length; i++) { + napi_value nVibrationValue; + int64_t vibrationValue = 0; + napi_get_element(env, nobj, i, &nVibrationValue); + NAPI_CALL(env, napi_typeof(env, nVibrationValue, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int64(env, nVibrationValue, &vibrationValue); + ANS_LOGI("vibrationValue is: %{public}lld", vibrationValue); + vibrationValues.emplace_back(vibrationValue); } + slot.SetVibrationStyle(vibrationValues); + } + return NapiGetNull(env); +} + +napi_value Common::GetBundleOption(const napi_env &env, const napi_value &value, BundleOption &option) +{ + ANS_LOGI("enter"); + + bool hasProperty{false}; + napi_valuetype valuetype; + napi_value result; + + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + // bundle: string; + NAPI_CALL(env, napi_has_named_property(env, value, "bundle", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property bundle expected."); + napi_get_named_property(env, value, "bundle", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); + option.bundle = str; + + // uid?: number; + if (hasProperty) { + NAPI_CALL(env, napi_has_named_property(env, value, "uid", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property uid expected."); + napi_get_named_property(env, value, "uid", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, result, &option.uid); + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationKey(const napi_env &env, const napi_value &value, NotificationKey &key) +{ + ANS_LOGI("enter"); + + bool hasProperty{false}; + napi_valuetype valuetype; + napi_value result; + + // id: number; + NAPI_CALL(env, napi_has_named_property(env, value, "id", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property id expected."); + napi_get_named_property(env, value, "id", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, result, &key.id); + + // lable?: string; + NAPI_CALL(env, napi_has_named_property(env, value, "label", &hasProperty)); + if (hasProperty) { + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + napi_get_named_property(env, value, "label", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); + key.label = str; } + return NapiGetNull(env); } @@ -2910,7 +3080,7 @@ bool Common::ContentTypeJSToC(const enum ContentType &inType, enum NotificationC outType = NotificationContent::Type::MEDIA; break; default: - ANS_LOGI("contentType is error"); + ANS_LOGE("ContentType %{public}d is an invalid value", inType); return false; } return true; @@ -2938,7 +3108,7 @@ bool Common::ContentTypeCToJS(const enum NotificationContent::Type &inType, enum outType = ContentType::NOTIFICATION_CONTENT_MEDIA; break; default: - ANS_LOGI("contentType is error"); + ANS_LOGE("ContentType %{public}d is an invalid value", inType); return false; } return true; @@ -2961,7 +3131,7 @@ bool Common::SlotTypeJSToC(const enum SlotType &inType, enum NotificationConstan outType = NotificationConstant::SlotType::OTHER; break; default: - ANS_LOGI("slotType is error"); + ANS_LOGE("SlotType %{public}d is an invalid value", inType); return false; } return true; @@ -2986,7 +3156,58 @@ bool Common::SlotTypeCToJS(const enum NotificationConstant::SlotType &inType, en outType = SlotType::OTHER_TYPES; break; default: - ANS_LOGI("slotType is error"); + ANS_LOGE("SlotType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool Common::SlotLevelJSToC(const SlotLevel &inLevel, NotificationSlot::NotificationLevel &outLevel) +{ + switch (inLevel) { + case SlotLevel::LEVEL_NONE: + outLevel = NotificationSlot::NotificationLevel::LEVEL_NONE; + break; + case SlotLevel::LEVEL_MIN: + outLevel = NotificationSlot::NotificationLevel::LEVEL_MIN; + break; + case SlotLevel::LEVEL_LOW: + outLevel = NotificationSlot::NotificationLevel::LEVEL_LOW; + break; + case SlotLevel::LEVEL_DEFAULT: + outLevel = NotificationSlot::NotificationLevel::LEVEL_DEFAULT; + break; + case SlotLevel::LEVEL_HIGH: + outLevel = NotificationSlot::NotificationLevel::LEVEL_HIGH; + break; + default: + ANS_LOGE("SlotLevel %{public}d is an invalid value", inLevel); + return false; + } + return true; +} + +bool Common::SlotLevelCToJS(const NotificationSlot::NotificationLevel &inLevel, SlotLevel &outLevel) +{ + switch (inLevel) { + case NotificationSlot::NotificationLevel::LEVEL_NONE: + case NotificationSlot::NotificationLevel::LEVEL_UNDEFINED: + outLevel = SlotLevel::LEVEL_NONE; + break; + case NotificationSlot::NotificationLevel::LEVEL_MIN: + outLevel = SlotLevel::LEVEL_MIN; + break; + case NotificationSlot::NotificationLevel::LEVEL_LOW: + outLevel = SlotLevel::LEVEL_LOW; + break; + case NotificationSlot::NotificationLevel::LEVEL_DEFAULT: + outLevel = SlotLevel::LEVEL_DEFAULT; + break; + case NotificationSlot::NotificationLevel::LEVEL_HIGH: + outLevel = SlotLevel::LEVEL_HIGH; + break; + default: + ANS_LOGE("SlotLevel %{public}d is an invalid value", inLevel); return false; } return true; @@ -3023,7 +3244,7 @@ bool Common::ReasonCToJS(const int &inType, int &outType) outType = NotificationReason::APP_CANCEL_REASON_OTHER; break; default: - ANS_LOGI("reason is error"); + ANS_LOGE("Reason %{public}d is an invalid value", inType); return false; } return true; @@ -3048,7 +3269,7 @@ bool Common::DisturbModeJSToC(const enum DisturbMode &inType, enum NotificationC outType = NotificationConstant::DisturbMode::ALLOW_ALARMS; break; default: - ANS_LOGI("disturbMode is error"); + ANS_LOGE("DisturbMode %{public}d is an invalid value", inType); return false; } return true; diff --git a/interfaces/kits/napi/ans/src/constant.cpp b/interfaces/kits/napi/ans/src/constant.cpp index 7744cfa77..e11b9dfd3 100644 --- a/interfaces/kits/napi/ans/src/constant.cpp +++ b/interfaces/kits/napi/ans/src/constant.cpp @@ -78,6 +78,27 @@ napi_value SlotTypeInit(napi_env env, napi_value exports) return exports; } +napi_value SlotLevelInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, SlotLevel::LEVEL_NONE, "LEVEL_NONE"); + SetNamedPropertyByInteger(env, obj, SlotLevel::LEVEL_MIN, "LEVEL_MIN"); + SetNamedPropertyByInteger(env, obj, SlotLevel::LEVEL_LOW, "LEVEL_LOW"); + SetNamedPropertyByInteger(env, obj, SlotLevel::LEVEL_DEFAULT, "LEVEL_DEFAULT"); + SetNamedPropertyByInteger(env, obj, SlotLevel::LEVEL_HIGH, "LEVEL_HIGH"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("SlotLevel", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + napi_value SemanticActionButtonInit(napi_env env, napi_value exports) { ANS_LOGI("%{public}s, called", __func__); @@ -191,6 +212,7 @@ napi_value ConstantInit(napi_env env, napi_value exports) { NotificationReasonInit(env, exports); SlotTypeInit(env, exports); + SlotLevelInit(env, exports); SemanticActionButtonInit(env, exports); InputsSourceInit(env, exports); DisturbModeInit(env, exports); diff --git a/interfaces/kits/napi/ans/src/create_subscriber.cpp b/interfaces/kits/napi/ans/src/create_subscriber.cpp index 639da8fa8..e81f74957 100644 --- a/interfaces/kits/napi/ans/src/create_subscriber.cpp +++ b/interfaces/kits/napi/ans/src/create_subscriber.cpp @@ -51,7 +51,7 @@ napi_value SetSubscribeCallbackData(const napi_env &env, const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason, napi_value &result) { - ANS_LOGI("SetSubscribeCallbackData start"); + ANS_LOGI("enter"); if (request == nullptr) { ANS_LOGE("request is null"); return Common::NapiGetboolean(env, false); @@ -106,7 +106,7 @@ void SubscriberInstance::OnCanceled(const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason) { - ANS_LOGI("OnCanceled start"); + ANS_LOGI("enter"); if (canceCallbackInfo_.ref == nullptr) { ANS_LOGI("cancel callback unset"); @@ -179,7 +179,7 @@ void SubscriberInstance::OnConsumed(const std::shared_ptr &request, const std::shared_ptr &sortingMap) { - ANS_LOGI("OnConsumed start"); + ANS_LOGI("enter"); if (consumeCallbackInfo_.ref == nullptr) { ANS_LOGI("consume callback unset"); @@ -246,7 +246,7 @@ void SubscriberInstance::OnConsumed(const std::shared_ptr &sortingMap) { - ANS_LOGI("OnUpdate start"); + ANS_LOGI("enter"); if (updateCallbackInfo_.ref == nullptr) { ANS_LOGI("update callback unset"); @@ -302,7 +302,7 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult result) { - ANS_LOGI("OnSubscribeResult start"); + ANS_LOGI("enter"); if (subscribeCallbackInfo_.ref == nullptr) { ANS_LOGI("subscribe callback unset"); @@ -348,7 +348,7 @@ void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) { - ANS_LOGI("OnUnsubscribeResult start"); + ANS_LOGI("enter"); if (unsubscribeCallbackInfo_.ref == nullptr) { ANS_LOGI("unsubscribe callback unset"); @@ -394,7 +394,7 @@ void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResu void SubscriberInstance::OnDied() { - ANS_LOGI("OnDied start"); + ANS_LOGI("enter"); if (dieCallbackInfo_.ref == nullptr) { ANS_LOGE("die callback unset"); @@ -436,7 +436,7 @@ void SubscriberInstance::OnDied() void SubscriberInstance::OnDisturbModeChanged(int disturbMode) { - ANS_LOGI("OnDisturbModeChanged start"); + ANS_LOGI("enter"); if (disturbModeCallbackInfo_.ref == nullptr) { ANS_LOGI("disturbModeChange callback unset"); @@ -546,7 +546,7 @@ void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string napi_value ParseParametersByOn(const napi_env &env, const size_t &argc, const napi_value (&argv)[ON_MAX_PARA], std::string &type, napi_ref &callback) { - ANS_LOGI("napi_value ParseParametersByOn start"); + ANS_LOGI("enter"); napi_valuetype valuetype; size_t strLen = 0; char str[STR_MAX_SIZE] = {0}; @@ -574,7 +574,7 @@ napi_value ParseParametersByOn(const napi_env &env, const size_t &argc, const na napi_value On(napi_env env, napi_callback_info info) { - ANS_LOGI("On start"); + ANS_LOGI("enter"); size_t argc = ON_MAX_PARA; napi_value argv[ON_MAX_PARA]; @@ -626,7 +626,7 @@ napi_value On(napi_env env, napi_callback_info info) napi_value ParseParametersByOff( const napi_env &env, const size_t &argc, const napi_value (&argv)[OFF_MAX_PARA], std::string &type) { - ANS_LOGI("napi_value ParseParametersByOff start"); + ANS_LOGI("enter"); napi_valuetype valuetype; size_t strLen = 0; char str[STR_MAX_SIZE] = {0}; @@ -649,7 +649,7 @@ napi_value ParseParametersByOff( napi_value Off(napi_env env, napi_callback_info info) { - ANS_LOGI("Off start"); + ANS_LOGI("enter"); size_t argc = OFF_MAX_PARA; napi_value argv[OFF_MAX_PARA]; @@ -702,7 +702,7 @@ napi_value Off(napi_env env, napi_callback_info info) napi_value CreateSubscriber(napi_env env, napi_callback_info info) { - ANS_LOGI("CreateSubscriber start"); + ANS_LOGI("enter"); size_t argc = 0; napi_value argv[1]; @@ -716,7 +716,7 @@ napi_value CreateSubscriber(napi_env env, napi_callback_info info) napi_value SubscriberConstructor(napi_env env, napi_callback_info info) { - ANS_LOGI("SubscriberConstructor start"); + ANS_LOGI("enter"); size_t argc = 0; napi_value argv[1]; @@ -752,7 +752,7 @@ napi_value SubscriberConstructor(napi_env env, napi_callback_info info) bool CreateSubscriberInstanceRecord(SubscriberInstance **subscriber) { - ANS_LOGI("CreateSubscriberInstanceRecord start"); + ANS_LOGI("enter"); *subscriber = new (std::nothrow) SubscriberInstance(); @@ -769,7 +769,7 @@ bool CreateSubscriberInstanceRecord(SubscriberInstance **subscriber) bool AddAsyncCallbackInfo(SubscriberInstance *subscriber, AsyncCallbackInfoOn *asynccallbackinfo) { - ANS_LOGI("AddAsyncCallbackInfo start"); + ANS_LOGI("enter"); if (subscriber == nullptr) { ANS_LOGE("subscriber is null"); @@ -804,7 +804,7 @@ bool AddAsyncCallbackInfo(SubscriberInstance *subscriber, AsyncCallbackInfoOn *a bool DelAsyncCallbackInfo(SubscriberInstance *subscriber, const std::string &type) { - ANS_LOGI("DelSubscriberInstance start"); + ANS_LOGI("enter"); if (subscriber == nullptr) { ANS_LOGE("subscriber is null"); @@ -849,7 +849,7 @@ bool DelAsyncCallbackInfo(SubscriberInstance *subscriber, const std::string &typ bool HasNotificationSubscriber(SubscriberInstance *subscriber) { - ANS_LOGI("HasNotificationSubscriber start"); + ANS_LOGI("enter"); if (subscriber == nullptr) { ANS_LOGE("subscriber is null"); @@ -857,7 +857,6 @@ bool HasNotificationSubscriber(SubscriberInstance *subscriber) } std::lock_guard lock(mutex_); - auto infoItem = g_SubscriberInstances.find(subscriber); if (infoItem != g_SubscriberInstances.end()) { return true; @@ -869,7 +868,7 @@ bool HasNotificationSubscriber(SubscriberInstance *subscriber) napi_value NotificationSubscriberInit(napi_env env, napi_value exports) { - ANS_LOGI("NotificationSubscriberInit start"); + ANS_LOGI("enter"); napi_property_descriptor properties[] = { DECLARE_NAPI_FUNCTION("on", On), diff --git a/interfaces/kits/napi/ans/src/get_active.cpp b/interfaces/kits/napi/ans/src/get_active.cpp index 28ab27097..09983eb20 100644 --- a/interfaces/kits/napi/ans/src/get_active.cpp +++ b/interfaces/kits/napi/ans/src/get_active.cpp @@ -23,18 +23,18 @@ const int ACTIVE_OR_NUMS_MAX_PARA = 1; struct AsyncCallbackInfoActive { napi_env env; napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - std::vector strValue; - bool isCallback = false; napi_value result = nullptr; - int errorCode = 0; + CallbackPromiseInfo info; }; -napi_value ParseParametersByAllActive(const napi_env &env, const napi_value (&argv)[ALL_ACTIVE_MAX_PARA], - const size_t &argc, std::vector &strValue, napi_ref &callback) +napi_value ParseParametersByAllActive(const napi_env &env, const napi_callback_info &info, napi_ref &callback) { - ANS_LOGI("ParseParametersByAllActive start"); + ANS_LOGI("enter"); + + size_t argc = ALL_ACTIVE_MAX_PARA; + napi_value argv[ALL_ACTIVE_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); if (argc >= ALL_ACTIVE_MAX_PARA) { napi_valuetype valuetype; @@ -47,10 +47,14 @@ napi_value ParseParametersByAllActive(const napi_env &env, const napi_value (&ar return Common::NapiGetNull(env); } -napi_value ParseParameters( - const napi_env &env, const napi_value (&argv)[ACTIVE_OR_NUMS_MAX_PARA], const size_t &argc, napi_ref &callback) +napi_value ParseParametersByGetActive(const napi_env &env, const napi_callback_info &info, napi_ref &callback) { - ANS_LOGI("ParseParameters start"); + ANS_LOGI("enter"); + + size_t argc = ACTIVE_OR_NUMS_MAX_PARA; + napi_value argv[ACTIVE_OR_NUMS_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); if (argc >= ACTIVE_OR_NUMS_MAX_PARA) { napi_valuetype valuetype; @@ -59,46 +63,26 @@ napi_value ParseParameters( NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); napi_create_reference(env, argv[0], 1, &callback); } - return Common::NapiGetNull(env); -} -void PaddingAsyncCallbackInfoIs( - const napi_env &env, AsyncCallbackInfoActive *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) -{ - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); - - if (callback) { - asynccallbackinfo->callback = callback; - asynccallbackinfo->isCallback = true; - } else { - napi_deferred deferred = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; - } + return Common::NapiGetNull(env); } napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) { - ANS_LOGI("GetAllActiveNotifications start"); + ANS_LOGI("enter"); - size_t argc = ALL_ACTIVE_MAX_PARA; - napi_value argv[ALL_ACTIVE_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); napi_ref callback = nullptr; - - std::vector hashcode; - if (ParseParametersByAllActive(env, argv, argc, hashcode, callback) == nullptr) { + if (ParseParametersByAllActive(env, info, callback) == nullptr) { return Common::JSParaError(env, callback); } - ANS_LOGI("GetAllActiveNotifications hashcode.size = %{public}d", hashcode.size()); AsyncCallbackInfoActive *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr, .strValue = hashcode}; - + new (std::nothrow) AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "getAllActiveNotifications", NAPI_AUTO_LENGTH, &resourceName); @@ -110,37 +94,33 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) ANS_LOGI("GetAllActiveNotifications napi_create_async_work start"); AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; - std::vector> notification; - if (asynccallbackinfo->strValue.size() > 0) { - asynccallbackinfo->errorCode = - NotificationHelper::GetAllActiveNotifications(asynccallbackinfo->strValue, notification); - } else { - asynccallbackinfo->errorCode = NotificationHelper::GetAllActiveNotifications(notification); + std::vector> notifications; + asynccallbackinfo->info.errorCode = NotificationHelper::GetAllActiveNotifications(notifications); + if (asynccallbackinfo->info.errorCode != ERR_OK) { + asynccallbackinfo->result = Common::NapiGetNull(env); + return; } - - if (asynccallbackinfo->errorCode == ERR_OK) { - napi_value arr; - int count = 0; - napi_create_array(env, &arr); - for (auto vec : notification) { - if (vec) { - napi_value result; - napi_create_object(env, &result); - if (Common::SetNotification( - env, static_cast(vec.GetRefPtr()), result)) { - napi_set_element(env, arr, count, result); - count++; - } - } + napi_value arr; + int count = 0; + napi_create_array(env, &arr); + for (auto vec : notifications) { + if (!vec) { + ANS_LOGW("Invalid Notification object ptr"); + continue; } - if (count > 0) { - ANS_LOGI("GetAllActiveNotifications count = %{public}d", count); - asynccallbackinfo->result = arr; - } else { - asynccallbackinfo->errorCode = ERROR; - asynccallbackinfo->result = Common::NapiGetNull(env); + napi_value result; + napi_create_object(env, &result); + if (!Common::SetNotification(env, vec.GetRefPtr(), result)) { + ANS_LOGW("Set Notification object failed"); + continue; } - } else { + napi_set_element(env, arr, count, result); + count++; + } + ANS_LOGI("GetAllActiveNotifications count = %{public}d", count); + asynccallbackinfo->result = arr; + if ((count == 0) && (notifications.size() > 0)) { + asynccallbackinfo->info.errorCode = ERROR; asynccallbackinfo->result = Common::NapiGetNull(env); } }, @@ -148,12 +128,7 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) ANS_LOGI("GetAllActiveNotifications napi_create_async_work end"); AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, asynccallbackinfo->result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -166,7 +141,7 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; @@ -175,23 +150,20 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) napi_value GetActiveNotifications(napi_env env, napi_callback_info info) { - ANS_LOGI("GetActiveNotifications start"); + ANS_LOGI("enter"); - size_t argc = ACTIVE_OR_NUMS_MAX_PARA; - napi_value argv[ACTIVE_OR_NUMS_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); napi_ref callback = nullptr; - - if (ParseParameters(env, argv, argc, callback) == nullptr) { + if (ParseParametersByGetActive(env, info, callback) == nullptr) { return Common::JSParaError(env, callback); } AsyncCallbackInfoActive *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr}; - + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "getActiveNotifications", NAPI_AUTO_LENGTH, &resourceName); @@ -203,32 +175,33 @@ napi_value GetActiveNotifications(napi_env env, napi_callback_info info) ANS_LOGI("GetActiveNotifications napi_create_async_work start"); AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; - std::vector> request; - asynccallbackinfo->errorCode = NotificationHelper::GetActiveNotifications(request); - - if (asynccallbackinfo->errorCode == ERR_OK) { - napi_value arr; - int count = 0; - napi_create_array(env, &arr); - for (auto vec : request) { - if (vec) { - napi_value result; - napi_create_object(env, &result); - if (Common::SetNotificationRequest( - env, static_cast(vec.GetRefPtr()), result)) { - napi_set_element(env, arr, count, result); - count++; - } - } + std::vector> requests; + asynccallbackinfo->info.errorCode = NotificationHelper::GetActiveNotifications(requests); + if (asynccallbackinfo->info.errorCode != ERR_OK) { + asynccallbackinfo->result = Common::NapiGetNull(env); + return; + } + napi_value arr; + int count = 0; + napi_create_array(env, &arr); + for (auto vec : requests) { + if (!vec) { + ANS_LOGW("Invalid NotificationRequest object ptr"); + continue; } - if (count > 0) { - ANS_LOGI("GetActiveNotifications count = %{public}d", count); - asynccallbackinfo->result = arr; - } else { - asynccallbackinfo->errorCode = ERROR; - asynccallbackinfo->result = Common::NapiGetNull(env); + napi_value result; + napi_create_object(env, &result); + if (!Common::SetNotificationRequest(env, vec.GetRefPtr(), result)) { + ANS_LOGW("Set NotificationRequest object failed"); + continue; } - } else { + napi_set_element(env, arr, count, result); + count++; + } + ANS_LOGI("GetActiveNotifications count = %{public}d", count); + asynccallbackinfo->result = arr; + if ((count == 0) && (requests.size() > 0)) { + asynccallbackinfo->info.errorCode = ERROR; asynccallbackinfo->result = Common::NapiGetNull(env); } }, @@ -236,12 +209,7 @@ napi_value GetActiveNotifications(napi_env env, napi_callback_info info) ANS_LOGI("GetActiveNotifications napi_create_async_work end"); AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, asynccallbackinfo->result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -254,31 +222,29 @@ napi_value GetActiveNotifications(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; } } + napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info) { - ANS_LOGI("GetActiveNotificationNums start"); + ANS_LOGI("enter"); - size_t argc = ACTIVE_OR_NUMS_MAX_PARA; - napi_value argv[ACTIVE_OR_NUMS_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); napi_ref callback = nullptr; - - if (ParseParameters(env, argv, argc, callback) == nullptr) { + if (ParseParametersByGetActive(env, info, callback) == nullptr) { return Common::JSParaError(env, callback); } AsyncCallbackInfoActive *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr}; - + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "getActiveNotificationNums", NAPI_AUTO_LENGTH, &resourceName); @@ -290,25 +256,20 @@ napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info) ANS_LOGI("GetActiveNotificationNums napi_create_async_work start"); AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; - int32_t nums = 0; - asynccallbackinfo->errorCode = NotificationHelper::GetActiveNotificationNums(nums); - ANS_LOGI("GetActiveNotificationNums nums = %{public}d", nums); - if (asynccallbackinfo->errorCode == ERR_OK) { - napi_create_int32(env, nums, &asynccallbackinfo->result); - } else { + int32_t num = 0; + asynccallbackinfo->info.errorCode = NotificationHelper::GetActiveNotificationNums(num); + ANS_LOGI("GetActiveNotificationNums nums = %{public}d", num); + if (asynccallbackinfo->info.errorCode != ERR_OK) { asynccallbackinfo->result = Common::NapiGetNull(env); + return; } + napi_create_int32(env, num, &asynccallbackinfo->result); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("GetActiveNotificationNums napi_create_async_work end"); AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, asynccallbackinfo->result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -321,7 +282,7 @@ napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; diff --git a/interfaces/kits/napi/ans/src/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index 14eb5ce8c..4f464fff2 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -39,14 +39,19 @@ napi_value NotificationInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("subscribe", Subscribe), DECLARE_NAPI_FUNCTION("unsubscribe", Unsubscribe), DECLARE_NAPI_FUNCTION("publish", Publish), + DECLARE_NAPI_FUNCTION("remove", Remove), + DECLARE_NAPI_FUNCTION("removeAll", RemoveAll), DECLARE_NAPI_FUNCTION("getAllActiveNotifications", GetAllActiveNotifications), DECLARE_NAPI_FUNCTION("getActiveNotifications", GetActiveNotifications), DECLARE_NAPI_FUNCTION("getActiveNotificationNums", GetActiveNotificationNums), DECLARE_NAPI_FUNCTION("cancel", Cancel), DECLARE_NAPI_FUNCTION("cancelAll", CancelAll), + DECLARE_NAPI_FUNCTION("addSlot", AddSlot), + DECLARE_NAPI_FUNCTION("addSlots", AddSlots), DECLARE_NAPI_FUNCTION("getSlot", GetSlot), DECLARE_NAPI_FUNCTION("getSlots", GetSlots), DECLARE_NAPI_FUNCTION("removeSlot", RemoveSlot), + DECLARE_NAPI_FUNCTION("removeAllSlots", RemoveAllSlots), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/interfaces/kits/napi/ans/src/publish.cpp b/interfaces/kits/napi/ans/src/publish.cpp index 4f85115a7..d420a5c42 100644 --- a/interfaces/kits/napi/ans/src/publish.cpp +++ b/interfaces/kits/napi/ans/src/publish.cpp @@ -25,130 +25,76 @@ static const int32_t PUBLISH_NOTIFICATION_MAX = 2; struct AsyncCallbackInfoPublish { napi_env env; napi_async_work asyncWork; - napi_ref callback = 0; - napi_deferred deferred; - NotificationRequest notificationRequest; + NotificationRequest request; std::string lable; - bool isCallback = false; - bool isPublishNotificationTwoPara = false; - int errorCode = 0; + CallbackPromiseInfo info; }; -struct NotificationLongTextContent { - std::string longText; - std::string briefText; - std::string expandedTitle; -}; - -struct NotificationPictureContent {}; - -struct NotificationConversationalContent {}; - -struct NotificationMultiLineContent {}; - -struct NotificationContentPublish { - int32_t type; - NotificationBasicContent notificationBasicContent; - NotificationLongTextContent notificationLongTextContent; - NotificationPictureContent notificationPictureContent; - NotificationConversationalContent notificationConversationalContent; - NotificationMultiLineContent notificationMultiLineContent; -}; - -struct ParseParametersPublish { - napi_env env; - size_t argc; - bool isCallback; +struct ParametersInfoPublish { std::string lable; - napi_ref callback; + NotificationRequest request; + napi_ref callback = nullptr; }; -napi_value GetCallbackByPublish( - ParseParametersPublish &parseParameters, const napi_value &value, napi_valuetype &valuetype) +napi_value GetCallback(const napi_env &env, const napi_value &value, ParametersInfoPublish ¶ms) { ANS_LOGI("enter"); - NAPI_CALL(parseParameters.env, napi_typeof(parseParameters.env, value, &valuetype)); - NAPI_ASSERT(parseParameters.env, valuetype = napi_function, "Wrong argument type. Function expected."); - napi_create_reference(parseParameters.env, value, 1, &parseParameters.callback); + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype = napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, value, 1, ¶ms.callback); ANS_LOGI("end"); - return Common::NapiGetNull(parseParameters.env); + return Common::NapiGetNull(env); } -napi_value ParseParametersByPublish(ParseParametersPublish &parseParameters, - const napi_value (&argv)[PUBLISH_NOTIFICATION_MAX], NotificationRequest ¬ificationRequest) +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, ParametersInfoPublish ¶ms) { ANS_LOGI("enter"); - NAPI_ASSERT(parseParameters.env, parseParameters.argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; + size_t argc = PUBLISH_NOTIFICATION_MAX; + napi_value argv[PUBLISH_NOTIFICATION_MAX]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); - NAPI_CALL(parseParameters.env, napi_typeof(parseParameters.env, argv[0], &valuetype)); - NAPI_ASSERT(parseParameters.env, valuetype == napi_object, "Wrong argument type. Object expected."); + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - // argv[0]----NotificationRequest - if (Common::GetNotificationRequest(parseParameters.env, argv[0], notificationRequest) == nullptr) { + // argv[0] : NotificationRequest + if (Common::GetNotificationRequest(env, argv[0], params.request) == nullptr) { return nullptr; } // argv[1] : callback - if (parseParameters.argc >= PUBLISH_NOTIFICATION_MAX) { - GetCallbackByPublish(parseParameters, argv[1], valuetype); + if (argc >= PUBLISH_NOTIFICATION_MAX) { + if (GetCallback(env, argv[1], params) == nullptr) { + return nullptr; + } } ANS_LOGI("end"); - return Common::NapiGetNull(parseParameters.env); -} - -void PaddingCallbackInfoInfoPublish(AsyncCallbackInfoPublish *&asynccallbackinfo, - const ParseParametersPublish &parseParameters, const NotificationRequest ¬ificationRequest) -{ - ANS_LOGI("enter"); - - asynccallbackinfo->lable = parseParameters.lable; - asynccallbackinfo->notificationRequest = notificationRequest; - - return; -} - -void PaddingPublishCallbackPromise(const napi_env &env, const ParseParametersPublish &parseParameters, - AsyncCallbackInfoPublish *&asynccallbackinfo, napi_value &promise) -{ - ANS_LOGI("enter"); - - if (parseParameters.callback != nullptr) { - asynccallbackinfo->callback = parseParameters.callback; - asynccallbackinfo->isCallback = true; - } else { - napi_deferred deferred = nullptr; - napi_create_promise(env, &deferred, &promise); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; - } - - return; + return Common::NapiGetNull(env); } napi_value Publish(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); - size_t argc = PUBLISH_NOTIFICATION_MAX; - napi_value argv[PUBLISH_NOTIFICATION_MAX]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - - ParseParametersPublish parseParameters = {env, argc, false, "", nullptr}; - NotificationRequest notificationRequest; - if (ParseParametersByPublish(parseParameters, argv, notificationRequest) == nullptr) { - return Common::JSParaError(env, parseParameters.callback); + ParametersInfoPublish params; + if (ParseParameters(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); } + + napi_value promise = 0; AsyncCallbackInfoPublish *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoPublish{.env = env, .asyncWork = nullptr}; - napi_value promise = 0; - - PaddingCallbackInfoInfoPublish(asynccallbackinfo, parseParameters, notificationRequest); - - PaddingPublishCallbackPromise(env, parseParameters, asynccallbackinfo, promise); + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + asynccallbackinfo->lable = params.lable; + asynccallbackinfo->request = params.request; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "publish", NAPI_AUTO_LENGTH, &resourceName); @@ -159,24 +105,19 @@ napi_value Publish(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("Publish napi_create_async_work start"); AsyncCallbackInfoPublish *asynccallbackinfo = (AsyncCallbackInfoPublish *)data; - ANS_LOGI("==============Publish napi_create_async_work start notificationId = %{public}d,contentType = " + ANS_LOGI("Publish napi_create_async_work start notificationId = %{public}d, contentType = " "%{public}d", - asynccallbackinfo->notificationRequest.GetNotificationId(), - asynccallbackinfo->notificationRequest.GetContent()->GetContentType()); + asynccallbackinfo->request.GetNotificationId(), + asynccallbackinfo->request.GetContent()->GetContentType()); - asynccallbackinfo->errorCode = NotificationHelper::PublishNotification( - asynccallbackinfo->lable, asynccallbackinfo->notificationRequest); + asynccallbackinfo->info.errorCode = + NotificationHelper::PublishNotification(asynccallbackinfo->lable, asynccallbackinfo->request); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("Publish napi_create_async_work complete start"); AsyncCallbackInfoPublish *asynccallbackinfo = (AsyncCallbackInfoPublish *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -190,7 +131,7 @@ napi_value Publish(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; diff --git a/interfaces/kits/napi/ans/src/remove.cpp b/interfaces/kits/napi/ans/src/remove.cpp index a3f01f924..335c2cfdd 100644 --- a/interfaces/kits/napi/ans/src/remove.cpp +++ b/interfaces/kits/napi/ans/src/remove.cpp @@ -14,94 +14,152 @@ */ #include "remove.h" +#include +#include "common.h" namespace OHOS { namespace NotificationNapi { +const int REMOVE_MIN_PARA = 1; const int REMOVE_OR_BUNDLE_MAX_PARA = 2; -const int REMOVE_ALL_MAX_PARA = 1; + +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; + +struct BundleAndKeyInfo { + BundleOption option; + NotificationKey key; +}; + +struct RemoveParams { + std::optional hashcode{}; + std::optional bundleAndKeyInfo{}; + napi_ref callback = nullptr; +}; struct AsyncCallbackInfoRemove { napi_env env; napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - std::string strValue; - bool isCallback = false; - int errorCode = 0; + RemoveParams params{}; + CallbackPromiseInfo info; }; -napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[REMOVE_OR_BUNDLE_MAX_PARA], const size_t &argc, - std::string &strValue, napi_ref &callback) +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, RemoveParams ¶ms) { + ANS_LOGI("enter"); + + size_t argc = REMOVE_OR_BUNDLE_MAX_PARA; + napi_value argv[REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA]; + 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"); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); - // argv[0]: hashCode/bundleName - size_t strLen; - char str[STR_MAX_SIZE] = {0}; napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, argv[0], str, STR_MAX_SIZE - 1, &strLen)); - strValue = str; - - // argv[1]:callback - if (argc >= REMOVE_OR_BUNDLE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, &callback); + NAPI_ASSERT(env, + (valuetype == napi_string) || (valuetype == napi_object), + "Wrong argument type. String or object expected."); + if (valuetype == napi_string) { + // argv[0]: hashCode + size_t strLen; + char str[STR_MAX_SIZE] = {0}; + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[0], str, STR_MAX_SIZE - 1, &strLen)); + params.hashcode = str; + + // argv[1]:callback + if (argc >= REMOVE_OR_BUNDLE_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, ¶ms.callback); + } + } else { + NAPI_ASSERT(env, argc >= REMOVE_BY_BUNDLE_AND_KEY_MIN_PARA, "Wrong number of arguments"); + + BundleAndKeyInfo info{}; + // argv[0]: BundleOption + auto retValue = Common::GetBundleOption(env, argv[0], info.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + + // argv[1]: NotificationKey + retValue = Common::GetNotificationKey(env, argv[1], info.key); + if (retValue == nullptr) { + ANS_LOGE("GetNotificationKey failed."); + return nullptr; + } + + params.bundleAndKeyInfo = info; + + // argv[2]:callback + if (argc >= REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[2], 1, ¶ms.callback); + } } + return Common::NapiGetNull(env); } -napi_value ParseParametersByRemoveAll( - const napi_env &env, const napi_value (&argv)[REMOVE_ALL_MAX_PARA], const size_t &argc, napi_ref &callback) +napi_value ParseParametersByRemoveAll(const napi_env &env, const napi_callback_info &info, RemoveParams ¶ms) { - // argv[0]:callback - napi_valuetype valuetype; - if (argc >= REMOVE_ALL_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[0], 1, &callback); + ANS_LOGI("enter"); + + size_t argc = REMOVE_ALL_MAX_PARA; + napi_value argv[REMOVE_ALL_MAX_PARA]; + 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) { + return Common::NapiGetNull(env); } - return Common::NapiGetNull(env); -} -void PaddingAsyncCallbackInfoIs( - const napi_env &env, AsyncCallbackInfoRemove *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) -{ - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); - if (callback) { - asynccallbackinfo->callback = callback; - asynccallbackinfo->isCallback = true; + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[0], &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[0], 1, ¶ms.callback); } else { - napi_deferred deferred = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; + BundleAndKeyInfo info{}; + // argv[0]: BundleOption + auto retValue = Common::GetBundleOption(env, argv[0], info.option); + NAPI_ASSERT(env, retValue != nullptr, "GetBundleOption failed."); + params.bundleAndKeyInfo = info; + + // argv[1]:callback + if (argc >= REMOVE_ALL_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, ¶ms.callback); + } } + + return Common::NapiGetNull(env); } napi_value Remove(napi_env env, napi_callback_info info) { - ANS_LOGI("Remove start"); - - size_t argc = REMOVE_OR_BUNDLE_MAX_PARA; - napi_value argv[REMOVE_OR_BUNDLE_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - napi_ref callback = nullptr; + ANS_LOGI("enter"); - std::string hashCode; - if (ParseParameters(env, argv, argc, hashCode, callback) == nullptr) { - return Common::JSParaError(env, callback); + RemoveParams params{}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); } - ANS_LOGI("Remove hashCode = %{public}s", hashCode.c_str()); AsyncCallbackInfoRemove *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .strValue = hashCode}; - + new (std::nothrow) AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "remove", NAPI_AUTO_LENGTH, &resourceName); @@ -112,80 +170,21 @@ napi_value Remove(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("Remove napi_create_async_work start"); AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; - asynccallbackinfo->errorCode = NotificationHelper::RemoveNotification(asynccallbackinfo->strValue); - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("Remove napi_create_async_work end"); - AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; + if (asynccallbackinfo->params.hashcode.has_value()) { + asynccallbackinfo->info.errorCode = + NotificationHelper::RemoveNotification(asynccallbackinfo->params.hashcode.value()); + } else if (asynccallbackinfo->params.bundleAndKeyInfo.has_value()) { + auto &infos = asynccallbackinfo->params.bundleAndKeyInfo.value(); + asynccallbackinfo->info.errorCode = NotificationHelper::RemoveNotification( + infos.option.bundle, infos.option.uid, infos.key.id, infos.key.label); } }, - (void *)asynccallbackinfo, - &asynccallbackinfo->asyncWork); - - NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - - if (asynccallbackinfo->isCallback) { - return Common::NapiGetNull(env); - } else { - return promise; - } -} -napi_value RemoveAsBundle(napi_env env, napi_callback_info info) -{ - ANS_LOGI("RemoveAsBundle start"); - - size_t argc = REMOVE_OR_BUNDLE_MAX_PARA; - napi_value argv[REMOVE_OR_BUNDLE_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - napi_ref callback = nullptr; - - std::string bundleName; - if (ParseParameters(env, argv, argc, bundleName, callback) == nullptr) { - return Common::JSParaError(env, callback); - } - ANS_LOGI("RemoveAsBundle bundleName = %{public}s", bundleName.c_str()); - - AsyncCallbackInfoRemove *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .strValue = bundleName}; - - napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); - - napi_value resourceName; - napi_create_string_latin1(env, "removeAsBundle", NAPI_AUTO_LENGTH, &resourceName); - // Asynchronous function call - napi_create_async_work(env, - nullptr, - resourceName, - [](napi_env env, void *data) { - ANS_LOGI("removeAsBundle napi_create_async_work start"); - AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; - asynccallbackinfo->errorCode = NotificationHelper::RemoveNotifications(asynccallbackinfo->strValue); - }, [](napi_env env, napi_status status, void *data) { - ANS_LOGI("removeAsBundle napi_create_async_work end"); + ANS_LOGI("Remove napi_create_async_work end"); AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -198,31 +197,29 @@ napi_value RemoveAsBundle(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; } } + napi_value RemoveAll(napi_env env, napi_callback_info info) { - ANS_LOGI("RemoveAll start"); + ANS_LOGI("enter"); - size_t argc = REMOVE_ALL_MAX_PARA; - napi_value argv[REMOVE_ALL_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - napi_ref callback = nullptr; - - if (ParseParametersByRemoveAll(env, argv, argc, callback) == nullptr) { - return Common::JSParaError(env, callback); + RemoveParams params{}; + if (ParseParametersByRemoveAll(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); } AsyncCallbackInfoRemove *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr}; - + new (std::nothrow) AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "removeAll", NAPI_AUTO_LENGTH, &resourceName); @@ -233,18 +230,20 @@ napi_value RemoveAll(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("RemoveAll napi_create_async_work start"); AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; - asynccallbackinfo->errorCode = NotificationHelper::RemoveNotifications(); + + if (asynccallbackinfo->params.bundleAndKeyInfo.has_value()) { + auto &infos = asynccallbackinfo->params.bundleAndKeyInfo.value(); + asynccallbackinfo->info.errorCode = + NotificationHelper::RemoveNotifications(infos.option.bundle, infos.option.uid); + } else { + asynccallbackinfo->info.errorCode = NotificationHelper::RemoveNotifications(); + } }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("RemoveAll napi_create_async_work end"); AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -257,7 +256,7 @@ napi_value RemoveAll(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; diff --git a/interfaces/kits/napi/ans/src/slot.cpp b/interfaces/kits/napi/ans/src/slot.cpp index 99864d9d2..49eaa6bb2 100644 --- a/interfaces/kits/napi/ans/src/slot.cpp +++ b/interfaces/kits/napi/ans/src/slot.cpp @@ -22,159 +22,165 @@ const int ADD_SLOTS_MAX_PARA = 2; const int GET_SLOT_MAX_PARA = 2; const int GET_SLOTS_MAX_PARA = 1; const int REMOVE_SLOT_MAX_PARA = 2; +const int REMOVE_ALL_MAX_PARA = 1; struct AsyncCallbackInfoAddSlot { napi_env env; napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; NotificationSlot slot; - bool isCallback = false; - int errorCode = 0; + enum NotificationConstant::SlotType inType; + bool isAddSlotByType = false; + CallbackPromiseInfo info; +}; + +struct ParametersInfoAddSlot { + NotificationSlot slot; + enum NotificationConstant::SlotType inType; + bool isAddSlotByType = false; + napi_ref callback = nullptr; }; struct AsyncCallbackInfoAddSlots { napi_env env; napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; std::vector slots; - bool isCallback = false; - int errorCode = 0; + CallbackPromiseInfo info; +}; + +struct ParametersInfoAddSlots { + std::vector slots; + napi_ref callback = nullptr; }; struct AsyncCallbackInfoGetSlot { napi_env env; napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; enum NotificationConstant::SlotType outType; - bool isCallback = false; napi_value result = nullptr; - int errorCode = 0; + CallbackPromiseInfo info; +}; + +struct ParametersInfoGetSlot { + enum NotificationConstant::SlotType outType; + napi_ref callback = nullptr; }; struct AsyncCallbackInfoGetSlots { napi_env env; napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - bool isCallback = false; napi_value result = nullptr; - int errorCode = 0; + CallbackPromiseInfo info; }; struct AsyncCallbackInfoRemoveSlot { napi_env env; napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; enum NotificationConstant::SlotType outType; - bool isCallback = false; - int errorCode = 0; + CallbackPromiseInfo info; +}; + +struct ParametersInfoRemoveSlot { + enum NotificationConstant::SlotType outType; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoRemoveAllSlots { + napi_env env; + napi_async_work asyncWork; + CallbackPromiseInfo info; }; -napi_value ParseParametersByAddSlot(const napi_env &env, const napi_value (&argv)[ADD_SLOT_MAX_PARA], - const size_t &argc, NotificationSlot &slot, napi_ref &callback) +napi_value ParseParametersByAddSlot(const napi_env &env, const napi_callback_info &info, ParametersInfoAddSlot ¶s) { + ANS_LOGI("enter"); + size_t argc = ADD_SLOT_MAX_PARA; + napi_value argv[ADD_SLOT_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_valuetype valuetype; // argv[0]: NotificationSlot NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - if (!Common::GetNotificationSlot(env, slot, argv[0])) { - return nullptr; + NAPI_ASSERT( + env, (valuetype == napi_object || valuetype == napi_number), "Wrong argument type. Object or number expected."); + if (valuetype == napi_number) { + paras.isAddSlotByType = true; + int slotType = 0; + napi_get_value_int32(env, argv[0], &slotType); + if (!Common::SlotTypeJSToC(SlotType(slotType), paras.inType)) { + return nullptr; + } + } else { + paras.isAddSlotByType = false; + if (!Common::GetNotificationSlot(env, argv[0], paras.slot)) { + return nullptr; + } } + // argv[1]:callback if (argc >= ADD_SLOT_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, &callback); + napi_create_reference(env, argv[1], 1, ¶s.callback); } return Common::NapiGetNull(env); } -void PaddingAsyncCallbackInfoIsByAddSlot( - const napi_env &env, AsyncCallbackInfoAddSlot *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) -{ - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); - - if (callback) { - asynccallbackinfo->callback = callback; - asynccallbackinfo->isCallback = true; - } else { - napi_deferred deferred = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; - } -} - -napi_value ParseParametersByAddSlots(const napi_env &env, const napi_value (&argv)[ADD_SLOTS_MAX_PARA], - const size_t &argc, std::vector &slots, napi_ref &callback) +napi_value ParseParametersByAddSlots(const napi_env &env, const napi_callback_info &info, ParametersInfoAddSlots ¶s) { + ANS_LOGI("enter"); + size_t argc = ADD_SLOTS_MAX_PARA; + napi_value argv[ADD_SLOTS_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_valuetype valuetype; // argv[0]: Array bool isArray = false; napi_is_array(env, argv[0], &isArray); - if (isArray) { - uint32_t length = 0; - napi_get_array_length(env, argv[0], &length); - for (size_t i = 0; i < length; i++) { - napi_value nSlot; - napi_get_element(env, argv[0], i, &nSlot); - NAPI_CALL(env, napi_typeof(env, nSlot, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - NotificationSlot slot; - if (!Common::GetNotificationSlot(env, slot, nSlot)) { - return nullptr; - } - slots.emplace_back(slot); - } - if (slots.size() == 0) { - ANS_LOGI("slots size is empyt"); + NAPI_ASSERT(env, isArray, "Wrong argument type. Array expected."); + uint32_t length = 0; + napi_get_array_length(env, argv[0], &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + for (size_t i = 0; i < length; i++) { + napi_value nSlot; + napi_get_element(env, argv[0], i, &nSlot); + NAPI_CALL(env, napi_typeof(env, nSlot, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + NotificationSlot slot; + if (!Common::GetNotificationSlot(env, nSlot, slot)) { return nullptr; } + paras.slots.emplace_back(slot); } + // argv[1]:callback if (argc >= ADD_SLOTS_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, &callback); + napi_create_reference(env, argv[1], 1, ¶s.callback); } return Common::NapiGetNull(env); } -void PaddingAsyncCallbackInfoIsByAddSlots( - const napi_env &env, AsyncCallbackInfoAddSlots *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) -{ - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); - - if (callback) { - asynccallbackinfo->callback = callback; - asynccallbackinfo->isCallback = true; - } else { - napi_deferred deferred = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; - } -} - -napi_value ParseParametersByGetSlot(const napi_env &env, const napi_value (&argv)[GET_SLOT_MAX_PARA], - const size_t &argc, enum NotificationConstant::SlotType &outType, napi_ref &callback) +napi_value ParseParametersByGetSlot(const napi_env &env, const napi_callback_info &info, ParametersInfoGetSlot ¶s) { + ANS_LOGI("enter"); + size_t argc = GET_SLOT_MAX_PARA; + napi_value argv[GET_SLOT_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_valuetype valuetype; // argv[0]: SlotType NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int slotType = 0; napi_get_value_int32(env, argv[0], &slotType); - - if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { + if (!Common::SlotTypeJSToC(SlotType(slotType), paras.outType)) { return nullptr; } @@ -182,30 +188,19 @@ napi_value ParseParametersByGetSlot(const napi_env &env, const napi_value (&argv if (argc >= GET_SLOT_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, &callback); + napi_create_reference(env, argv[1], 1, ¶s.callback); } return Common::NapiGetNull(env); } -void PaddingAsyncCallbackInfoIsByGetSlot( - const napi_env &env, AsyncCallbackInfoGetSlot *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +napi_value ParseParametersByGetSlots(const napi_env &env, const napi_callback_info &info, napi_ref &callback) { - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); - - if (callback) { - asynccallbackinfo->callback = callback; - asynccallbackinfo->isCallback = true; - } else { - napi_deferred deferred = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; - } -} + ANS_LOGI("enter"); + size_t argc = GET_SLOTS_MAX_PARA; + napi_value argv[GET_SLOTS_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); -napi_value ParseParametersByGetSlots( - const napi_env &env, const napi_value (&argv)[GET_SLOTS_MAX_PARA], const size_t &argc, napi_ref &callback) -{ // argv[0]:callback napi_valuetype valuetype; if (argc >= GET_SLOTS_MAX_PARA) { @@ -216,35 +211,23 @@ napi_value ParseParametersByGetSlots( return Common::NapiGetNull(env); } -void PaddingAsyncCallbackInfoIsByGetSlots( - const napi_env &env, AsyncCallbackInfoGetSlots *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) -{ - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); - - if (callback) { - asynccallbackinfo->callback = callback; - asynccallbackinfo->isCallback = true; - } else { - napi_deferred deferred = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; - } -} - -napi_value ParseParametersByRemoveSlot(const napi_env &env, const napi_value (&argv)[REMOVE_SLOT_MAX_PARA], - const size_t &argc, enum NotificationConstant::SlotType &outType, napi_ref &callback) +napi_value ParseParametersByRemoveSlot( + const napi_env &env, const napi_callback_info &info, ParametersInfoRemoveSlot ¶s) { + ANS_LOGI("enter"); + size_t argc = REMOVE_SLOT_MAX_PARA; + napi_value argv[REMOVE_SLOT_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_valuetype valuetype; // argv[0]: SlotType NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int slotType = 0; napi_get_value_int32(env, argv[0], &slotType); - - if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { + if (!Common::SlotTypeJSToC(SlotType(slotType), paras.outType)) { return nullptr; } @@ -252,48 +235,48 @@ napi_value ParseParametersByRemoveSlot(const napi_env &env, const napi_value (&a if (argc >= REMOVE_SLOT_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, &callback); + napi_create_reference(env, argv[1], 1, ¶s.callback); } return Common::NapiGetNull(env); } -void PaddingAsyncCallbackInfoIsByRemoveSlot( - const napi_env &env, AsyncCallbackInfoRemoveSlot *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +napi_value ParseParametersByRemoveAllSlots(const napi_env &env, const napi_callback_info &info, napi_ref &callback) { - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + ANS_LOGI("enter"); + size_t argc = REMOVE_ALL_MAX_PARA; + napi_value argv[REMOVE_ALL_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (callback) { - asynccallbackinfo->callback = callback; - asynccallbackinfo->isCallback = true; - } else { - napi_deferred deferred = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; + if (argc >= REMOVE_ALL_MAX_PARA) { + napi_valuetype valuetype; + // argv[0]:callback + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[0], 1, &callback); } + return Common::NapiGetNull(env); } napi_value AddSlot(napi_env env, napi_callback_info info) { - ANS_LOGI("AddSlot start"); - - size_t argc = ADD_SLOT_MAX_PARA; - napi_value argv[ADD_SLOT_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + ANS_LOGI("enter"); - napi_ref callback = nullptr; - - NotificationSlot slot; - if (ParseParametersByAddSlot(env, argv, argc, slot, callback) == nullptr) { - return Common::JSParaError(env, callback); + ParametersInfoAddSlot paras; + if (ParseParametersByAddSlot(env, info, paras) == nullptr) { + return Common::JSParaError(env, paras.callback); } - AsyncCallbackInfoAddSlot *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoAddSlot{.env = env, .asyncWork = nullptr, .slot = slot}; - + AsyncCallbackInfoAddSlot *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoAddSlot{.env = env, + .asyncWork = nullptr, + .slot = paras.slot, + .inType = paras.inType, + .isAddSlotByType = paras.isAddSlotByType}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIsByAddSlot(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "addSlot", NAPI_AUTO_LENGTH, &resourceName); @@ -304,18 +287,17 @@ napi_value AddSlot(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("AddSlot napi_create_async_work start"); AsyncCallbackInfoAddSlot *asynccallbackinfo = (AsyncCallbackInfoAddSlot *)data; - asynccallbackinfo->errorCode = NotificationHelper::AddNotificationSlot(asynccallbackinfo->slot); + if (asynccallbackinfo->isAddSlotByType) { + asynccallbackinfo->info.errorCode = NotificationHelper::AddSlotByType(asynccallbackinfo->inType); + } else { + asynccallbackinfo->info.errorCode = NotificationHelper::AddNotificationSlot(asynccallbackinfo->slot); + } }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("AddSlot napi_create_async_work end"); AsyncCallbackInfoAddSlot *asynccallbackinfo = (AsyncCallbackInfoAddSlot *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -328,33 +310,29 @@ napi_value AddSlot(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; } } + napi_value AddSlots(napi_env env, napi_callback_info info) { - ANS_LOGI("AddSlots start"); + ANS_LOGI("enter"); - size_t argc = ADD_SLOTS_MAX_PARA; - napi_value argv[ADD_SLOTS_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - napi_ref callback = nullptr; - - std::vector slots; - if (ParseParametersByAddSlots(env, argv, argc, slots, callback) == nullptr) { - return Common::JSParaError(env, callback); + ParametersInfoAddSlots paras; + if (ParseParametersByAddSlots(env, info, paras) == nullptr) { + return Common::JSParaError(env, paras.callback); } AsyncCallbackInfoAddSlots *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoAddSlots{.env = env, .asyncWork = nullptr, .slots = slots}; - + new (std::nothrow) AsyncCallbackInfoAddSlots{.env = env, .asyncWork = nullptr, .slots = paras.slots}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIsByAddSlots(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "addSlots", NAPI_AUTO_LENGTH, &resourceName); @@ -365,18 +343,13 @@ napi_value AddSlots(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("AddSlots napi_create_async_work start"); AsyncCallbackInfoAddSlots *asynccallbackinfo = (AsyncCallbackInfoAddSlots *)data; - asynccallbackinfo->errorCode = NotificationHelper::AddNotificationSlots(asynccallbackinfo->slots); + asynccallbackinfo->info.errorCode = NotificationHelper::AddNotificationSlots(asynccallbackinfo->slots); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("AddSlots napi_create_async_work end"); AsyncCallbackInfoAddSlots *asynccallbackinfo = (AsyncCallbackInfoAddSlots *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -389,33 +362,29 @@ napi_value AddSlots(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; } } + napi_value GetSlot(napi_env env, napi_callback_info info) { - ANS_LOGI("GetSlot start"); + ANS_LOGI("enter"); - size_t argc = GET_SLOT_MAX_PARA; - napi_value argv[GET_SLOT_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - napi_ref callback = nullptr; - - enum NotificationConstant::SlotType outType; - if (ParseParametersByGetSlot(env, argv, argc, outType, callback) == nullptr) { - return Common::JSParaError(env, callback); + ParametersInfoGetSlot paras; + if (ParseParametersByGetSlot(env, info, paras) == nullptr) { + return Common::JSParaError(env, paras.callback); } AsyncCallbackInfoGetSlot *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoGetSlot{.env = env, .asyncWork = nullptr, .outType = outType}; - + new (std::nothrow) AsyncCallbackInfoGetSlot{.env = env, .asyncWork = nullptr, .outType = paras.outType}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIsByGetSlot(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "getSlot", NAPI_AUTO_LENGTH, &resourceName); @@ -428,14 +397,19 @@ napi_value GetSlot(napi_env env, napi_callback_info info) AsyncCallbackInfoGetSlot *asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; sptr slot = nullptr; - asynccallbackinfo->errorCode = NotificationHelper::GetNotificationSlot(asynccallbackinfo->outType, slot); - if (slot && asynccallbackinfo->errorCode == ERR_OK) { - napi_create_object(env, &asynccallbackinfo->result); - if (!Common::SetNotificationSlot(env, *slot, asynccallbackinfo->result)) { - asynccallbackinfo->errorCode = ERROR; - asynccallbackinfo->result = Common::NapiGetNull(env); - } - } else { + asynccallbackinfo->info.errorCode = + NotificationHelper::GetNotificationSlot(asynccallbackinfo->outType, slot); + asynccallbackinfo->result = Common::NapiGetNull(env); + if (asynccallbackinfo->info.errorCode != ERR_OK) { + return; + } + if (slot == nullptr) { + asynccallbackinfo->info.errorCode = ERROR; + return; + } + napi_create_object(env, &asynccallbackinfo->result); + if (!Common::SetNotificationSlot(env, *slot, asynccallbackinfo->result)) { + asynccallbackinfo->info.errorCode = ERROR; asynccallbackinfo->result = Common::NapiGetNull(env); } }, @@ -443,12 +417,7 @@ napi_value GetSlot(napi_env env, napi_callback_info info) ANS_LOGI("GetSlot napi_create_async_work end"); AsyncCallbackInfoGetSlot *asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, asynccallbackinfo->result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -461,7 +430,7 @@ napi_value GetSlot(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; @@ -470,23 +439,20 @@ napi_value GetSlot(napi_env env, napi_callback_info info) napi_value GetSlots(napi_env env, napi_callback_info info) { - ANS_LOGI("GetSlots start"); + ANS_LOGI("enter"); - size_t argc = GET_SLOTS_MAX_PARA; - napi_value argv[GET_SLOTS_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); napi_ref callback = nullptr; - - if (ParseParametersByGetSlots(env, argv, argc, callback) == nullptr) { + if (ParseParametersByGetSlots(env, info, callback) == nullptr) { return Common::JSParaError(env, callback); } AsyncCallbackInfoGetSlots *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetSlots{.env = env, .asyncWork = nullptr}; - + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIsByGetSlots(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "getSlots", NAPI_AUTO_LENGTH, &resourceName); @@ -499,28 +465,32 @@ napi_value GetSlots(napi_env env, napi_callback_info info) AsyncCallbackInfoGetSlots *asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; std::vector> slots; - asynccallbackinfo->errorCode = NotificationHelper::GetNotificationSlots(slots); - if (asynccallbackinfo->errorCode == ERR_OK) { - napi_value arr; - napi_create_array(env, &arr); - size_t count = 0; - for (auto vec : slots) { - if (vec) { - napi_value nSlot; - napi_create_object(env, &nSlot); - if (Common::SetNotificationSlot(env, *vec, nSlot)) { - napi_set_element(env, arr, count, nSlot); - count++; - } - } + asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlots(slots); + if (asynccallbackinfo->info.errorCode != ERR_OK) { + asynccallbackinfo->result = Common::NapiGetNull(env); + return; + } + + napi_value arr; + napi_create_array(env, &arr); + size_t count = 0; + for (auto vec : slots) { + if (!vec) { + ANS_LOGW("Invalid NotificationSlot object ptr"); + continue; } - ANS_LOGI("getSlots count = %{public}d", count); - if (count == 0) { - asynccallbackinfo->errorCode = ERROR; - asynccallbackinfo->result = Common::NapiGetNull(env); + napi_value nSlot; + napi_create_object(env, &nSlot); + if (!Common::SetNotificationSlot(env, *vec, nSlot)) { + continue; } - asynccallbackinfo->result = arr; - } else { + napi_set_element(env, arr, count, nSlot); + count++; + } + ANS_LOGI("getSlots count = %{public}d", count); + asynccallbackinfo->result = arr; + if ((count == 0) && (slots.size() > 0)) { + asynccallbackinfo->info.errorCode = ERROR; asynccallbackinfo->result = Common::NapiGetNull(env); } }, @@ -528,12 +498,7 @@ napi_value GetSlots(napi_env env, napi_callback_info info) ANS_LOGI("GetSlots napi_create_async_work end"); AsyncCallbackInfoGetSlots *asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, asynccallbackinfo->result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -546,33 +511,29 @@ napi_value GetSlots(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; } } + napi_value RemoveSlot(napi_env env, napi_callback_info info) { - ANS_LOGI("RemoveSlot start"); + ANS_LOGI("enter"); - size_t argc = REMOVE_SLOT_MAX_PARA; - napi_value argv[REMOVE_SLOT_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - napi_ref callback = nullptr; - - enum NotificationConstant::SlotType outType; - if (ParseParametersByRemoveSlot(env, argv, argc, outType, callback) == nullptr) { - return Common::JSParaError(env, callback); + ParametersInfoRemoveSlot paras; + if (ParseParametersByRemoveSlot(env, info, paras) == nullptr) { + return Common::JSParaError(env, paras.callback); } AsyncCallbackInfoRemoveSlot *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoRemoveSlot{.env = env, .asyncWork = nullptr, .outType = outType}; - + new (std::nothrow) AsyncCallbackInfoRemoveSlot{.env = env, .asyncWork = nullptr, .outType = paras.outType}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIsByRemoveSlot(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "removeSlot", NAPI_AUTO_LENGTH, &resourceName); @@ -583,18 +544,65 @@ napi_value RemoveSlot(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("removeSlot napi_create_async_work start"); AsyncCallbackInfoRemoveSlot *asynccallbackinfo = (AsyncCallbackInfoRemoveSlot *)data; - asynccallbackinfo->errorCode = NotificationHelper::RemoveNotificationSlot(asynccallbackinfo->outType); + asynccallbackinfo->info.errorCode = NotificationHelper::RemoveNotificationSlot(asynccallbackinfo->outType); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("removeSlot napi_create_async_work end"); AsyncCallbackInfoRemoveSlot *asynccallbackinfo = (AsyncCallbackInfoRemoveSlot *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value RemoveAllSlots(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + napi_ref callback = nullptr; + if (ParseParametersByRemoveAllSlots(env, info, callback) == nullptr) { + return Common::JSParaError(env, callback); + } + + AsyncCallbackInfoRemoveAllSlots *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoRemoveAllSlots{.env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } + napi_value promise = 0; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "removeAll", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("RemoveAllSlots napi_create_async_work start"); + AsyncCallbackInfoRemoveAllSlots *asynccallbackinfo = (AsyncCallbackInfoRemoveAllSlots *)data; + asynccallbackinfo->info.errorCode = NotificationHelper::RemoveAllSlots(); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("RemoveAllSlots napi_create_async_work end"); + AsyncCallbackInfoRemoveAllSlots *asynccallbackinfo = (AsyncCallbackInfoRemoveAllSlots *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -607,7 +615,7 @@ napi_value RemoveSlot(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index af36a9452..3e6405842 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -17,106 +17,85 @@ namespace OHOS { namespace NotificationNapi { - const int SUBSRIBE_MAX_PARA = 3; struct AsyncCallbackInfoSubscribe { napi_env env; napi_async_work asyncWork; - napi_ref callback = 0; - napi_deferred deferred; SubscriberInstance *objectInfo = nullptr; NotificationSubscriberInfo subscriberInfo; - bool isCallback = false; - int errorCode = 0; + CallbackPromiseInfo info; }; -napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[SUBSRIBE_MAX_PARA], const size_t &argc, +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, NotificationSubscriberInfo &subscriberInfo, SubscriberInstance *&objectInfo, napi_ref &callback) { + ANS_LOGI("enter"); + size_t argc = SUBSRIBE_MAX_PARA; + napi_value argv[SUBSRIBE_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; - // argv[0]:Subscriber + napi_valuetype valuetype; + // argv[0]:NotificationSubscriber NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. Subscribe expected."); - + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. NotificationSubscriber object expected."); napi_unwrap(env, argv[0], (void **)&objectInfo); if (!objectInfo) { - ANS_LOGE("ParseParameters subscriberInstance is null"); + ANS_LOGE("SubscriberInstance is null"); return nullptr; } - - ANS_LOGI("ParseParameters subscriberInstance = %{public}p start", objectInfo); - + ANS_LOGI("SubscriberInstance = %{public}p start", objectInfo); if (!HasNotificationSubscriber(objectInfo)) { return nullptr; } - ANS_LOGI("================ParseParameters 1111111111111111111111================="); - // argv[1]:callback/NotificationSubscriberInfo + + // argv[1]:callback or NotificationSubscribeInfo if (argc >= 2) { NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, (valuetype == napi_function) || (valuetype == napi_object), + "Wrong argument type for arg1. Function or NotificationSubscribeInfo object expected."); if (valuetype == napi_function) { napi_create_reference(env, argv[1], 1, &callback); - } else if (valuetype == napi_object) { + } else { if (Common::GetNotificationSubscriberInfo(env, argv[1], subscriberInfo) == nullptr) { - ANS_LOGE("ParseParameters SubscriberInfo parse failed"); + ANS_LOGE("NotificationSubscribeInfo parse failed"); return nullptr; } } } - ANS_LOGI("================ParseParameters 22222222222222222222222222================="); + // argv[2]:callback if (argc >= SUBSRIBE_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - ANS_LOGI("================ParseParameters 33333333333333333333333================="); napi_create_reference(env, argv[2], 1, &callback); } - ANS_LOGI("================ParseParameters 444444444444444444444444444================="); - return Common::NapiGetNull(env); -} -void PaddingAsyncCallbackInfoIs( - const napi_env &env, AsyncCallbackInfoSubscribe *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) -{ - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); - - if (callback) { - asynccallbackinfo->callback = callback; - asynccallbackinfo->isCallback = true; - } else { - napi_deferred deferred = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; - } + return Common::NapiGetNull(env); } napi_value Subscribe(napi_env env, napi_callback_info info) { - ANS_LOGI("Subscribe start"); - - size_t argc = SUBSRIBE_MAX_PARA; - napi_value argv[SUBSRIBE_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + ANS_LOGI("enter"); napi_ref callback = nullptr; - SubscriberInstance *objectInfo = nullptr; NotificationSubscriberInfo subscriberInfo; - if (ParseParameters(env, argv, argc, subscriberInfo, objectInfo, callback) == nullptr) { + if (ParseParameters(env, info, subscriberInfo, objectInfo, callback) == nullptr) { return Common::JSParaError(env, callback); } ANS_LOGI("Subscribe objectInfo = %{public}p", objectInfo); AsyncCallbackInfoSubscribe *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoSubscribe{ .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .subscriberInfo = subscriberInfo}; - + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "subscribeNotification", NAPI_AUTO_LENGTH, &resourceName); @@ -128,13 +107,13 @@ napi_value Subscribe(napi_env env, napi_callback_info info) ANS_LOGI("Subscribe napi_create_async_work start"); AsyncCallbackInfoSubscribe *asynccallbackinfo = (AsyncCallbackInfoSubscribe *)data; if (asynccallbackinfo->subscriberInfo.hasSubscriberInfo) { - ANS_LOGI("Subscribe There are NotificationSubscribeInfo"); + ANS_LOGI("Subscribe with NotificationSubscribeInfo"); NotificationSubscribeInfo subscribeInfo; subscribeInfo.AddAppNames(asynccallbackinfo->subscriberInfo.bundleNames); - asynccallbackinfo->errorCode = + asynccallbackinfo->info.errorCode = NotificationHelper::SubscribeNotification(*(asynccallbackinfo->objectInfo), subscribeInfo); } else { - asynccallbackinfo->errorCode = + asynccallbackinfo->info.errorCode = NotificationHelper::SubscribeNotification(*(asynccallbackinfo->objectInfo)); } }, @@ -142,12 +121,7 @@ napi_value Subscribe(napi_env env, napi_callback_info info) ANS_LOGI("Subscribe napi_create_async_work end"); AsyncCallbackInfoSubscribe *asynccallbackinfo = (AsyncCallbackInfoSubscribe *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -160,7 +134,7 @@ napi_value Subscribe(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; diff --git a/interfaces/kits/napi/ans/src/unsubscribe.cpp b/interfaces/kits/napi/ans/src/unsubscribe.cpp index babc54fbf..54b81dc5e 100644 --- a/interfaces/kits/napi/ans/src/unsubscribe.cpp +++ b/interfaces/kits/napi/ans/src/unsubscribe.cpp @@ -23,34 +23,35 @@ const int UNSUBSCRIBE_MAX_PARA = 2; struct AsyncCallbackInfoUnsubscribe { napi_env env; napi_async_work asyncWork; - napi_ref callback = 0; - napi_deferred deferred; SubscriberInstance *objectInfo = nullptr; - bool isCallback = false; - int errorCode = 0; + CallbackPromiseInfo info; }; -napi_value ParseParameters(const napi_env &env, const size_t &argc, const napi_value (&argv)[UNSUBSCRIBE_MAX_PARA], - SubscriberInstance *&objectInfo, napi_ref &callback) +struct ParametersInfoUnsubscribe { + SubscriberInstance *objectInfo = nullptr; + napi_ref callback = nullptr; +}; + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, ParametersInfoUnsubscribe ¶s) { - ANS_LOGI("ParseParameters start"); + ANS_LOGI("enter"); + size_t argc = UNSUBSCRIBE_MAX_PARA; + napi_value argv[UNSUBSCRIBE_MAX_PARA]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype; // argv[0]:subscriber NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. Subscribe expected."); - - napi_unwrap(env, argv[0], (void **)&objectInfo); - if (!objectInfo) { - ANS_LOGE("ParseParameters objectInfo is null"); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. Subscribe object expected."); + napi_unwrap(env, argv[0], (void **)¶s.objectInfo); + if (!paras.objectInfo) { + ANS_LOGE("ObjectInfo is null"); return nullptr; } - - ANS_LOGI("ParseParameters objectInfo = %{public}p start", objectInfo); - - if (!HasNotificationSubscriber(objectInfo)) { + ANS_LOGI("ObjectInfo = %{public}p start", paras.objectInfo); + if (!HasNotificationSubscriber(paras.objectInfo)) { return nullptr; } @@ -58,48 +59,28 @@ napi_value ParseParameters(const napi_env &env, const size_t &argc, const napi_v if (argc >= UNSUBSCRIBE_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, &callback); + napi_create_reference(env, argv[1], 1, ¶s.callback); } return Common::NapiGetNull(env); } -void PaddingAsyncCallbackInfoIs(const napi_env &env, const size_t &argc, - AsyncCallbackInfoUnsubscribe *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) -{ - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); - - if (argc >= UNSUBSCRIBE_MAX_PARA) { - asynccallbackinfo->callback = callback; - asynccallbackinfo->isCallback = true; - } else { - napi_deferred deferred = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); - asynccallbackinfo->deferred = deferred; - asynccallbackinfo->isCallback = false; - } -} - napi_value Unsubscribe(napi_env env, napi_callback_info info) { ANS_LOGI("Unsubscribe start"); - // Argument parsing - size_t argc = UNSUBSCRIBE_MAX_PARA; - napi_value argv[UNSUBSCRIBE_MAX_PARA]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - - napi_ref callback = 0; - SubscriberInstance *subscriberInstance = nullptr; - if (ParseParameters(env, argc, argv, subscriberInstance, callback) == nullptr) { - return Common::JSParaError(env, callback); + ParametersInfoUnsubscribe paras; + if (ParseParameters(env, info, paras) == nullptr) { + return Common::JSParaError(env, paras.callback); } AsyncCallbackInfoUnsubscribe *asynccallbackinfo = new (std::nothrow) - AsyncCallbackInfoUnsubscribe{.env = env, .asyncWork = nullptr, .objectInfo = subscriberInstance}; - + AsyncCallbackInfoUnsubscribe{.env = env, .asyncWork = nullptr, .objectInfo = paras.objectInfo}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, argc, asynccallbackinfo, callback, promise); + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); napi_value resourceName; napi_create_string_latin1(env, "Unsubscribe", NAPI_AUTO_LENGTH, &resourceName); @@ -112,19 +93,14 @@ napi_value Unsubscribe(napi_env env, napi_callback_info info) ANS_LOGI("Unsubscribe napi_create_async_work start"); AsyncCallbackInfoUnsubscribe *asynccallbackinfo = (AsyncCallbackInfoUnsubscribe *)data; - asynccallbackinfo->errorCode = + asynccallbackinfo->info.errorCode = NotificationHelper::UnSubscribeNotification(*(asynccallbackinfo->objectInfo)); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("Unsubscribe napi_create_async_work end"); AsyncCallbackInfoUnsubscribe *asynccallbackinfo = (AsyncCallbackInfoUnsubscribe *)data; - CallbackPromiseInfo info; - info.isCallback = asynccallbackinfo->isCallback; - info.callback = asynccallbackinfo->callback; - info.deferred = asynccallbackinfo->deferred; - info.errorCode = asynccallbackinfo->errorCode; - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); DelAsyncCallbackInfo(asynccallbackinfo->objectInfo); @@ -139,7 +115,7 @@ napi_value Unsubscribe(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { + if (asynccallbackinfo->info.isCallback) { return Common::NapiGetNull(env); } else { return promise; diff --git a/interfaces/kits/napi/wantagent/napi_want_agent.cpp b/interfaces/kits/napi/wantagent/napi_want_agent.cpp index f20c92234..38360c953 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.cpp +++ b/interfaces/kits/napi/wantagent/napi_want_agent.cpp @@ -962,7 +962,7 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info) asyncCallbackInfo->wantAgentSecond = std::make_shared(*pWantAgentSecond); if (callBackMode) { - napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + napi_create_reference(env, argv[2], 1, &asyncCallbackInfo->callback[0]); } napi_value ret = NAPI_EqualWrap(env, info, callBackMode, asyncCallbackInfo); if (ret == nullptr) { diff --git a/ohos.build b/ohos.build index c19654580..bb7fe8553 100644 --- a/ohos.build +++ b/ohos.build @@ -13,6 +13,7 @@ "test_list": [ "//base/notification/ans_standard/services/ans/test/unittest:ans_unit_test", "//base/notification/ans_standard/services/test/moduletest:ans_module_test", + "//base/notification/ans_standard/frameworks/ans/test/moduletest:moduletest", "//base/notification/ans_standard/frameworks/wantagent/test/:unittest" ] } diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 8bd0738df..34fb25766 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -47,8 +47,10 @@ public: ErrCode Publish(const std::string &label, const sptr &request) override; ErrCode Cancel(int notificationId, const std::string &label) override; ErrCode CancelAll() override; + ErrCode AddSlotByType(NotificationConstant::SlotType slotType) override; ErrCode AddSlots(const std::vector> &slots) override; ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) override; + ErrCode RemoveAllSlots() override; ErrCode AddSlotGroups(std::vector> groups) override; ErrCode GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) override; ErrCode GetSlots(std::vector> &slots) override; @@ -72,6 +74,9 @@ public: ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; ErrCode SetPrivateNotificationsAllowed(bool allow) override; ErrCode GetPrivateNotificationsAllowed(bool &allow) override; + ErrCode RemoveNotification( + const std::string &bundle, int uid, int notificationId, const std::string &label) override; + ErrCode RemoveAllNotifications(const std::string &bundle, int uid) override; ErrCode Delete(const std::string &key) override; ErrCode DeleteByBundle(const std::string &bundle) override; ErrCode DeleteAll() override; @@ -85,6 +90,7 @@ public: const std::string &deviceId, const std::string &bundleName, bool enabled) override; ErrCode SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) override; ErrCode GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) override; + ErrCode GetShowBadgeEnabled(bool &enabled) override; ErrCode Subscribe(const sptr &subscriber, const sptr &info) override; ErrCode Unsubscribe(const sptr &subscriber, const sptr &info) override; ErrCode IsAllowedNotify(bool &allowed) override; diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index 0e8936727..3b0b174ea 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -32,8 +32,8 @@ namespace Notification { class BundleManagerHelper : public DelayedSingleton { public: - std::string GetBundleNameByUid(uid_t uid); - bool IsSystemApp(uid_t uid); + std::string GetBundleNameByUid(int uid); + bool IsSystemApp(int uid); private: void Connect(); diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index c2d476978..6fa653767 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -30,7 +30,9 @@ public: ErrCode AddNotificationSlots(const std::string &bundleName, const std::vector> &slots); ErrCode AddNotificationSlotGroups( const std::string &bundleName, const std::vector> &groups); + ErrCode AddNotificationBundleProperty(const std::string &bundleName); ErrCode RemoveNotificationSlot(const std::string &bundleName, const NotificationConstant::SlotType &slotType); + ErrCode RemoveNotificationAllSlots(const std::string &bundleName); ErrCode RemoveNotificationSlotGroups(const std::string &bundleName, const std::vector &groupIds); ErrCode RemoveNotificationForBundle(const std::string &bundleName); ErrCode UpdateNotificationSlots(const std::string &bundleName, const std::vector> &slot); @@ -64,8 +66,6 @@ public: void OnDistributedKvStoreDeathRecipient(); private: - // enum class BundlePropertyType; - ErrCode CheckSlotForCreateSlot(const std::string &bundleName, const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const; ErrCode CheckGroupForCreateSlotGroup(const std::string &bundleName, const sptr &group, diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 411098a4a..650f1f2c7 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -25,12 +25,13 @@ namespace OHOS { namespace Notification { -class NotificationPreferencesDatabase { +class NotificationPreferencesDatabase final { public: NotificationPreferencesDatabase(); ~NotificationPreferencesDatabase(); bool PutSlotsToDisturbeDB(const std::string &bundleName, const std::vector> &slots); bool PutGroupsToDisturbeDB(const std::string &bundleName, const std::vector> &groups); + bool PutBundlePropertyToDisturbeDB(const NotificationPreferencesInfo::BundleInfo &bundleInfo); bool PutShowBadge(const std::string &bundleName, const bool &enable); bool PutImportance(const std::string &bundleName, const int &importance); @@ -42,28 +43,27 @@ public: bool ParseFromDisturbeDB(NotificationPreferencesInfo &info); - bool RemoveAllBundleFromDisturbeDB(); + bool RemoveAllDataFromDisturbeDB(); bool RemoveBundleFromDisturbeDB(const std::string &bundleName); bool RemoveSlotFromDisturbeDB(const std::string &bundleName, const NotificationConstant::SlotType &type); + bool RemoveAllSlotsFromDisturbeDB(const std::string &bundleName); bool RemoveGroupsFromDisturbeDB(const std::string &bundleName, const std::vector &groupId); - void SubscribeDeathRecipient(const std::shared_ptr &callback); - void UnsubscribeDeathRecipient(const std::shared_ptr &callback); - bool StoreDeathRecipient(NotificationPreferencesInfo &info); + bool StoreDeathRecipient(); private: void TryTwice(const std::function &func) const; OHOS::DistributedKv::Status GetKvStore(); void CloseKvStore(); bool CheckKvStore(); - bool ResetStore(); bool CheckBundle(const std::string &bundleName); - bool InitBundlePropertyValueToDisturbeDB(const std::string &bundleName); + bool PutBundlePropertyValueToDisturbeDB(const NotificationPreferencesInfo::BundleInfo &bundleInfo); template OHOS::DistributedKv::Status PutBundlePropertyToDisturbeDB( const std::string &bundleName, const BundleType &type, const T &t); - bool PutBundleToDisturbeDB(const std::string &bundleName); + bool PutBundleToDisturbeDB( + const std::string &bundleName, const NotificationPreferencesInfo::BundleInfo &bundleInfo); void GetValueFromDisturbeDB(const std::string &key, std::function funcion); void GetValueFromDisturbeDB(const std::string &key, @@ -76,16 +76,17 @@ private: bool GroupToEntry(const std::string &bundleName, const sptr &group, std::vector &entries); void GenerateGroupEntry(const std::string &bundleName, const sptr &group, - std::vector &entries); + std::vector &entries) const; void GenerateSlotEntry(const std::string &bundleName, const sptr &slot, - std::vector &entries); + std::vector &entries) const; void GenerateEntry( - const std::string &key, const std::string &value, std::vector &entry); + const std::string &key, const std::string &value, std::vector &entry) const; - std::string FindLastString(const std::string &inputString) const; - std::string SubUniqueIdentifyFromString(const std::string &keyStr) const; + std::string FindLastString(const std::string &findString, const std::string &inputString) const; + std::string SubUniqueIdentifyFromString(const std::string &findString, const std::string &keyStr) const; std::string VectorToString(const std::vector &data) const; void StringToVector(const std::string &str, std::vector &data) const; + int StringToInt(const std::string &str) const; std::string GenerateSlotKey( const std::string &bundleKey, const std::string &type = "", const std::string &subType = "") const; std::string GenerateGroupKey(const std::string &bundleKey, const std::string &subType = "") const; @@ -98,10 +99,11 @@ private: void ParseGroupFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleName, const OHOS::DistributedKv::Entry &entry); void ParseBundlePropertyFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, - const OHOS::DistributedKv::Key &key, const OHOS::DistributedKv::Value &value); + const std::string &bundleName, const OHOS::DistributedKv::Entry &entry); void ParseDisturbeMode(NotificationPreferencesInfo &info); void ParseEnableAllNotification(NotificationPreferencesInfo &info); - void ParseGroupDescription(sptr &group, const OHOS::DistributedKv::Entry &entry); + void ParseGroupDescription( + const std::string &bundleName, sptr &group, const OHOS::DistributedKv::Entry &entry); void ParseBundleName(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; void ParseBundleImportance(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; void ParseBundleShowBadge(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; @@ -109,7 +111,8 @@ private: void ParseBundlePrivateAllowed(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; void ParseBundleEnableNotification( NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; - void ParseSlot(sptr &slot, const OHOS::DistributedKv::Entry &entry); + void ParseSlot( + const std::string &findString, sptr &slot, const OHOS::DistributedKv::Entry &entry); void ParseSlotGroupId(sptr &slot, const std::string &value) const; void ParseSlotDescription(sptr &slot, const std::string &value) const; void ParseSlotLevel(sptr &slot, const std::string &value) const; diff --git a/services/ans/include/notification_preferences_info.h b/services/ans/include/notification_preferences_info.h index 611a9d713..de04a4046 100644 --- a/services/ans/include/notification_preferences_info.h +++ b/services/ans/include/notification_preferences_info.h @@ -26,9 +26,9 @@ namespace OHOS { namespace Notification { -class NotificationPreferencesInfo { +class NotificationPreferencesInfo final { public: - class BundleInfo { + class BundleInfo final { public: BundleInfo(); ~BundleInfo(); @@ -55,17 +55,18 @@ public: bool IsExsitSlot(const NotificationConstant::SlotType &type) const; bool IsExsitSlotGroup(const std::string &groupId) const; bool RemoveSlot(const NotificationConstant::SlotType &type); + void RemoveAllSlots(); bool RemoveSlotGroup(const std::string &groupId); private: - std::string bundleName_{}; + std::string bundleName_ {}; int importance_ = BUNDLE_IMPORTANCE; bool isShowBadge_ = BUNDLE_SHOW_BADGE; int badgeTotalNum_ = BUNDLE_BADGE_TOTAL_NUM; bool isPrivateAllowed_ = BUNDLE_PRIVATE_ALLOWED; bool isEnabledNotification_ = BUNDLE_ENABLE_NOTIFICATION; - std::map> slots_{}; - std::map> groups_{}; + std::map> slots_ {}; + std::map> groups_ {}; }; NotificationPreferencesInfo() diff --git a/services/ans/include/preferences_constant.h b/services/ans/include/preferences_constant.h index 1923774ba..30702e8fe 100644 --- a/services/ans/include/preferences_constant.h +++ b/services/ans/include/preferences_constant.h @@ -19,62 +19,58 @@ namespace OHOS { namespace Notification { -const static std::string kDisturbMode = "ans_disturbMode"; -const static std::string kEnable = "ans_notificationAll"; -const static std::string kBundleLabel = "label_ans_bundle_"; -const static std::string kUnderLine = "_"; -const static std::string kAnsBundle = "ans_bundle"; +const static std::string KEY_DISTURB_MODE = "ans_disturbMode"; +const static std::string KEY_ENABLE_ALL_NOTIFICATION = "ans_notificationAll"; +const static std::string KEY_BUNDLE_LABEL = "label_ans_bundle_"; +const static std::string KEY_UNDER_LINE = "_"; +const static std::string KEY_ANS_BUNDLE = "ans_bundle"; -const static std::string kBundleName = "name"; -const static std::string kBundleImportance = "importance"; -const static std::string kBundleShowBadge = "showBadge"; -const static std::string kBundleBadgeTotalNum = "badgeTotalNum"; -const static std::string kBundlePrivateAllowed = "privateAllowed"; -const static std::string kBundleEnableNotification = "enabledNotification"; +const static std::string KEY_BUNDLE_NAME = "name"; +const static std::string KEY_BUNDLE_IMPORTANCE = "importance"; +const static std::string KEY_BUNDLE_SHOW_BADGE = "showBadge"; +const static std::string KEY_BUNDLE_BADGE_TOTAL_NUM = "badgeTotalNum"; +const static std::string KEY_BUNDLE_PRIVATE_ALLOWED = "privateAllowed"; +const static std::string KEY_BUNDLE_ENABLE_NOTIFICATION = "enabledNotification"; -const static std::string kGroup = "group"; -const static std::string kGroupSize = "group_size"; -const static std::string kGroupId = "id"; -const static std::string kGroupName = "name"; -const static std::string kGroupDescription = "groupDescription"; -const static std::string kGroupDisable = "isDisable"; +const static std::string KEY_GROUP = "group"; +const static std::string KEY_GROUP_ID = "id"; +const static std::string KEY_GROUP_NAME = "name"; +const static std::string KEY_GROUP_DESCRIPTION = "groupDescription"; +const static std::string KEY_GROUP_DISABLE = "isDisable"; -const static std::string kSlot = "slot"; -const static std::string kSlotType = "type"; -const static std::string kSlotId = "id"; -const static std::string kSlotGroupId = "groupId"; -const static std::string kSlotName = "name"; -const static std::string kSlotDescription = "description"; -const static std::string kSlotLevel = "level"; -const static std::string kSlotShowBadge = "showBadge"; -const static std::string kSlotEnableLight = "enableLight"; -const static std::string kSlotEnableVrbration = "enableVibration"; -const static std::string kSlotLedLightColor = "ledLightColor"; -const static std::string kSlotLockscreenVisibleness = "lockscreenVisibleness"; -const static std::string kSlotSound = "sound"; -const static std::string kSlotVibrationSytle = "vibrationSytle"; -const static std::string kSlotEnableBypassDnd = "enableBypassDnd"; - -const static int32_t MAX_TIMES = 5; // 500ms -const static int32_t SLEEP_INTERVAL = 100 * 1000; // 100ms +const static std::string KEY_SLOT = "slot"; +const static std::string KEY_SLOT_TYPE = "type"; +const static std::string KEY_SLOT_ID = "id"; +const static std::string KEY_SLOT_GROUPID = "groupId"; +const static std::string KEY_SLOT_NAME = "name"; +const static std::string KEY_SLOT_DESCRIPTION = "description"; +const static std::string KEY_SLOT_LEVEL = "level"; +const static std::string KEY_SLOT_SHOW_BADGE = "showBadge"; +const static std::string KEY_SLOT_ENABLE_LIGHT = "enableLight"; +const static std::string KEY_SLOT_ENABLE_VRBRATION = "enableVibration"; +const static std::string KEY_SLOT_LED_LIGHT_COLOR = "ledLightColor"; +const static std::string KEY_SLOT_LOCKSCREEN_VISIBLENESS = "lockscreenVisibleness"; +const static std::string KEY_SLOT_SOUND = "sound"; +const static std::string KEY_SLOT_VIBRATION_STYLE = "vibrationSytle"; +const static std::string KEY_SLOT_ENABLE_BYPASS_DND = "enableBypassDnd"; // distributed database const std::string APP_ID = "advanced_notification_service"; const std::string STORE_ID = "local_db"; const static int BUNDLE_IMPORTANCE = 3; -const static bool BUNDLE_SHOW_BADGE = true; const static int BUNDLE_BADGE_TOTAL_NUM = 0; -const static int BUNDLE_PRIVATE_ALLOWED = true; +const static int BUNDLE_PRIVATE_ALLOWED = false; const static int BUNDLE_ENABLE_NOTIFICATION = true; +const static bool BUNDLE_SHOW_BADGE = false; enum class BundleType { - kBundleNameType = 1, - kBundleImportanceType, - kBundleShowBadgeType, - kBundleBadgeTotalNumType, - kBundlePrivateAllowedType, - kBundleEnableNotificationType, + BUNDLE_NAME_TYPE = 1, + BUNDLE_IMPORTANCE_TYPE, + BUNDLE_SHOW_BADGE_TYPE, + BUNDLE_BADGE_TOTAL_NUM_TYPE, + BUNDLE_PRIVATE_ALLOWED_TYPE, + BUNDLE_ENABLE_NOTIFICATION_TYPE, }; } // namespace Notification diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 12c76f049..fe2f299b0 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -69,7 +69,7 @@ inline std::string GetClientBundleName() { std::string bundle; - uid_t callingUid = IPCSkeleton::GetCallingUid(); + int callingUid = IPCSkeleton::GetCallingUid(); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { @@ -83,7 +83,7 @@ inline bool IsSystemApp() { bool isSystemApp = false; - uid_t callingUid = IPCSkeleton::GetCallingUid(); + int callingUid = IPCSkeleton::GetCallingUid(); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { @@ -128,8 +128,8 @@ inline ErrCode PrepereNotificationRequest(const sptr &reque request->SetOwnerBundleName(bundle); request->SetCreatorBundleName(bundle); - int32_t uid = IPCSkeleton::GetCallingUid(); - int32_t pid = IPCSkeleton::GetCallingPid(); + int uid = IPCSkeleton::GetCallingUid(); + int pid = IPCSkeleton::GetCallingPid(); request->SetCreatorUid(uid); request->SetCreatorPid(pid); @@ -176,6 +176,9 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt } ErrCode result = PrepereNotificationRequest(request); + if (result != ERR_OK) { + return result; + } std::shared_ptr record = std::make_shared(); record->request = request; @@ -370,18 +373,6 @@ ErrCode AdvancedNotificationService::CancelAll() return result; } -inline bool IsCustomSlotContained(const std::vector> &slots) -{ - bool isContained = false; - for (auto slot : slots) { - if (slot->GetType() == NotificationConstant::SlotType::CUSTOM) { - isContained = true; - break; - } - } - return isContained; -} - ErrCode AdvancedNotificationService::AddSlots(const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -392,37 +383,32 @@ ErrCode AdvancedNotificationService::AddSlots(const std::vector> innerSlots; + if (slots.size() == 0) { + return ERR_ANS_INVALID_PARAM; + } - sptr item; - for (auto slot : slots) { - switch (slot->GetType()) { - case NotificationConstant::SlotType::SOCIAL_COMMUNICATION: - case NotificationConstant::SlotType::SERVICE_REMINDER: - case NotificationConstant::SlotType::CONTENT_INFORMATION: - case NotificationConstant::SlotType::OTHER: - item = new NotificationSlot(slot->GetType()); - item->SetDescription(slot->GetDescription()); - innerSlots.push_back(item); - break; - case NotificationConstant::SlotType::CUSTOM: - item = slot; - innerSlots.push_back(item); - break; - default: - break; + handler_->PostSyncTask(std::bind([&]() { + std::vector> addSlots; + for (auto slot : slots) { + sptr originalSlot; + result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slot->GetType(), originalSlot); + if ((result == ERR_OK) && (originalSlot != nullptr)) { + continue; + } else { + addSlots.push_back(slot); + } } - item = nullptr; - } - handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().AddNotificationSlots(bundle, innerSlots); })); + if (addSlots.size() == 0) { + result = ERR_OK; + } else { + result = NotificationPreferences::GetInstance().AddNotificationSlots(bundle, addSlots); + } + })); return result; } @@ -572,7 +558,12 @@ ErrCode AdvancedNotificationService::SetDisturbMode(NotificationConstant::Distur if (bundle.empty()) { return ERR_ANS_INVALID_BUNDLE; } - handler_->PostSyncTask(std::bind([&]() { result = NotificationPreferences::GetInstance().SetDisturbMode(mode); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().SetDisturbMode(mode); + if (result == ERR_OK) { + NotificationSubscriberManager::GetInstance()->NotifyDisturbModeChanged(mode); + } + })); return result; } ErrCode AdvancedNotificationService::GetDisturbMode(NotificationConstant::DisturbMode &mode) @@ -654,10 +645,10 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const std::string &bundle) ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { - sptr notification = nullptr; - std::vector keys = GetNotificationKeys(bundle); for (auto key : keys) { + sptr notification = nullptr; + result = RemoveFromNotificationList(key, notification); if (result != ERR_OK) { continue; @@ -687,10 +678,10 @@ ErrCode AdvancedNotificationService::DeleteAll() ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { - sptr notification = nullptr; - std::vector keys = GetNotificationKeys(std::string()); for (auto key : keys) { + sptr notification = nullptr; + result = RemoveFromNotificationList(key, notification); if (result != ERR_OK) { continue; @@ -811,6 +802,20 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle(const std::str return result; } +ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().IsShowBadge(bundle, enabled); })); + return result; +} + ErrCode AdvancedNotificationService::RemoveFromNotificationList(const std::string &bundle, const std::string &label, int notificationId, sptr ¬ification, bool isCancel) { @@ -1022,8 +1027,15 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(const std::str { ANS_LOGD("%{public}s", __FUNCTION__); - if (!IsSystemApp()) { - return ERR_ANS_NON_SYSTEM_APP; + std::string clientBundle = GetClientBundleName(); + if (clientBundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + + if (bundle != clientBundle) { + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } } ErrCode result = ERR_OK; @@ -1116,6 +1128,9 @@ ErrCode AdvancedNotificationService::SetRecentNotificationCount(const std::strin } recentInfo_->recentCount = count; + while(recentInfo_->list.size() > recentInfo_->recentCount) { + recentInfo_->list.pop_back(); + } return ERR_OK; } @@ -1158,7 +1173,7 @@ void AdvancedNotificationService::UpdateRecentNotification(sptr &n if (!isDelete) { if (recentInfo_->list.size() >= recentInfo_->recentCount) { - recentInfo_->list.erase(recentInfo_->list.end()); + recentInfo_->list.pop_back(); } auto recentNotification = std::make_shared(); recentNotification->isActive = true; @@ -1247,5 +1262,115 @@ void AdvancedNotificationService::OnDistributedKvStoreDeathRecipient() std::bind([&]() { NotificationPreferences::GetInstance().OnDistributedKvStoreDeathRecipient(); })); } +ErrCode AdvancedNotificationService::RemoveAllSlots() +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().RemoveNotificationAllSlots(bundle); })); + return result; +} + +ErrCode AdvancedNotificationService::AddSlotByType(NotificationConstant::SlotType slotType) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + + handler_->PostSyncTask(std::bind([&]() { + sptr slot; + result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot); + if ((result == ERR_OK) && (slot != nullptr)) { + return; + } else { + slot = new NotificationSlot(slotType); + std::vector> slots; + slots.push_back(slot); + result = NotificationPreferences::GetInstance().AddNotificationSlots(bundle, slots); + } + })); + return result; +} + +ErrCode AdvancedNotificationService::RemoveNotification( + const std::string &bundle, int uid, int notificationId, const std::string &label) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS; + + handler_->PostSyncTask(std::bind([&]() { + sptr notification = nullptr; + + for (auto record : notificationList_) { + if ((record->notification->GetBundleName() == bundle) && (record->notification->GetUid() == uid) && + (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) { + if (record->request->IsUnremovable()) { + result = ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; + break; + } + notification = record->notification; + notificationList_.remove(record); + result = ERR_OK; + break; + } + } + + if (notification != nullptr) { + int reason = NotificationConstant::CANCEL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); + } + })); + + return result; +} + +ErrCode AdvancedNotificationService::RemoveAllNotifications(const std::string &bundle, int uid) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + handler_->PostSyncTask(std::bind([&]() { + std::vector> removeList; + for (auto record : notificationList_) { + if ((record->notification->GetBundleName() == bundle) && (record->notification->GetUid() == uid) && + !record->request->IsUnremovable()) { + removeList.push_back(record); + } + } + + for (auto record : removeList) { + notificationList_.remove(record); + + if (record->notification != nullptr) { + int reason = NotificationConstant::CANCEL_REASON_DELETE; + UpdateRecentNotification(record->notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason); + } + } + })); + + 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 fca92739b..17025f71d 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -40,7 +40,7 @@ void BundleManagerHelper::OnRemoteDied(const wptr &object) Disconnect(); } -std::string BundleManagerHelper::GetBundleNameByUid(uid_t uid) +std::string BundleManagerHelper::GetBundleNameByUid(int uid) { std::string bundle; @@ -55,7 +55,7 @@ std::string BundleManagerHelper::GetBundleNameByUid(uid_t uid) return bundle; } -bool BundleManagerHelper::IsSystemApp(uid_t uid) +bool BundleManagerHelper::IsSystemApp(int uid) { bool isSystemApp = false; diff --git a/services/ans/src/disturb_filter.cpp b/services/ans/src/disturb_filter.cpp index c6547f081..d5ebca7ba 100644 --- a/services/ans/src/disturb_filter.cpp +++ b/services/ans/src/disturb_filter.cpp @@ -61,6 +61,9 @@ ErrCode DisturbFilter::OnPublish(const std::shared_ptr &reco break; case NotificationConstant::DisturbMode::ALLOW_PRIORITY: break; + case NotificationConstant::DisturbMode::ALLOW_UNKNOWN: + // DO NOTHING + break; default: break; } diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 04d67ccf9..cced15ee4 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -81,8 +81,7 @@ ErrCode NotificationPreferences::AddNotificationSlotGroups( } if (result == ERR_OK && (!preferncesDB_->PutGroupsToDisturbeDB(bundleName, groups))) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - return result; + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } if (result == ERR_OK) { @@ -91,6 +90,25 @@ ErrCode NotificationPreferences::AddNotificationSlotGroups( return result; } +ErrCode NotificationPreferences::AddNotificationBundleProperty(const std::string &bundleName) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + NotificationPreferencesInfo::BundleInfo bundleInfo; + preferencesInfo.SetBundleInfo(bundleInfo); + ErrCode result = ERR_OK; + if (preferncesDB_->PutBundlePropertyToDisturbeDB(bundleInfo)) { + preferencesInfo_ = preferencesInfo; + } else { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + + return result; +} + ErrCode NotificationPreferences::RemoveNotificationSlot( const std::string &bundleName, const NotificationConstant::SlotType &slotType) { @@ -103,8 +121,31 @@ ErrCode NotificationPreferences::RemoveNotificationSlot( result = CheckSlotForRemoveSlot(bundleName, slotType, preferencesInfo); if (result == ERR_OK && (!preferncesDB_->RemoveSlotFromDisturbeDB(bundleName, slotType))) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - return result; + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } + return result; +} + +ErrCode NotificationPreferences::RemoveNotificationAllSlots(const std::string &bundleName) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + ErrCode result = ERR_OK; + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + bundleInfo.RemoveAllSlots(); + if (!preferncesDB_->RemoveAllSlotsFromDisturbeDB(bundleName)) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + } else { + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } if (result == ERR_OK) { @@ -129,8 +170,7 @@ ErrCode NotificationPreferences::RemoveNotificationSlotGroups( } } if (result == ERR_OK && (!preferncesDB_->RemoveGroupsFromDisturbeDB(bundleName, groupIds))) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - return result; + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } if (result == ERR_OK) { @@ -183,8 +223,7 @@ ErrCode NotificationPreferences::UpdateNotificationSlots( } if (result == ERR_OK && (!preferncesDB_->PutSlotsToDisturbeDB(bundleName, slots))) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - return result; + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } if (result == ERR_OK) { @@ -212,8 +251,7 @@ ErrCode NotificationPreferences::UpdateNotificationSlotGroups( } if (result == ERR_OK && (!preferncesDB_->PutGroupsToDisturbeDB(bundleName, groups))) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - return result; + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } if (result == ERR_OK) { @@ -320,12 +358,10 @@ ErrCode NotificationPreferences::GetNotificationAllSlotInSlotGroup( ErrCode NotificationPreferences::IsShowBadge(const std::string &bundleName, bool &enable) { - ErrCode result = ERR_ANS_INVALID_PARAM; if (bundleName.empty()) { - return result; + return ERR_ANS_INVALID_PARAM; } - result = GetBundleProperty(bundleName, BundleType::kBundleShowBadgeType, enable); - return result; + return GetBundleProperty(bundleName, BundleType::BUNDLE_SHOW_BADGE_TYPE, enable); } ErrCode NotificationPreferences::SetShowBadge(const std::string &bundleName, const bool enable) @@ -335,7 +371,7 @@ ErrCode NotificationPreferences::SetShowBadge(const std::string &bundleName, con } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleShowBadgeType, enable); + ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::BUNDLE_SHOW_BADGE_TYPE, enable); if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } @@ -348,8 +384,7 @@ ErrCode NotificationPreferences::GetImportance(const std::string &bundleName, in return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundleType::kBundleImportanceType, importance); - return result; + return GetBundleProperty(bundleName, BundleType::BUNDLE_IMPORTANCE_TYPE, importance); } ErrCode NotificationPreferences::SetImportance(const std::string &bundleName, const int &importance) @@ -358,7 +393,7 @@ ErrCode NotificationPreferences::SetImportance(const std::string &bundleName, co return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleImportanceType, importance); + ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::BUNDLE_IMPORTANCE_TYPE, importance); if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } @@ -370,8 +405,7 @@ ErrCode NotificationPreferences::GetTotalBadgeNums(const std::string &bundleName if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundleType::kBundleBadgeTotalNumType, totalBadgeNum); - return result; + return GetBundleProperty(bundleName, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, totalBadgeNum); } ErrCode NotificationPreferences::SetTotalBadgeNums(const std::string &bundleName, const int num) @@ -380,7 +414,7 @@ ErrCode NotificationPreferences::SetTotalBadgeNums(const std::string &bundleName return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleBadgeTotalNumType, num); + ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, num); if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } @@ -392,8 +426,7 @@ ErrCode NotificationPreferences::GetPrivateNotificationsAllowed(const std::strin if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundleType::kBundlePrivateAllowedType, allow); - return result; + return GetBundleProperty(bundleName, BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE, allow); } ErrCode NotificationPreferences::SetPrivateNotificationsAllowed(const std::string &bundleName, const bool allow) @@ -402,7 +435,7 @@ ErrCode NotificationPreferences::SetPrivateNotificationsAllowed(const std::strin return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundlePrivateAllowedType, allow); + ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE, allow); if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } @@ -414,17 +447,18 @@ ErrCode NotificationPreferences::GetNotificationsEnabledForBundle(const std::str if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundleType::kBundleEnableNotificationType, enabled); - return result; + return GetBundleProperty(bundleName, BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE, enabled); } ErrCode NotificationPreferences::SetNotificationsEnabledForBundle(const std::string &bundleName, const bool enabled) { if (bundleName.empty()) { - return ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + return ERR_ANS_INVALID_PARAM; } + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleEnableNotificationType, enabled); + ErrCode result = + SetBundleProperty(preferencesInfo, bundleName, BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE, enabled); if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; @@ -446,6 +480,10 @@ ErrCode NotificationPreferences::SetNotificationsEnabled(const bool &enabled) if (!preferncesDB_->PutNotificationsEnabled(enabled)) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } return result; } @@ -463,6 +501,10 @@ ErrCode NotificationPreferences::SetDisturbMode(const NotificationConstant::Dist if (!preferncesDB_->PutDisturbMode(mode)) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } return result; } @@ -471,9 +513,13 @@ ErrCode NotificationPreferences::ClearNotificationInRestoreFactorySettings() NotificationPreferencesInfo preferencesInfo = preferencesInfo_; preferencesInfo.ClearBundleInfo(); ErrCode result = ERR_OK; - if (!preferncesDB_->RemoveAllBundleFromDisturbeDB()) { + if (!preferncesDB_->RemoveAllDataFromDisturbeDB()) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } return result; } @@ -485,7 +531,6 @@ ErrCode NotificationPreferences::CheckSlotForCreateSlot(const std::string &bundl return ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; } - ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; if (!preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { bundleInfo.SetBundleName(bundleName); @@ -493,7 +538,7 @@ ErrCode NotificationPreferences::CheckSlotForCreateSlot(const std::string &bundl bundleInfo.SetSlot(slot); preferencesInfo.SetBundleInfo(bundleInfo); - return result; + return ERR_OK; } ErrCode NotificationPreferences::CheckGroupForCreateSlotGroup(const std::string &bundleName, @@ -509,21 +554,19 @@ ErrCode NotificationPreferences::CheckGroupForCreateSlotGroup(const std::string return ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID; } - ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; if (!preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { bundleInfo.SetBundleName(bundleName); } else { if (bundleInfo.GetGroupSize() >= MAX_SLOT_GROUP_NUM) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM; - return result; + return ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM; } } bundleInfo.SetGroup(group); preferencesInfo.SetBundleInfo(bundleInfo); - return result; + return ERR_OK; } ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const std::string &bundleName, @@ -582,11 +625,12 @@ ErrCode NotificationPreferences::CheckSlotForUpdateSlot(const std::string &bundl bundleInfo.SetSlot(slot); preferencesInfo.SetBundleInfo(bundleInfo); } else { + ANS_LOGE("Notification slot type does not exist."); result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; } } else { - ANS_LOGE("Notification slot is nullptr."); - return ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + ANS_LOGE("Notification bundle does not exsit."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } return result; @@ -607,7 +651,7 @@ ErrCode NotificationPreferences::CheckGroupForUpdateSlotGroup(const std::string } } else { ANS_LOGE("Notification slot is nullptr."); - return ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } return result; } @@ -634,34 +678,30 @@ ErrCode NotificationPreferences::SaveBundleProperty(NotificationPreferencesInfo: { bool storeDBResult = true; switch (type) { - case BundleType::kBundleImportanceType: + case BundleType::BUNDLE_IMPORTANCE_TYPE: bundleInfo.SetImportance(value); storeDBResult = preferncesDB_->PutImportance(bundleName, value); break; - case BundleType::kBundleBadgeTotalNumType: + case BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE: bundleInfo.SetBadgeTotalNum(value); storeDBResult = preferncesDB_->PutTotalBadgeNums(bundleName, value); break; - case BundleType::kBundleShowBadgeType: + case BundleType::BUNDLE_SHOW_BADGE_TYPE: bundleInfo.SetIsShowBadge(value); storeDBResult = preferncesDB_->PutShowBadge(bundleName, value); break; - case BundleType::kBundlePrivateAllowedType: + case BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE: bundleInfo.SetIsPrivateAllowed(value); storeDBResult = preferncesDB_->PutPrivateNotificationsAllowed(bundleName, value); break; - case BundleType::kBundleEnableNotificationType: + case BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE: bundleInfo.SetEnableNotification(value); storeDBResult = preferncesDB_->PutNotificationsEnabledForBundle(bundleName, value); break; default: break; } - ErrCode result = ERR_OK; - if (!storeDBResult) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - } - return result; + return storeDBResult ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } template @@ -672,19 +712,19 @@ ErrCode NotificationPreferences::GetBundleProperty( NotificationPreferencesInfo::BundleInfo bundleInfo; if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { switch (type) { - case BundleType::kBundleImportanceType: + case BundleType::BUNDLE_IMPORTANCE_TYPE: value = bundleInfo.GetImportance(); break; - case BundleType::kBundleBadgeTotalNumType: + case BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE: value = bundleInfo.GetBadgeTotalNum(); break; - case BundleType::kBundleShowBadgeType: + case BundleType::BUNDLE_SHOW_BADGE_TYPE: value = bundleInfo.GetIsShowBadge(); break; - case BundleType::kBundlePrivateAllowedType: + case BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE: value = bundleInfo.GetIsPrivateAllowed(); break; - case BundleType::kBundleEnableNotificationType: + case BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE: value = bundleInfo.GetEnableNotification(); break; default: @@ -701,7 +741,8 @@ ErrCode NotificationPreferences::GetBundleProperty( void NotificationPreferences::OnDistributedKvStoreDeathRecipient() { if (preferncesDB_ != nullptr) { - preferncesDB_->StoreDeathRecipient(preferencesInfo_); + if (preferncesDB_->StoreDeathRecipient()) { + } } } diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 98c595654..d9a9a8f16 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -27,59 +27,59 @@ namespace Notification { const std::map &, std::string &)>> NotificationPreferencesDatabase::slotMap_ = { - {kSlotGroupId, + {KEY_SLOT_GROUPID, std::bind(&NotificationPreferencesDatabase::ParseSlotGroupId, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kSlotDescription, + {KEY_SLOT_DESCRIPTION, std::bind(&NotificationPreferencesDatabase::ParseSlotDescription, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kSlotLevel, + {KEY_SLOT_LEVEL, std::bind(&NotificationPreferencesDatabase::ParseSlotLevel, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kSlotShowBadge, + {KEY_SLOT_SHOW_BADGE, std::bind(&NotificationPreferencesDatabase::ParseSlotShowBadge, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kSlotEnableLight, + {KEY_SLOT_ENABLE_LIGHT, std::bind(&NotificationPreferencesDatabase::ParseSlotEnableLight, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kSlotEnableVrbration, + {KEY_SLOT_ENABLE_VRBRATION, std::bind(&NotificationPreferencesDatabase::ParseSlotEnableVrbration, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kSlotLedLightColor, + {KEY_SLOT_LED_LIGHT_COLOR, std::bind(&NotificationPreferencesDatabase::ParseSlotLedLightColor, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kSlotLockscreenVisibleness, + {KEY_SLOT_LOCKSCREEN_VISIBLENESS, std::bind(&NotificationPreferencesDatabase::ParseSlotLockscreenVisibleness, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kSlotSound, + {KEY_SLOT_SOUND, std::bind(&NotificationPreferencesDatabase::ParseSlotSound, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kSlotVibrationSytle, + {KEY_SLOT_VIBRATION_STYLE, std::bind(&NotificationPreferencesDatabase::ParseSlotVibrationSytle, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kSlotEnableBypassDnd, + {KEY_SLOT_VIBRATION_STYLE, std::bind(&NotificationPreferencesDatabase::ParseSlotEnableBypassDnd, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}}; const std::map> NotificationPreferencesDatabase::bundleMap_ = { - {kBundleName, + {KEY_BUNDLE_NAME, std::bind(&NotificationPreferencesDatabase::ParseBundleName, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kBundleImportance, + {KEY_BUNDLE_IMPORTANCE, std::bind(&NotificationPreferencesDatabase::ParseBundleImportance, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kBundleShowBadge, + {KEY_BUNDLE_SHOW_BADGE, std::bind(&NotificationPreferencesDatabase::ParseBundleShowBadge, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kBundleBadgeTotalNum, + {KEY_BUNDLE_BADGE_TOTAL_NUM, std::bind(&NotificationPreferencesDatabase::ParseBundleBadgeNum, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kBundlePrivateAllowed, + {KEY_BUNDLE_PRIVATE_ALLOWED, std::bind(&NotificationPreferencesDatabase::ParseBundlePrivateAllowed, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, - {kBundleEnableNotification, + {KEY_BUNDLE_ENABLE_NOTIFICATION, std::bind(&NotificationPreferencesDatabase::ParseBundleEnableNotification, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}}; @@ -98,7 +98,7 @@ void NotificationPreferencesDatabase::TryTwice(const std::function 0) { - OHOS::DistributedKv::Status status = GetKvStore(); - if (status == OHOS::DistributedKv::Status::SUCCESS && kvStorePtr_ != nullptr) { - return true; - } - ANS_LOGW("CheckKvStore, Times: %{public}d", tryTimes); - usleep(SLEEP_INTERVAL); - tryTimes--; - } - return false; -} - bool NotificationPreferencesDatabase::PutSlotsToDisturbeDB( const std::string &bundleName, const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + ANS_LOGE("Bundle name is null."); return false; } if (slots.empty()) { - ANS_LOGE("Slot is empty"); + ANS_LOGE("Slot is empty."); return false; } @@ -182,7 +166,7 @@ bool NotificationPreferencesDatabase::PutSlotsToDisturbeDB( } if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } OHOS::DistributedKv::Status status = kvStorePtr_->PutBatch(entries); @@ -193,12 +177,12 @@ bool NotificationPreferencesDatabase::PutGroupsToDisturbeDB( const std::string &bundleName, const std::vector> &groups) { if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + ANS_LOGE("Bundle name is null."); return false; } if (groups.empty()) { - ANS_LOGE("Slot is empty"); + ANS_LOGE("Slot is empty."); return false; } @@ -212,17 +196,49 @@ bool NotificationPreferencesDatabase::PutGroupsToDisturbeDB( } if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } OHOS::DistributedKv::Status status = kvStorePtr_->PutBatch(entries); return (status == OHOS::DistributedKv::Status::SUCCESS); } +bool NotificationPreferencesDatabase::PutBundlePropertyToDisturbeDB( + const NotificationPreferencesInfo::BundleInfo &bundleInfo) +{ + if (bundleInfo.GetBundleName().empty()) { + ANS_LOGE("Bundle name is null."); + return false; + } + + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr."); + return false; + } + + std::string bundleKeyStr = KEY_BUNDLE_LABEL + bundleInfo.GetBundleName(); + bool result = false; + GetValueFromDisturbeDB(bundleKeyStr, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { + switch (status) { + case OHOS::DistributedKv::Status::KEY_NOT_FOUND: { + result = PutBundleToDisturbeDB(bundleInfo.GetBundleName(), bundleInfo); + break; + } + case OHOS::DistributedKv::Status::SUCCESS: { + ANS_LOGE("Current bundle has exsited."); + break; + } + default: + break; + } + }); + return result; +} + bool NotificationPreferencesDatabase::PutShowBadge(const std::string &bundleName, const bool &enable) { if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + ANS_LOGE("Bundle name is null."); return false; } @@ -230,14 +246,14 @@ bool NotificationPreferencesDatabase::PutShowBadge(const std::string &bundleName return false; } OHOS::DistributedKv::Status status = - PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleShowBadgeType, enable); + PutBundlePropertyToDisturbeDB(bundleName, BundleType::BUNDLE_SHOW_BADGE_TYPE, enable); return (status == OHOS::DistributedKv::Status::SUCCESS); } bool NotificationPreferencesDatabase::PutImportance(const std::string &bundleName, const int &importance) { if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + ANS_LOGE("Bundle name is null."); return false; } @@ -245,14 +261,14 @@ bool NotificationPreferencesDatabase::PutImportance(const std::string &bundleNam return false; } OHOS::DistributedKv::Status status = - PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleImportanceType, importance); + PutBundlePropertyToDisturbeDB(bundleName, BundleType::BUNDLE_IMPORTANCE_TYPE, importance); return (status == OHOS::DistributedKv::Status::SUCCESS); } bool NotificationPreferencesDatabase::PutTotalBadgeNums(const std::string &bundleName, const int &totalBadgeNum) { if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + ANS_LOGE("Bundle name is null."); return false; } @@ -261,14 +277,14 @@ bool NotificationPreferencesDatabase::PutTotalBadgeNums(const std::string &bundl } OHOS::DistributedKv::Status status = - PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleBadgeTotalNumType, totalBadgeNum); + PutBundlePropertyToDisturbeDB(bundleName, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, totalBadgeNum); return (status == OHOS::DistributedKv::Status::SUCCESS); } bool NotificationPreferencesDatabase::PutPrivateNotificationsAllowed(const std::string &bundleName, const bool &allow) { if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + ANS_LOGE("Bundle name is null."); return false; } @@ -276,7 +292,7 @@ bool NotificationPreferencesDatabase::PutPrivateNotificationsAllowed(const std:: return false; } OHOS::DistributedKv::Status status = - PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundlePrivateAllowedType, allow); + PutBundlePropertyToDisturbeDB(bundleName, BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE, allow); return (status == OHOS::DistributedKv::Status::SUCCESS); } @@ -285,7 +301,7 @@ bool NotificationPreferencesDatabase::PutNotificationsEnabledForBundle( const std::string &bundleName, const bool &enabled) { if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + ANS_LOGE("Bundle name is null."); return false; } @@ -294,18 +310,18 @@ bool NotificationPreferencesDatabase::PutNotificationsEnabledForBundle( } OHOS::DistributedKv::Status status = - PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleEnableNotificationType, enabled); + PutBundlePropertyToDisturbeDB(bundleName, BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE, enabled); return (status == OHOS::DistributedKv::Status::SUCCESS); } bool NotificationPreferencesDatabase::PutNotificationsEnabled(const bool &enabled) { if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } - OHOS::DistributedKv::Key enableKey(kEnable); + OHOS::DistributedKv::Key enableKey(KEY_ENABLE_ALL_NOTIFICATION); OHOS::DistributedKv::Value enableValue(std::to_string(enabled)); OHOS::DistributedKv::Status status; status = kvStorePtr_->Put(enableKey, enableValue); @@ -319,11 +335,11 @@ bool NotificationPreferencesDatabase::PutNotificationsEnabled(const bool &enable bool NotificationPreferencesDatabase::PutDisturbMode(const NotificationConstant::DisturbMode &mode) { if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } - OHOS::DistributedKv::Key disturbModeKey(kDisturbMode); + OHOS::DistributedKv::Key disturbModeKey(KEY_DISTURB_MODE); OHOS::DistributedKv::Value disturbModeValue(std::to_string(mode)); OHOS::DistributedKv::Status status; status = kvStorePtr_->Put(disturbModeKey, disturbModeValue); @@ -338,7 +354,7 @@ void NotificationPreferencesDatabase::GetValueFromDisturbeDB( const std::string &key, std::function funcion) { if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return; } @@ -362,7 +378,7 @@ void NotificationPreferencesDatabase::GetValueFromDisturbeDB( const std::string &key, std::function funcion) { if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return; } @@ -375,12 +391,14 @@ void NotificationPreferencesDatabase::GetValueFromDisturbeDB( bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleName) { - std::string bundleKeyStr = kBundleLabel + bundleName; + std::string bundleKeyStr = KEY_BUNDLE_LABEL + bundleName; bool result = true; GetValueFromDisturbeDB(bundleKeyStr, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { switch (status) { case OHOS::DistributedKv::Status::KEY_NOT_FOUND: { - result = PutBundleToDisturbeDB(bundleName); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(bundleName); + result = PutBundleToDisturbeDB(bundleName, bundleInfo); break; } case OHOS::DistributedKv::Status::SUCCESS: { @@ -395,19 +413,27 @@ bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleName) return result; } -bool NotificationPreferencesDatabase::InitBundlePropertyValueToDisturbeDB(const std::string &bundleName) +bool NotificationPreferencesDatabase::PutBundlePropertyValueToDisturbeDB( + const NotificationPreferencesInfo::BundleInfo &bundleInfo) { std::vector entries; - GenerateEntry(GenerateBundleKey(bundleName, kBundleName), bundleName, entries); - GenerateEntry(GenerateBundleKey(bundleName, kBundleBadgeTotalNum), std::to_string(BUNDLE_BADGE_TOTAL_NUM), entries); - GenerateEntry(GenerateBundleKey(bundleName, kBundleImportance), std::to_string(BUNDLE_IMPORTANCE), entries); - GenerateEntry(GenerateBundleKey(bundleName, kBundleShowBadge), std::to_string(BUNDLE_SHOW_BADGE), entries); + std::string bundleName = bundleInfo.GetBundleName(); + GenerateEntry(GenerateBundleKey(bundleName, KEY_BUNDLE_NAME), bundleName, entries); + GenerateEntry(GenerateBundleKey(bundleName, KEY_BUNDLE_BADGE_TOTAL_NUM), + std::to_string(bundleInfo.GetBadgeTotalNum()), + entries); GenerateEntry( - GenerateBundleKey(bundleName, kBundlePrivateAllowed), std::to_string(BUNDLE_PRIVATE_ALLOWED), entries); + GenerateBundleKey(bundleName, KEY_BUNDLE_IMPORTANCE), std::to_string(bundleInfo.GetImportance()), entries); GenerateEntry( - GenerateBundleKey(bundleName, kBundleEnableNotification), std::to_string(BUNDLE_ENABLE_NOTIFICATION), entries); + GenerateBundleKey(bundleName, KEY_BUNDLE_SHOW_BADGE), std::to_string(bundleInfo.GetIsShowBadge()), entries); + GenerateEntry(GenerateBundleKey(bundleName, KEY_BUNDLE_PRIVATE_ALLOWED), + std::to_string(bundleInfo.GetIsPrivateAllowed()), + entries); + GenerateEntry(GenerateBundleKey(bundleName, KEY_BUNDLE_ENABLE_NOTIFICATION), + std::to_string(bundleInfo.GetEnableNotification()), + entries); if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } OHOS::DistributedKv::Status status = kvStorePtr_->PutBatch(entries); @@ -425,12 +451,12 @@ bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreference ParseEnableAllNotification(info); if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } OHOS::DistributedKv::Status status; std::vector entries; - status = kvStorePtr_->GetEntries({kBundleLabel}, entries); + status = kvStorePtr_->GetEntries({KEY_BUNDLE_LABEL}, entries); if (status != OHOS::DistributedKv::Status::SUCCESS) { ANS_LOGE("Get Bundle Info failed."); return false; @@ -439,11 +465,11 @@ bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreference return true; } -bool NotificationPreferencesDatabase::RemoveAllBundleFromDisturbeDB() +bool NotificationPreferencesDatabase::RemoveAllDataFromDisturbeDB() { ANS_LOGD("%{public}s", __FUNCTION__); if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } OHOS::DistributedKv::Status status = dataManager_.DeleteKvStore(appId_, storeId_); @@ -454,13 +480,13 @@ bool NotificationPreferencesDatabase::RemoveBundleFromDisturbeDB(const std::stri { ANS_LOGD("%{public}s", __FUNCTION__); if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } OHOS::DistributedKv::Status status; std::vector entries; - status = kvStorePtr_->GetEntries({kAnsBundle + kUnderLine + bundleName + kUnderLine}, entries); + status = kvStorePtr_->GetEntries({KEY_ANS_BUNDLE + KEY_UNDER_LINE + bundleName + KEY_UNDER_LINE}, entries); if (status != OHOS::DistributedKv::Status::SUCCESS) { ANS_LOGE("Get Bundle Info failed."); @@ -472,7 +498,7 @@ bool NotificationPreferencesDatabase::RemoveBundleFromDisturbeDB(const std::stri keys.push_back(iter.key); } - OHOS::DistributedKv::Key bundleKey({kBundleLabel + kBundleName + kUnderLine + bundleName}); + OHOS::DistributedKv::Key bundleKey({KEY_BUNDLE_LABEL + KEY_BUNDLE_NAME + KEY_UNDER_LINE + bundleName}); keys.push_back(bundleKey); status = kvStorePtr_->DeleteBatch(keys); if (status != OHOS::DistributedKv::Status::SUCCESS) { @@ -487,19 +513,19 @@ bool NotificationPreferencesDatabase::RemoveSlotFromDisturbeDB( { ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + ANS_LOGE("Bundle name is null."); return false; } if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } OHOS::DistributedKv::Status status; std::vector slotentries; - std::string slotType = kSlotType + std::to_string(type); - status = kvStorePtr_->GetEntries({GenerateSlotKey(bundleName, slotType) + kUnderLine}, slotentries); + std::string slotType = std::to_string(type); + status = kvStorePtr_->GetEntries({GenerateSlotKey(bundleName, slotType) + KEY_UNDER_LINE}, slotentries); if (status != DistributedKv::Status::SUCCESS) { return false; } @@ -508,30 +534,60 @@ bool NotificationPreferencesDatabase::RemoveSlotFromDisturbeDB( keys.push_back(iter.key); } - std::string slotTypeKey = GenerateSlotKey(bundleName, kSlotType, std::to_string(type)); - OHOS::DistributedKv::Key slotIdKey({slotTypeKey}); - keys.push_back(slotIdKey); status = kvStorePtr_->DeleteBatch(keys); if (status != OHOS::DistributedKv::Status::SUCCESS) { ANS_LOGE("delete bundle Info failed."); return false; } - ANS_LOGD("%{public}s remove status %{public}d", __FUNCTION__, status); - + ANS_LOGD("%{public}s remove slot status %{public}d", __FUNCTION__, status); return true; } +bool NotificationPreferencesDatabase::RemoveAllSlotsFromDisturbeDB(const std::string &bundleName) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + if (bundleName.empty()) { + ANS_LOGE("Bundle name is null."); + return false; + } + + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr."); + return false; + } + + OHOS::DistributedKv::Status status; + std::vector slotsEntries; + status = kvStorePtr_->GetEntries({GenerateSlotKey(bundleName) + KEY_UNDER_LINE}, slotsEntries); + if (status != DistributedKv::Status::SUCCESS) { + return false; + } + std::vector keys; + for (auto iter : slotsEntries) { + keys.push_back(iter.key); + } + + status = kvStorePtr_->DeleteBatch(keys); + ANS_LOGD("%{public}s remove all slots status %{public}d", __FUNCTION__, status); + return (status == OHOS::DistributedKv::Status::SUCCESS); +} + bool NotificationPreferencesDatabase::RemoveGroupsFromDisturbeDB( const std::string &bundleName, const std::vector &groupIds) { if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + ANS_LOGE("Bundle name is null."); + return false; + } + + if (groupIds.empty()) { + ANS_LOGE("Group id is empty."); return false; } if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } @@ -545,25 +601,22 @@ bool NotificationPreferencesDatabase::RemoveGroupsFromDisturbeDB( } OHOS::DistributedKv::Status status = kvStorePtr_->DeleteBatch(keys); - if (status != OHOS::DistributedKv::Status::SUCCESS) { - ANS_LOGE("delete bundle Info failed."); - return false; - } - return result; + ANS_LOGD("%{public}s remove groups status %{public}d", __FUNCTION__, status); + return (status == OHOS::DistributedKv::Status::SUCCESS); } bool NotificationPreferencesDatabase::GetRemoveGroupKeysFromDisturbeDB( const std::string &bundleName, const std::string &groupId, std::vector &keys) { if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } OHOS::DistributedKv::Status status; std::vector groupentries; std::string slotKeyStr = GenerateGroupKey(bundleName, groupId); - status = kvStorePtr_->GetEntries({slotKeyStr + kUnderLine}, groupentries); + status = kvStorePtr_->GetEntries({slotKeyStr + KEY_UNDER_LINE}, groupentries); if (status != DistributedKv::Status::SUCCESS) { return false; } @@ -571,34 +624,16 @@ bool NotificationPreferencesDatabase::GetRemoveGroupKeysFromDisturbeDB( keys.push_back(iter.key); } - OHOS::DistributedKv::Key groupIdKey({GenerateGroupKey(bundleName, kGroupId + kUnderLine + groupId)}); - keys.push_back(groupIdKey); - return true; } -void NotificationPreferencesDatabase::SubscribeDeathRecipient( - const std::shared_ptr &callback) -{ - dataManager_.RegisterKvStoreServiceDeathRecipient(callback); -} - -void NotificationPreferencesDatabase::UnsubscribeDeathRecipient( - const std::shared_ptr &callback) -{ - dataManager_.UnRegisterKvStoreServiceDeathRecipient(callback); -} - -bool NotificationPreferencesDatabase::StoreDeathRecipient(NotificationPreferencesInfo &info) +bool NotificationPreferencesDatabase::StoreDeathRecipient() { ANS_LOGW("distribute remote died"); - bool result = ResetStore(); - if (result) { - ParseFromDisturbeDB(info); - } else { - ANS_LOGE("db try connect failed"); + if (kvStorePtr_ != nullptr) { + kvStorePtr_ = nullptr; } - return result; + return true; } template @@ -607,52 +642,52 @@ OHOS::DistributedKv::Status NotificationPreferencesDatabase::PutBundlePropertyTo { std::string keyStr; switch (type) { - case BundleType::kBundleBadgeTotalNumType: - keyStr = GenerateBundleKey(bundleName, kBundleBadgeTotalNum); + case BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE: + keyStr = GenerateBundleKey(bundleName, KEY_BUNDLE_BADGE_TOTAL_NUM); break; - case BundleType::kBundleImportanceType: - keyStr = GenerateBundleKey(bundleName, kBundleImportance); + case BundleType::BUNDLE_IMPORTANCE_TYPE: + keyStr = GenerateBundleKey(bundleName, KEY_BUNDLE_IMPORTANCE); break; - case BundleType::kBundleShowBadgeType: - keyStr = GenerateBundleKey(bundleName, kBundleShowBadge); + case BundleType::BUNDLE_SHOW_BADGE_TYPE: + keyStr = GenerateBundleKey(bundleName, KEY_BUNDLE_SHOW_BADGE); break; - case BundleType::kBundlePrivateAllowedType: - keyStr = GenerateBundleKey(bundleName, kBundlePrivateAllowed); + case BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE: + keyStr = GenerateBundleKey(bundleName, KEY_BUNDLE_PRIVATE_ALLOWED); break; - case BundleType::kBundleEnableNotificationType: - keyStr = GenerateBundleKey(bundleName, kBundleEnableNotification); + case BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE: + keyStr = GenerateBundleKey(bundleName, KEY_BUNDLE_ENABLE_NOTIFICATION); break; default: break; } - OHOS::DistributedKv::Status status; OHOS::DistributedKv::Key key(keyStr); OHOS::DistributedKv::Value value(std::to_string(t)); if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); - status = OHOS::DistributedKv::Status::ERROR; - return status; + ANS_LOGE("KvStore is nullptr."); + return OHOS::DistributedKv::Status::ERROR; } + OHOS::DistributedKv::Status status; status = kvStorePtr_->Put(key, value); return status; } -bool NotificationPreferencesDatabase::PutBundleToDisturbeDB(const std::string &bundleName) +bool NotificationPreferencesDatabase::PutBundleToDisturbeDB( + const std::string &bundleName, const NotificationPreferencesInfo::BundleInfo &bundleInfo) { if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } - ANS_LOGD("Key not fund, so create a bundle. bundle key is %{public}s", bundleName.c_str()); - OHOS::DistributedKv::Key bundleKey(kBundleLabel + bundleName); + ANS_LOGD("Key not fund, so create a bundle, bundle key is %{public}s.", bundleName.c_str()); + OHOS::DistributedKv::Key bundleKey(KEY_BUNDLE_LABEL + bundleName); OHOS::DistributedKv::Value bundleValue(bundleName); if (kvStorePtr_->Put(bundleKey, bundleValue) != OHOS::DistributedKv::Status::SUCCESS) { ANS_LOGE("Store bundle name to db is failed."); return false; } - if (!InitBundlePropertyValueToDisturbeDB(bundleName)) { + if (!PutBundlePropertyValueToDisturbeDB(bundleInfo)) { return false; } @@ -660,7 +695,7 @@ bool NotificationPreferencesDatabase::PutBundleToDisturbeDB(const std::string &b } void NotificationPreferencesDatabase::GenerateEntry( - const std::string &key, const std::string &value, std::vector &entries) + const std::string &key, const std::string &value, std::vector &entries) const { OHOS::DistributedKv::Entry entry; OHOS::DistributedKv::Key dbKey(key); @@ -674,7 +709,7 @@ bool NotificationPreferencesDatabase::SlotToEntry( const std::string &bundleName, const sptr &slot, std::vector &entries) { if (slot == nullptr) { - ANS_LOGE("Notification group is nullptr"); + ANS_LOGE("Notification group is nullptr."); return false; } @@ -686,32 +721,35 @@ bool NotificationPreferencesDatabase::SlotToEntry( return true; } -void NotificationPreferencesDatabase::GenerateSlotEntry( - const std::string &bundleName, const sptr &slot, std::vector &entries) +void NotificationPreferencesDatabase::GenerateSlotEntry(const std::string &bundleName, + const sptr &slot, std::vector &entries) const { - std::string slotType = kSlotType + kUnderLine + std::to_string(slot->GetType()); - GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotType), std::to_string(slot->GetType()), entries); - GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotId), slot->GetId(), entries); - GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotGroupId), slot->GetSlotGroup(), entries); - GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotName), slot->GetName(), entries); - GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotDescription), slot->GetDescription(), entries); - GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotLevel), std::to_string(slot->GetLevel()), entries); - GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotShowBadge), std::to_string(slot->IsShowBadge()), entries); + std::string slotType = std::to_string(slot->GetType()); + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_TYPE), std::to_string(slot->GetType()), entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_ID), slot->GetId(), entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_GROUPID), slot->GetSlotGroup(), entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_NAME), slot->GetName(), entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_DESCRIPTION), slot->GetDescription(), entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_LEVEL), std::to_string(slot->GetLevel()), entries); GenerateEntry( - GenerateSlotKey(bundleName, slotType, kSlotEnableLight), std::to_string(slot->CanEnableLight()), entries); + GenerateSlotKey(bundleName, slotType, KEY_SLOT_SHOW_BADGE), std::to_string(slot->IsShowBadge()), entries); GenerateEntry( - GenerateSlotKey(bundleName, slotType, kSlotEnableVrbration), std::to_string(slot->CanVibrate()), entries); + GenerateSlotKey(bundleName, slotType, KEY_SLOT_ENABLE_LIGHT), std::to_string(slot->CanEnableLight()), entries); GenerateEntry( - GenerateSlotKey(bundleName, slotType, kSlotLedLightColor), std::to_string(slot->GetLedLightColor()), entries); - GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotLockscreenVisibleness), + GenerateSlotKey(bundleName, slotType, KEY_SLOT_ENABLE_VRBRATION), std::to_string(slot->CanVibrate()), entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_LED_LIGHT_COLOR), + std::to_string(slot->GetLedLightColor()), + entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_LOCKSCREEN_VISIBLENESS), std::to_string(static_cast(slot->GetLockScreenVisibleness())), entries); - GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotSound), slot->GetSound().ToString(), entries); - GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotEnableBypassDnd), + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_SOUND), slot->GetSound().ToString(), entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_VIBRATION_STYLE), std::to_string(slot->IsEnableBypassDnd()), entries); - GenerateEntry( - GenerateSlotKey(bundleName, slotType, kSlotVibrationSytle), VectorToString(slot->GetVibrationStyle()), entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, KEY_SLOT_VIBRATION_STYLE), + VectorToString(slot->GetVibrationStyle()), + entries); } bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleName, @@ -719,7 +757,7 @@ bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleName { if (group == nullptr) { - ANS_LOGE("Notification group is nullptr"); + ANS_LOGE("Notification group is nullptr."); return false; } @@ -732,38 +770,37 @@ bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleName } void NotificationPreferencesDatabase::GenerateGroupEntry(const std::string &bundleName, - const sptr &group, std::vector &entries) + const sptr &group, std::vector &entries) const { - std::string groupId = kGroupId + kUnderLine + group->GetId(); - std::string groupLebal = group->GetId().append(kUnderLine); - GenerateEntry(GenerateGroupKey(bundleName, groupId), group->GetId(), entries); - GenerateEntry(GenerateGroupKey(bundleName, groupLebal + kGroupName), group->GetName(), entries); - GenerateEntry(GenerateGroupKey(bundleName, groupLebal + kGroupDescription), group->GetDescription(), entries); + std::string groupLebal = group->GetId().append(KEY_UNDER_LINE); + GenerateEntry(GenerateGroupKey(bundleName, groupLebal + KEY_GROUP_ID), group->GetId(), entries); + GenerateEntry(GenerateGroupKey(bundleName, groupLebal + KEY_GROUP_NAME), group->GetName(), entries); + GenerateEntry(GenerateGroupKey(bundleName, groupLebal + KEY_GROUP_DESCRIPTION), group->GetDescription(), entries); GenerateEntry( - GenerateGroupKey(bundleName, groupLebal + kGroupDisable), std::to_string(group->IsDisabled()), entries); + GenerateGroupKey(bundleName, groupLebal + KEY_GROUP_DISABLE), std::to_string(group->IsDisabled()), entries); } void NotificationPreferencesDatabase::ParseBundleFromDistureDB( NotificationPreferencesInfo &info, const std::vector &entries) { if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return; } for (auto item : entries) { std::string bundleName = item.value.ToString(); - ANS_LOGD("bundle name is %{public}s", bundleName.c_str()); + ANS_LOGD("Bundle name is %{public}s.", bundleName.c_str()); std::vector bundleEntries; kvStorePtr_->GetEntries({GenerateBundleKey(bundleName)}, bundleEntries); - ANS_LOGD("bundle key is %{public}s", GenerateBundleKey(bundleName).c_str()); + ANS_LOGD("Bundle key is %{public}s.", GenerateBundleKey(bundleName).c_str()); NotificationPreferencesInfo::BundleInfo bunldeInfo; for (auto bundleEntry : bundleEntries) { - if (bundleEntry.key.ToString().find(kSlot) != std::string::npos) { + if (bundleEntry.key.ToString().find(KEY_SLOT) != std::string::npos) { ParseSlotFromDisturbeDB(bunldeInfo, bundleName, bundleEntry); - } else if (bundleEntry.key.ToString().find(kGroup) != std::string::npos) { + } else if (bundleEntry.key.ToString().find(KEY_GROUP) != std::string::npos) { ParseGroupFromDisturbeDB(bunldeInfo, bundleName, bundleEntry); } else { - ParseBundlePropertyFromDisturbeDB(bunldeInfo, bundleEntry.key, bundleEntry.value); + ParseBundlePropertyFromDisturbeDB(bunldeInfo, bundleName, bundleEntry); } } @@ -775,14 +812,14 @@ void NotificationPreferencesDatabase::ParseSlotFromDisturbeDB(NotificationPrefer const std::string &bundleName, const OHOS::DistributedKv::Entry &entry) { std::string slotKey = entry.key.ToString(); - - NotificationConstant::SlotType slotType = - static_cast(stoi(SubUniqueIdentifyFromString(slotKey), nullptr)); + std::string typeStr = SubUniqueIdentifyFromString(GenerateSlotKey(bundleName) + KEY_UNDER_LINE, slotKey); + NotificationConstant::SlotType slotType = static_cast(StringToInt(typeStr)); sptr slot = nullptr; if (!bundleInfo.GetSlot(slotType, slot)) { slot = new NotificationSlot(slotType); } - ParseSlot(slot, entry); + std::string findString = GenerateSlotKey(bundleName, typeStr) + KEY_UNDER_LINE; + ParseSlot(findString, slot, entry); bundleInfo.SetSlot(slot); } @@ -790,15 +827,15 @@ void NotificationPreferencesDatabase::ParseGroupFromDisturbeDB(NotificationPrefe const std::string &bundleName, const OHOS::DistributedKv::Entry &entry) { if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return; } std::string groupKey = entry.key.ToString(); - std::string groupId = SubUniqueIdentifyFromString(groupKey); + std::string groupId = SubUniqueIdentifyFromString(GenerateGroupKey(bundleName) + KEY_UNDER_LINE, groupKey); sptr group; if (!bundleInfo.GetGroup(groupId, group)) { std::string groupName; - std::string groupNameKey = GenerateGroupKey(bundleName, groupId + kUnderLine + kGroupName); + std::string groupNameKey = GenerateGroupKey(bundleName, groupId + KEY_UNDER_LINE + KEY_GROUP_NAME); GetValueFromDisturbeDB( groupNameKey, [&groupName](OHOS::DistributedKv::Value &value) { groupName = value.ToString(); }); if (groupName.empty()) { @@ -808,17 +845,17 @@ void NotificationPreferencesDatabase::ParseGroupFromDisturbeDB(NotificationPrefe group = new NotificationSlotGroup(groupId, groupName); } - ParseGroupDescription(group, entry); + ParseGroupDescription(bundleName, group, entry); bundleInfo.SetGroup(group); } void NotificationPreferencesDatabase::ParseBundlePropertyFromDisturbeDB( - NotificationPreferencesInfo::BundleInfo &bundleInfo, const OHOS::DistributedKv::Key &key, - const OHOS::DistributedKv::Value &value) + NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleName, + const OHOS::DistributedKv::Entry &entry) { - std::string typeStr = FindLastString(key.ToString()); - std::string valueStr = value.ToString(); - ANS_LOGD("db key = %{public}s and type str %{public}s", key.ToString().c_str(), typeStr.c_str()); + std::string typeStr = FindLastString(GenerateBundleKey(bundleName), entry.key.ToString()); + std::string valueStr = entry.value.ToString(); + ANS_LOGD("DB key = %{public}s , type str %{public}s", entry.key.ToString().c_str(), typeStr.c_str()); auto iter = bundleMap_.find(typeStr); if (iter != bundleMap_.end()) { @@ -827,11 +864,12 @@ void NotificationPreferencesDatabase::ParseBundlePropertyFromDisturbeDB( } } -void NotificationPreferencesDatabase::ParseSlot(sptr &slot, const OHOS::DistributedKv::Entry &entry) +void NotificationPreferencesDatabase::ParseSlot( + const std::string &findString, sptr &slot, const OHOS::DistributedKv::Entry &entry) { - std::string typeStr = FindLastString(entry.key.ToString()); + std::string typeStr = FindLastString(findString, entry.key.ToString()); std::string valueStr = entry.value.ToString(); - ANS_LOGD("db key = %{public}s , type str %{public}s , value is %{public}s ", + ANS_LOGD("db key = %{public}s , %{public}s : %{public}s ", entry.key.ToString().c_str(), typeStr.c_str(), entry.value.ToString().c_str()); @@ -843,12 +881,13 @@ void NotificationPreferencesDatabase::ParseSlot(sptr &slot, co } } -std::string NotificationPreferencesDatabase::FindLastString(const std::string &inputString) const +std::string NotificationPreferencesDatabase::FindLastString( + const std::string &findString, const std::string &inputString) const { std::string keyStr; - size_t pos = inputString.find_last_of(kUnderLine); + size_t pos = findString.size(); if (pos != std::string::npos) { - keyStr = inputString.substr(pos + 1); + keyStr = inputString.substr(pos); } return keyStr; } @@ -856,7 +895,7 @@ std::string NotificationPreferencesDatabase::FindLastString(const std::string &i std::string NotificationPreferencesDatabase::VectorToString(const std::vector &data) const { std::stringstream streamStr; - std::copy(data.begin(), data.end(), std::ostream_iterator(streamStr, kUnderLine.c_str())); + std::copy(data.begin(), data.end(), std::ostream_iterator(streamStr, KEY_UNDER_LINE.c_str())); return streamStr.str(); } @@ -866,33 +905,44 @@ void NotificationPreferencesDatabase::StringToVector(const std::string &str, std return; } - if (str.find_first_of(kUnderLine) != std::string::npos) { - std::string str1 = str.substr(0, str.find_first_of(kUnderLine)); - std::string afterStr = str.substr(str.find_first_of(kUnderLine) + 1); - data.push_back(stoi(str1, nullptr)); + if (str.find_first_of(KEY_UNDER_LINE) != std::string::npos) { + std::string str1 = str.substr(0, str.find_first_of(KEY_UNDER_LINE)); + std::string afterStr = str.substr(str.find_first_of(KEY_UNDER_LINE) + 1); + data.push_back(StringToInt(str1)); StringToVector(afterStr, data); } } +int NotificationPreferencesDatabase::StringToInt(const std::string &str) const +{ + int value = 0; + try { + value = stoi(str, nullptr); + } catch (const std::exception &e) { + ANS_LOGW("Stoi error is %{public}s.", e.what()); + } + return value; +} + std::string NotificationPreferencesDatabase::GenerateSlotKey( const std::string &bundleKey, const std::string &type, const std::string &subType) const { /*slot key * - * ans_bundle_bundlename_slot_type_0_id - * ans_bundle_bundlename_slot_type_0_des - * ans_bundle_bundlename_slot_type_1_id - * ans_bundle_bundlename_slot_type_1_des + * KEY_ANS_BUNDLE_bundlename_slot_type_0_id + * KEY_ANS_BUNDLE_bundlename_slot_type_0_des + * KEY_ANS_BUNDLE_bundlename_slot_type_1_id + * KEY_ANS_BUNDLE_bundlename_slot_type_1_des * */ - std::string key = GenerateBundleKey(bundleKey).append(kSlot); + std::string key = GenerateBundleKey(bundleKey).append(KEY_SLOT).append(KEY_UNDER_LINE).append(KEY_SLOT_TYPE); if (!type.empty()) { - key.append(kUnderLine).append(type); + key.append(KEY_UNDER_LINE).append(type); } if (!subType.empty()) { - key.append(kUnderLine).append(subType); + key.append(KEY_UNDER_LINE).append(subType); } - ANS_LOGD("Slot key is : %{public}s", key.c_str()); + ANS_LOGD("Slot key is : %{public}s.", key.c_str()); return key; } @@ -901,15 +951,16 @@ std::string NotificationPreferencesDatabase::GenerateGroupKey( { /*group key * - * ans_bundle_bundlename_group_group_id0_name - * ans_bundle_bundlename_group_group_id1_name + * KEY_ANS_BUNDLE_bundlename_group_id_id0_id: + * KEY_ANS_BUNDLE_bundlename_group_id_id0_name: + * KEY_ANS_BUNDLE_bundlename_group_id_id1_name * */ - std::string key = GenerateBundleKey(bundleKey).append(kGroup); + std::string key = GenerateBundleKey(bundleKey).append(KEY_GROUP).append(KEY_UNDER_LINE).append(KEY_GROUP_ID); if (!type.empty()) { - key.append(kUnderLine).append(type); + key.append(KEY_UNDER_LINE).append(type); } - ANS_LOGD("Group key is %{public}s", key.c_str()); + ANS_LOGD("Group key is %{public}s.", key.c_str()); return key; } @@ -918,27 +969,30 @@ std::string NotificationPreferencesDatabase::GenerateBundleKey( { /*bundle key * - * label_ans_bundle_name = "" - * ans_bundle_bundlename_ - * ans_bundle_bundlename_ - * ans_bundle_bundlename_ - * ans_bundle_bundlename_ + * label_KEY_ANS_KEY_BUNDLE_NAME = "" + * KEY_ANS_BUNDLE_bundlename_ + * KEY_ANS_BUNDLE_bundlename_ + * KEY_ANS_BUNDLE_bundlename_ + * KEY_ANS_BUNDLE_bundlename_ * */ - std::string key = std::string().append(kAnsBundle).append(kUnderLine).append(bundleName).append(kUnderLine); + std::string key = + std::string().append(KEY_ANS_BUNDLE).append(KEY_UNDER_LINE).append(bundleName).append(KEY_UNDER_LINE); if (!type.empty()) { key.append(type); } - ANS_LOGD("Bundle key : %{public}s", key.c_str()); + ANS_LOGD("Bundle key : %{public}s.", key.c_str()); return key; } -std::string NotificationPreferencesDatabase::SubUniqueIdentifyFromString(const std::string &keyStr) const +std::string NotificationPreferencesDatabase::SubUniqueIdentifyFromString( + const std::string &findString, const std::string &keyStr) const { std::string slotType; - size_t pos = keyStr.find_last_of(kUnderLine); + std::string tempStr = FindLastString(findString, keyStr); + size_t pos = tempStr.find_last_of(KEY_UNDER_LINE); if (pos != std::string::npos) { - slotType = FindLastString(keyStr.substr(0, pos)); + slotType = tempStr.substr(0, pos); } return slotType; @@ -946,41 +1000,44 @@ std::string NotificationPreferencesDatabase::SubUniqueIdentifyFromString(const s void NotificationPreferencesDatabase::ParseDisturbeMode(NotificationPreferencesInfo &info) { - GetValueFromDisturbeDB(kDisturbMode, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { - if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { - PutDisturbMode(info.GetDisturbMode()); - } else if (status == OHOS::DistributedKv::Status::SUCCESS) { - if (!value.ToString().empty()) { - info.SetDisturbMode(static_cast(stoi(value.ToString(), nullptr))); + GetValueFromDisturbeDB( + KEY_DISTURB_MODE, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { + if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { + PutDisturbMode(info.GetDisturbMode()); + } else if (status == OHOS::DistributedKv::Status::SUCCESS) { + if (!value.ToString().empty()) { + info.SetDisturbMode(static_cast(StringToInt(value.ToString()))); + } + } else { + ANS_LOGW("Parse disturbe mode failed, use defalut value."); } - } else { - ANS_LOGD("Parse disturbe mode failed, use defalut value."); - } - }); + }); } void NotificationPreferencesDatabase::ParseEnableAllNotification(NotificationPreferencesInfo &info) { - GetValueFromDisturbeDB(kEnable, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { - if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { - PutNotificationsEnabled(info.GetEnabledAllNotification()); - } else if (status == OHOS::DistributedKv::Status::SUCCESS) { - if (!value.ToString().empty()) { - info.SetEnabledAllNotification(static_cast(stoi(value.ToString(), nullptr))); + GetValueFromDisturbeDB( + KEY_ENABLE_ALL_NOTIFICATION, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { + if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { + PutNotificationsEnabled(info.GetEnabledAllNotification()); + } else if (status == OHOS::DistributedKv::Status::SUCCESS) { + if (!value.ToString().empty()) { + info.SetEnabledAllNotification(static_cast(StringToInt(value.ToString()))); + } + } else { + ANS_LOGW("Parse enable all notification failed, use defalut value."); } - } else { - ANS_LOGD("Parse enable all notification failed, use defalut value."); - } - }); + }); } void NotificationPreferencesDatabase::ParseGroupDescription( - sptr &group, const OHOS::DistributedKv::Entry &entry) + const std::string &bundleName, sptr &group, const OHOS::DistributedKv::Entry &entry) { - std::string typeStr = FindLastString(entry.key.ToString()); + std::string findStr = GenerateGroupKey(bundleName, group->GetId()) + KEY_UNDER_LINE; + std::string typeStr = FindLastString(findStr, entry.key.ToString()); std::string valueStr = entry.value.ToString(); - if (!typeStr.compare(kGroupDescription)) { - ANS_LOGD("SetGroupDescription is %{public}s", valueStr.c_str()); + if (!typeStr.compare(KEY_GROUP_DESCRIPTION)) { + ANS_LOGD("SetGroupDescription is %{public}s.", valueStr.c_str()); group->SetDescription(valueStr); } } @@ -988,93 +1045,93 @@ void NotificationPreferencesDatabase::ParseGroupDescription( void NotificationPreferencesDatabase::ParseBundleName( NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const { - ANS_LOGD("SetBundleName bundle name is %{public}s", value.c_str()); + ANS_LOGD("SetBundleName bundle name is %{public}s.", value.c_str()); bundleInfo.SetBundleName(value); } void NotificationPreferencesDatabase::ParseBundleImportance( NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const { - ANS_LOGD("SetBundleImportance bundle importance is %{public}s", value.c_str()); - bundleInfo.SetImportance(static_cast(stoi(value, nullptr))); + ANS_LOGD("SetBundleImportance bundle importance is %{public}s.", value.c_str()); + bundleInfo.SetImportance(static_cast(StringToInt(value))); } void NotificationPreferencesDatabase::ParseBundleShowBadge( NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const { - ANS_LOGD("SetBundleShowBadge bundle show badge is %{public}s", value.c_str()); - bundleInfo.SetIsShowBadge(static_cast(stoi(value, nullptr))); + ANS_LOGD("SetBundleShowBadge bundle show badge is %{public}s.", value.c_str()); + bundleInfo.SetIsShowBadge(static_cast(StringToInt(value))); } void NotificationPreferencesDatabase::ParseBundleBadgeNum( NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const { - ANS_LOGD("SetBundleBadgeNum bundle badge num is %{public}s", value.c_str()); - bundleInfo.SetBadgeTotalNum(stoi(value, nullptr)); + ANS_LOGD("SetBundleBadgeNum bundle badge num is %{public}s.", value.c_str()); + bundleInfo.SetBadgeTotalNum(StringToInt(value)); } void NotificationPreferencesDatabase::ParseBundlePrivateAllowed( NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const { - ANS_LOGD("SetBundlePrivateAllowed bundle private allowed is %{public}s", value.c_str()); - bundleInfo.SetIsPrivateAllowed(static_cast(stoi(value, nullptr))); + ANS_LOGD("SetBundlePrivateAllowed bundle private allowed is %{public}s.", value.c_str()); + bundleInfo.SetIsPrivateAllowed(static_cast(StringToInt(value))); } void NotificationPreferencesDatabase::ParseBundleEnableNotification( NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const { - ANS_LOGD("SetBundleEnableNotification bundle enable is %{public}s", value.c_str()); - bundleInfo.SetEnableNotification(static_cast(stoi(value, nullptr))); + ANS_LOGD("SetBundleEnableNotification bundle enable is %{public}s.", value.c_str()); + bundleInfo.SetEnableNotification(static_cast(StringToInt(value))); } void NotificationPreferencesDatabase::ParseSlotGroupId(sptr &slot, const std::string &value) const { - ANS_LOGD("slot group id is %{public}s", value.c_str()); + ANS_LOGD("ParseSlotGroupId slot group id is %{public}s.", value.c_str()); std::string slotGroupId = value; slot->SetSlotGroup(slotGroupId); } void NotificationPreferencesDatabase::ParseSlotDescription(sptr &slot, const std::string &value) const { - ANS_LOGD("slot des is %{public}s", value.c_str()); + ANS_LOGD("ParseSlotDescription slot des is %{public}s.", value.c_str()); std::string slotDescription = value; slot->SetDescription(slotDescription); } void NotificationPreferencesDatabase::ParseSlotLevel(sptr &slot, const std::string &value) const { - ANS_LOGD("slot level is %{public}s", value.c_str()); - NotificationSlot::NotificationLevel level = static_cast(stoi(value, nullptr)); + ANS_LOGD("ParseSlotLevel slot level is %{public}s.", value.c_str()); + NotificationSlot::NotificationLevel level = static_cast(StringToInt(value)); slot->SetLevel(level); } void NotificationPreferencesDatabase::ParseSlotShowBadge(sptr &slot, const std::string &value) const { - ANS_LOGD("slot show badge is %{public}s", value.c_str()); - bool showBadge = static_cast(stoi(value, nullptr)); + ANS_LOGD("ParseSlotShowBadge slot show badge is %{public}s.", value.c_str()); + bool showBadge = static_cast(StringToInt(value)); slot->EnableBadge(showBadge); } void NotificationPreferencesDatabase::ParseSlotEnableLight(sptr &slot, const std::string &value) const { - ANS_LOGD("slot enable light is %{public}s", value.c_str()); - bool enableLight = static_cast(stoi(value, nullptr)); + ANS_LOGD("ParseSlotEnableLight slot enable light is %{public}s.", value.c_str()); + bool enableLight = static_cast(StringToInt(value)); slot->SetEnableLight(enableLight); } void NotificationPreferencesDatabase::ParseSlotEnableVrbration( sptr &slot, const std::string &value) const { - ANS_LOGD("slot enable vir is %{public}s", value.c_str()); - bool enableVrbration = static_cast(stoi(value, nullptr)); + ANS_LOGD("ParseSlotEnableVrbration slot enable vir is %{public}s.", value.c_str()); + bool enableVrbration = static_cast(StringToInt(value)); slot->SetEnableVibration(enableVrbration); } void NotificationPreferencesDatabase::ParseSlotLedLightColor( sptr &slot, const std::string &value) const { - ANS_LOGD("slot led is %{public}s", value.c_str()); - int32_t ledLightColor = static_cast(stoi(value, nullptr)); + ANS_LOGD("ParseSlotLedLightColor slot led is %{public}s.", value.c_str()); + int32_t ledLightColor = static_cast(StringToInt(value)); slot->SetLedLightColor(ledLightColor); } @@ -1082,9 +1139,9 @@ void NotificationPreferencesDatabase::ParseSlotLockscreenVisibleness( sptr &slot, const std::string &value) const { - ANS_LOGD("slot visible is %{public}s", value.c_str()); + ANS_LOGD("ParseSlotLockscreenVisibleness slot visible is %{public}s.", value.c_str()); NotificationConstant::VisiblenessType visible = - static_cast(stoi(value, nullptr)); + static_cast(StringToInt(value)); slot->SetLockscreenVisibleness(visible); } @@ -1106,8 +1163,8 @@ void NotificationPreferencesDatabase::ParseSlotVibrationSytle( void NotificationPreferencesDatabase::ParseSlotEnableBypassDnd( sptr &slot, const std::string &value) const { - ANS_LOGD("slot by pass dnd is %{public}s", value.c_str()); - bool enable = static_cast(stoi(value, nullptr)); + ANS_LOGD("ParseSlotEnableBypassDnd slot by pass dnd is %{public}s.", value.c_str()); + bool enable = static_cast(StringToInt(value)); slot->EnableBypassDnd(enable); } } // namespace Notification diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index 1202b2870..0e0cd5afd 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -179,6 +179,11 @@ bool NotificationPreferencesInfo::BundleInfo::RemoveSlot(const NotificationConst return false; } +void NotificationPreferencesInfo::BundleInfo::RemoveAllSlots() +{ + slots_.clear(); +} + bool NotificationPreferencesInfo::BundleInfo::RemoveSlotGroup(const std::string &groupId) { auto iter = groups_.find(groupId); diff --git a/services/ans/src/notification_slot_filter.cpp b/services/ans/src/notification_slot_filter.cpp index 6231cccb2..fe660df51 100644 --- a/services/ans/src/notification_slot_filter.cpp +++ b/services/ans/src/notification_slot_filter.cpp @@ -32,14 +32,26 @@ ErrCode NotificationSlotFilter::OnPublish(const std::shared_ptrslot != nullptr) { if (record->slot->CanEnableLight()) { + record->notification->SetEnableLight(true); record->notification->SetLedLightColor(record->slot->GetLedLightColor()); + } else { + record->notification->SetEnableLight(false); } if (record->slot->CanVibrate()) { + record->notification->SetEnableViration(true); record->notification->SetVibrationStyle(record->slot->GetVibrationStyle()); + } else { + record->notification->SetEnableViration(false); } - record->notification->SetSound(record->slot->GetSound()); + auto sound = record->slot->GetSound(); + if (!sound.ToString().empty()) { + record->notification->SetEnableSound(true); + record->notification->SetSound(record->slot->GetSound()); + } else { + record->notification->SetEnableSound(false); + } record->request->SetVisibleness(record->slot->GetLockScreenVisibleness()); } else { diff --git a/services/ans/test/unittest/bundle_manager_helper_test.cpp b/services/ans/test/unittest/bundle_manager_helper_test.cpp index b64140c3f..7f4a8dda5 100644 --- a/services/ans/test/unittest/bundle_manager_helper_test.cpp +++ b/services/ans/test/unittest/bundle_manager_helper_test.cpp @@ -53,7 +53,7 @@ void BundleManagerHelperTest::TearDown() */ HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00100, Function | SmallTest | Level1) { - uid_t callingUid = IPCSkeleton::GetCallingUid(); + int callingUid = IPCSkeleton::GetCallingUid(); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); EXPECT_EQ(bundleManager->GetBundleNameByUid(callingUid), "bundleName"); } @@ -65,7 +65,7 @@ HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00100, Function | Smal */ HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00200, Function | SmallTest | Level1) { - uid_t callingUid = IPCSkeleton::GetCallingUid(); + int callingUid = IPCSkeleton::GetCallingUid(); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); EXPECT_TRUE(bundleManager->IsSystemApp(callingUid)); } diff --git a/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h b/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h index 39c56acab..538e9f839 100755 --- a/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h +++ b/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h @@ -33,9 +33,9 @@ public: // remove current thread from work loop. static void StopWorkThread(); - static pid_t GetCallingPid(); + static int GetCallingPid(); - static pid_t GetCallingUid(); + static int GetCallingUid(); static std::string GetLocalDeviceID(); @@ -55,7 +55,7 @@ public: static bool SetCallingIdentity(std::string &identity); - static void SetCallingUid(pid_t uid); + static void SetCallingUid(int uid); }; } // namespace OHOS #endif // OHOS_IPC_IPC_SKELETON_H 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 b7aa3f474..76b1944ff 100644 --- a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -31,12 +31,12 @@ BundleManagerHelper::~BundleManagerHelper() void BundleManagerHelper::OnRemoteDied(const wptr &object) {} -std::string BundleManagerHelper::GetBundleNameByUid(uid_t uid) +std::string BundleManagerHelper::GetBundleNameByUid(int uid) { return 1000 < uid && uid < 1500 ? "" : "bundleName"; } -bool BundleManagerHelper::IsSystemApp(uid_t uid) +bool BundleManagerHelper::IsSystemApp(int uid) { return 500 < uid && uid < 1000 ? false : true; } diff --git a/services/ans/test/unittest/mock/mock_ipc.cpp b/services/ans/test/unittest/mock/mock_ipc.cpp index 3c2bc08da..3e4a9f4bd 100644 --- a/services/ans/test/unittest/mock/mock_ipc.cpp +++ b/services/ans/test/unittest/mock/mock_ipc.cpp @@ -20,20 +20,20 @@ namespace OHOS { using namespace IPC_SINGLE; #endif -pid_t uid_ = 1; +int uid_ = 1; -pid_t IPCSkeleton::GetCallingUid() +int IPCSkeleton::GetCallingUid() { return uid_; } -pid_t IPCSkeleton::GetCallingPid() +int IPCSkeleton::GetCallingPid() { uid_ = 1; return uid_; } -void IPCSkeleton::SetCallingUid(pid_t uid) +void IPCSkeleton::SetCallingUid(int uid) { uid_ = uid; } diff --git a/services/ans/test/unittest/notification_preferences_database_test.cpp b/services/ans/test/unittest/notification_preferences_database_test.cpp index b2ad8c94a..eaea00c06 100644 --- a/services/ans/test/unittest/notification_preferences_database_test.cpp +++ b/services/ans/test/unittest/notification_preferences_database_test.cpp @@ -320,9 +320,9 @@ HWTEST_F(NotificationPreferencesDatabaseTest, CreateExsitBundle_00100, Function * @tc.name : * @tc.desc : RemoveAllBundleFromDisturbeDB_00100 */ -HWTEST_F(NotificationPreferencesDatabaseTest, RemoveAllBundleFromDisturbeDB_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, RemoveAllDataFromDisturbeDB_00100, Function | SmallTest | Level1) { - EXPECT_EQ(true, preferncesDB_->RemoveAllBundleFromDisturbeDB()); + EXPECT_EQ(true, preferncesDB_->RemoveAllDataFromDisturbeDB()); } /** @@ -406,9 +406,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, GetRemoveGroupKeys_00100, Function */ HWTEST_F(NotificationPreferencesDatabaseTest, StoreDeathRecipient_00100, Function | SmallTest | Level1) { - NotificationPreferencesInfo preferencesInfo_{}; - NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - EXPECT_EQ(true, preferncesDB_->StoreDeathRecipient(preferencesInfo)); + EXPECT_EQ(true, preferncesDB_->StoreDeathRecipient()); } /** @@ -434,22 +432,12 @@ HWTEST_F(NotificationPreferencesDatabaseTest, CheckKvStore_00100, Function | Sma /** * @tc.number : * @tc.name : - * @tc.desc : ResetStore_00100 + * @tc.desc : PutBundlePropertyValueToDisturbeDB_00100 */ -HWTEST_F(NotificationPreferencesDatabaseTest, ResetStore_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, PutBundlePropertyValueToDisturbeDB_00100, Function | SmallTest | Level1) { - EXPECT_EQ(true, preferncesDB_->ResetStore()); -} - -/** - * @tc.number : - * @tc.name : - * @tc.desc : InitBundlePropertyValueToDisturbeDB_00100 - */ -HWTEST_F(NotificationPreferencesDatabaseTest, InitBundlePropertyValueToDisturbeDB_00100, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName"; - EXPECT_EQ(true, preferncesDB_->InitBundlePropertyValueToDisturbeDB(bundleName)); + NotificationPreferencesInfo::BundleInfo info; + EXPECT_EQ(true, preferncesDB_->PutBundlePropertyValueToDisturbeDB(info)); } /** @@ -500,7 +488,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, ParseGroupFromDisturbeDB_00100, Fu { NotificationPreferencesInfo::BundleInfo bundleInfo; bundleInfo.SetBundleName("BundleName"); - // preferncesDB_->ParseGroupFromDisturbeDB(bundleInfo, std::string()); // TODO Q + // preferncesDB_->ParseGroupFromDisturbeDB(bundleInfo, std::string()); // TODO �������Q�� EXPECT_EQ("BundleName", bundleInfo.GetBundleName()); } diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp index bc99a3773..b8f13f4cb 100644 --- a/services/test/moduletest/ans_module_test.cpp +++ b/services/test/moduletest/ans_module_test.cpp @@ -1,3 +1,17 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #include #include diff --git a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp index 5df99fa52..5fef8d274 100644 --- a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp @@ -30,12 +30,12 @@ BundleManagerHelper::~BundleManagerHelper() void BundleManagerHelper::OnRemoteDied(const wptr &object) {} -std::string BundleManagerHelper::GetBundleNameByUid(uid_t uid) +std::string BundleManagerHelper::GetBundleNameByUid(int uid) { return "bundleName"; } -bool BundleManagerHelper::IsSystemApp(uid_t uid) +bool BundleManagerHelper::IsSystemApp(int uid) { return true; } diff --git a/services/test/moduletest/mock/mock_ipc.cpp b/services/test/moduletest/mock/mock_ipc.cpp index 1acbe4a3f..3eec05102 100644 --- a/services/test/moduletest/mock/mock_ipc.cpp +++ b/services/test/moduletest/mock/mock_ipc.cpp @@ -19,9 +19,9 @@ namespace OHOS { #ifdef CONFIG_IPC_SINGLE using namespace IPC_SINGLE; #endif -pid_t IPCSkeleton::GetCallingUid() +int IPCSkeleton::GetCallingUid() { - pid_t uid = 1; + int uid = 1; return uid; } } // namespace OHOS -- Gitee