diff --git a/README_zh.md b/README_zh.md index 740832be15e7eab30d5093100e201cd8af2c5ca8..4004597ce4ad23b8d4a3048c726a2ce9bed72300 100644 --- a/README_zh.md +++ b/README_zh.md @@ -2,43 +2,50 @@ ## 简介 -OpenHarmony通过ANS(Advanced Notification Service,通知系统服务)对通知类型的消息进行管理,支持多种通知类型,包括文本,长文本,多文本,图片,社交,媒体等。所有系统服务以及应用都可以通过通知接口发送通知消息,用户可以通过SystemUI系统APP查看所有通知消息。 为应用程序提供订阅、发布、取消订阅的能力。 +OpenHarmony通过ANS(Advanced Notification Service,通知系统服务)对通知类型的消息进行管理,支持多种通知类型,包括文本,长文本,多文本,图片,社交,媒体等。所有系统服务以及应用都可以通过通知接口发送通知消息,用户可以通过SystemUI查看所有通知消息。 通知常见的使用场景: - 显示接收到短消息、即时消息等。 - 显示应用的推送消息,如广告、版本更新等。 -- 显示当前正在进行的事件,如播放音乐、导航、下载等。 +- 显示当前正在进行的事件,如导航、下载等。 ### 架构图 -![](figures\ans_logical_architecture_diagram.png "通知服务架构图") +![](figures/ans_logical_architecture_diagram.png) ## 目录 ``` /base/notification/ans_standard/ -├── innerkits # 对内接口目录 -├── kits # 对外接口目录 +├── frameworks # 接口实现 +├── interfaces +│ ├── innerkits # 对内接口目录 +│ └── kits # 对外接口目录 ├── sa_profile # 组件服务配置 ├── services # 组件服务实现 -├── tools # 组件工具实现 -│── ohos.build # 组件编译脚本 +└── tools # 组件工具实现 ``` ## 使用说明 -以下模块的JS接口为非正式API,仅供SystemUI等系统应用使用,不排除对这些接口进行变更的可能性,后续版本将提供正式API。 +ANS支持4种类型的通道,分别为: +- 社交通讯 +- 服务提醒 +- 内容资讯 +- 其他 -- notificationSlot.d.ts -- notificationRequest.d.ts -- notificationContent.d.ts -- notificationActionButton.ts -- triggerInfo.d.ts -- wantAgentInfo.d.ts -- @ohos.notification.d.ts -- @ohos.wantAgent.d.ts +应用开发者可以根据使用场景创建通道。通道创建后,提醒方式均为系统默认提醒方式。终端用户可以通过设置应用调整各通道的提醒方式。 + +应用开发者发可发布以下类型的通知: +- 普通文本 +- 长文本 +- 图片 +- 多行文本 +- 社交 + +并且可调整通知的分发时间、角标数字、分组、触发事件等属性。 ## 相关仓 @@ -46,3 +53,8 @@ OpenHarmony通过ANS(Advanced Notification Service,通知系统服务)对 **notification_ans_standard** +[aafwk\_standard](https://gitee.com/openharmony/aafwk_standard) + +[appexecfwk\_standard](https://gitee.com/openharmony/appexecfwk_standard) + +[distributeddatamgr\_datamgr](https://gitee.com/openharmony/distributeddatamgr_datamgr) \ No newline at end of file diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index 4f52df4d5346907427031355b7ef86149d79b32b..f630d47e49280435910f67417f94a55ece784256 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -28,6 +28,7 @@ config("public_ans_core_config") { "${interfaces_path}/innerkits/ans/native/include", "${interfaces_path}/innerkits/wantAgent/include", "//utils/native/base/include", + "//third_party/jsoncpp/include", ] } @@ -44,6 +45,7 @@ ohos_shared_library("ans_core") { "${frameworks_path}/ans/native/src/notification.cpp", "${frameworks_path}/ans/native/src/notification_action_button.cpp", "${frameworks_path}/ans/native/src/notification_basic_content.cpp", + "${frameworks_path}/ans/native/src/notification_bundle_option.cpp", "${frameworks_path}/ans/native/src/notification_constant.cpp", "${frameworks_path}/ans/native/src/notification_content.cpp", "${frameworks_path}/ans/native/src/notification_conversational_content.cpp", @@ -72,6 +74,7 @@ ohos_shared_library("ans_core") { "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/frameworks/ans/core/include/ans_manager_death_recipient.h b/frameworks/ans/core/include/ans_manager_death_recipient.h index f46e8df6f0fa6d0ba4fd657f14ee094bc0f63d54..a726115e961eb032ce4a5685808f3a3667e64857 100644 --- a/frameworks/ans/core/include/ans_manager_death_recipient.h +++ b/frameworks/ans/core/include/ans_manager_death_recipient.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/ans/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index 136bf8cd1bf2aaa5f5057d6c1ced1f05f647596b..c6fe562d80dc7d6b9ddf316751e6fd9b96387a8f 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -21,6 +21,7 @@ #include "ans_subscriber_interface.h" #include "iremote_broker.h" +#include "notification_bundle_option.h" #include "notification_constant.h" #include "notification_request.h" #include "notification_slot.h" @@ -42,14 +43,18 @@ 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; + + virtual ErrCode GetSlotNumAsBundle(const sptr &bundleOption, int &num) = 0; + virtual ErrCode RemoveSlotGroups(const std::vector &groupIds) = 0; virtual ErrCode GetActiveNotifications(std::vector> ¬ifications) = 0; virtual ErrCode GetActiveNotificationNums(int &num) = 0; @@ -69,33 +74,45 @@ public: virtual ErrCode SetPrivateNotificationsAllowed(bool allow) = 0; virtual ErrCode GetPrivateNotificationsAllowed(bool &allow) = 0; virtual ErrCode Delete(const std::string &key) = 0; - virtual ErrCode DeleteByBundle(const std::string &bundle) = 0; + + virtual ErrCode RemoveNotification( + const sptr &bundleOption, int notificationId, const std::string &label) = 0; + + virtual ErrCode RemoveAllNotifications(const sptr &bundleOption) = 0; + + virtual ErrCode DeleteByBundle(const sptr &bundleOption) = 0; + virtual ErrCode DeleteAll() = 0; - virtual ErrCode GetSlotsByBundle(const std::string &bundle, std::vector> &slots) = 0; - virtual ErrCode UpdateSlots(const std::string &bundle, const std::vector> &slots) = 0; + virtual ErrCode GetSlotsByBundle( + const sptr &bundleOption, std::vector> &slots) = 0; + virtual ErrCode UpdateSlots( + const sptr &bundleOption, const std::vector> &slots) = 0; virtual ErrCode UpdateSlotGroups( - const std::string &bundle, const std::vector> &groups) = 0; + const sptr &bundleOption, const std::vector> &groups) = 0; virtual ErrCode SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) = 0; virtual ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) = 0; virtual ErrCode SetNotificationsEnabledForSpecialBundle( - 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; + const std::string &deviceId, const sptr &bundleOption, bool enabled) = 0; + virtual ErrCode SetShowBadgeEnabledForBundle(const sptr &bundleOption, bool enabled) = 0; + virtual ErrCode GetShowBadgeEnabledForBundle(const sptr &bundleOption, 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; virtual ErrCode AreNotificationsSuspended(bool &suspended) = 0; virtual ErrCode GetCurrentAppSorting(sptr &sortingMap) = 0; virtual ErrCode IsAllowedNotify(bool &allowed) = 0; - virtual ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) = 0; + virtual ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, 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, @@ -104,6 +121,7 @@ protected: GET_SLOTS, GET_SLOT_GROUP, GET_SLOT_GROUPS, + GET_SLOT_NUM_AS_BUNDLE, REMOVE_SLOT_GROUPS, GET_ACTIVE_NOTIFICATIONS, GET_ACTIVE_NOTIFICATION_NUMS, @@ -120,6 +138,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 +151,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 d3221d4a0e4d35e9dbd3161269daf7dbcfb6c1c4..b90bc8e955cd548c1e9b4345ee3edab801650b89 100644 --- a/frameworks/ans/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -4,7 +4,7 @@ * 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 + * 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, @@ -32,14 +32,18 @@ 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; + + ErrCode GetSlotNumAsBundle(const sptr &bundleOption, int &num) override; + ErrCode RemoveSlotGroups(const std::vector &groupIds) override; ErrCode GetActiveNotifications(std::vector> ¬ifications) override; ErrCode GetActiveNotificationNums(int &num) override; @@ -58,25 +62,36 @@ public: ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; ErrCode SetPrivateNotificationsAllowed(bool allow) override; ErrCode GetPrivateNotificationsAllowed(bool &allow) override; + + ErrCode RemoveNotification( + const sptr &bundleOption, int notificationId, const std::string &label) override; + + ErrCode RemoveAllNotifications(const sptr &bundleOption) override; + ErrCode Delete(const std::string &key) override; - ErrCode DeleteByBundle(const std::string &bundle) override; + + ErrCode DeleteByBundle(const sptr &bundleOption) override; + ErrCode DeleteAll() override; - ErrCode GetSlotsByBundle(const std::string &bundle, std::vector> &slots) override; - ErrCode UpdateSlots(const std::string &bundle, const std::vector> &slots) override; - ErrCode UpdateSlotGroups( - const std::string &bundle, const std::vector> &groups) override; + ErrCode GetSlotsByBundle( + const sptr &bundleOption, std::vector> &slots) override; + ErrCode UpdateSlots( + const sptr &bundleOption, const std::vector> &slots) override; + ErrCode UpdateSlotGroups(const sptr &bundleOption, + const std::vector> &groups) override; ErrCode SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) override; ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) override; ErrCode SetNotificationsEnabledForSpecialBundle( - 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; + const std::string &deviceId, const sptr &bundleOption, bool enabled) override; + ErrCode SetShowBadgeEnabledForBundle(const sptr &bundleOption, bool enabled) override; + ErrCode GetShowBadgeEnabledForBundle(const sptr &bundleOption, 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; ErrCode GetCurrentAppSorting(sptr &sortingMap) override; ErrCode IsAllowedNotify(bool &allowed) override; - ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) override; + ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override; ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; diff --git a/frameworks/ans/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h index bc9f3b3569b3b53a5870fac3ef9f7d82e4ea249a..4bf53b3866f68512e04d2250fd7fb5ddee6df715 100644 --- a/frameworks/ans/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -38,14 +38,16 @@ 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; + virtual ErrCode GetSlotNumAsBundle(const sptr &bundleOption, int &num) override; virtual ErrCode RemoveSlotGroups(const std::vector &groupIds) override; virtual ErrCode GetActiveNotifications(std::vector> ¬ifications) override; virtual ErrCode GetActiveNotificationNums(int &num) override; @@ -64,19 +66,27 @@ public: virtual ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; virtual ErrCode SetPrivateNotificationsAllowed(bool allow) override; virtual ErrCode GetPrivateNotificationsAllowed(bool &allow) override; + virtual ErrCode RemoveNotification( + const sptr &bundleOption, int notificationId, const std::string &label) override; + virtual ErrCode RemoveAllNotifications(const sptr &bundleOption) override; virtual ErrCode Delete(const std::string &key) override; - virtual ErrCode DeleteByBundle(const std::string &bundle) override; + virtual ErrCode DeleteByBundle(const sptr &bundleOption) override; virtual ErrCode DeleteAll() override; - virtual ErrCode GetSlotsByBundle(const std::string &bundle, std::vector> &slots) override; - virtual ErrCode UpdateSlots(const std::string &bundle, const std::vector> &slots) override; - virtual ErrCode UpdateSlotGroups( - const std::string &bundle, const std::vector> &groups) override; + virtual ErrCode GetSlotsByBundle( + const sptr &bundleOption, std::vector> &slots) override; + virtual ErrCode UpdateSlots( + const sptr &bundleOption, const std::vector> &slots) override; + virtual ErrCode UpdateSlotGroups(const sptr &bundleOption, + const std::vector> &groups) override; virtual ErrCode SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) override; virtual ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) override; virtual ErrCode SetNotificationsEnabledForSpecialBundle( - 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; + const std::string &deviceId, const sptr &bundleOption, bool enabled) override; + virtual ErrCode SetShowBadgeEnabledForBundle( + const sptr &bundleOption, bool enabled) override; + virtual ErrCode GetShowBadgeEnabledForBundle( + const sptr &bundleOption, bool &enabled) override; + virtual ErrCode GetShowBadgeEnabled(bool &enabled) override; virtual ErrCode Subscribe( const sptr &subscriber, const sptr &info) override; virtual ErrCode Unsubscribe( @@ -84,17 +94,20 @@ public: virtual ErrCode AreNotificationsSuspended(bool &suspended) override; virtual ErrCode GetCurrentAppSorting(sptr &sortingMap) override; virtual ErrCode IsAllowedNotify(bool &allowed) override; - virtual ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) override; + virtual ErrCode IsSpecialBundleAllowedNotify( + const sptr &bundleOption, bool &allowed) override; 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); @@ -103,6 +116,7 @@ private: ErrCode HandleGetSlotByType(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetSlotGroup(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetSlotGroups(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetSlotNumAsBundle(MessageParcel &data, MessageParcel &reply); ErrCode HandleRemoveSlotGroups(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetActiveNotifications(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetActiveNotificationNums(MessageParcel &data, MessageParcel &reply); @@ -119,6 +133,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,13 +146,13 @@ 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); ErrCode HandleGetCurrentAppSorting(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply); - ErrCode HandleShellDump(MessageParcel &data, MessageParcel &reply); template diff --git a/frameworks/ans/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h index bea2c2c7f478230e089068ee195cbab891603bf7..c21ec347b4fdf1a1514a69b33679cc104fe4e9eb 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -20,6 +20,7 @@ #include "ans_manager_death_recipient.h" #include "ans_manager_interface.h" +#include "notification_bundle_option.h" #include "notification_request.h" #include "notification_slot.h" #include "notification_slot_group.h" @@ -45,6 +46,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 +71,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. * @@ -129,6 +145,15 @@ public: */ ErrCode GetNotificationSlotGroups(std::vector> &groups); + /** + * Obtains number of slot. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param num Indicates number of slot. + * @return Returns get slot number by bundle result. + */ + ErrCode GetNotificationSlotNumAsBundle(const NotificationBundleOption &bundleOption, int &num); + /** * Publishes a notification. * @note If a notification with the same ID has been published by the current application and has not been deleted, @@ -382,14 +407,35 @@ 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 bundleOption Indicates the bundle name and 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 NotificationBundleOption &bundleOption, 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 bundleOption Indicates the bundle name and uid of the application whose notifications are to be removed. + * @return Returns remove notification result. + */ + ErrCode RemoveAllNotifications(const NotificationBundleOption &bundleOption); + /** * Removes all removable notifications of a specified bundle. * @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 bundleOption Indicates the bundle name and uid of the application whose notifications are to be removed. * @return Returns remove notifications result. */ - ErrCode RemoveNotifications(const std::string &bundleName); + ErrCode RemoveNotificationsByBundle(const NotificationBundleOption &bundleOption); /** * Removes all removable notifications in the system. @@ -401,11 +447,32 @@ public: /** * Returns all notification slots belonging to the specified bundle. * - * @param bundleName Indicates the application name. + * @param bundleOption Indicates the bundle name and uid of the application. * @param slots Indicates a list of notification slots. * @return Returns get notification slots for bundle result. */ - ErrCode GetNotificationSlotsForBundle(const std::string &bundleName, std::vector> &slots); + ErrCode GetNotificationSlotsForBundle( + const NotificationBundleOption &bundleOption, std::vector> &slots); + + /** + * Update all notification slots for the specified bundle. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param slots Indicates a list of new notification slots. + * @return Returns update notification slots for bundle result. + */ + ErrCode UpdateNotificationSlots( + const NotificationBundleOption &bundleOption, const std::vector> &slots); + + /** + * Update all notification slot groups for the specified bundle. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param groups Indicates a list of new notification slot groups. + * @return Returns update notification slot groups for bundle result. + */ + ErrCode UpdateNotificationSlotGroups( + const NotificationBundleOption &bundleOption, const std::vector> &groups); /** * Obtains all active notifications in the current system. The caller must have system permissions to @@ -434,11 +501,11 @@ public: * the current application, no permission is required for calling this method. If bundle specifies another * application, the caller must have system permissions. * - * @param bundle Indicates the bundle name of the application to check. + * @param bundleOption Indicates the bundle name and uid of the application. * @param allowed True if the application has permissions; returns false otherwise. * @return Returns is allowed notify result. */ - ErrCode IsAllowedNotify(const std::string &bundle, bool &allowed); + ErrCode IsAllowedNotify(const NotificationBundleOption &bundleOption, bool &allowed); /** * Sets whether to allow all applications to publish notifications on a specified device. The caller must have @@ -470,7 +537,7 @@ public: * Sets whether to allow a specified application to publish notifications on a specified device. The caller * must have system permissions to call this method. * - * @param bundle Indicates the bundle name of the application. + * @param bundleOption Indicates the bundle name and uid of the application. * @param deviceId Indicates the ID of the device running the application. At present, this parameter can only * be null or an empty string, indicating the current device. * @param enabled Specifies whether to allow the given application to publish notifications. The value @@ -479,7 +546,33 @@ public: * @return Returns set notifications enabled for specified bundle result. */ ErrCode SetNotificationsEnabledForSpecifiedBundle( - const std::string &bundle, const std::string &deviceId, bool enabled); + const NotificationBundleOption &bundleOption, const std::string &deviceId, bool enabled); + + /** + * Sets whether to allow a specified application to to show badge. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param enabled Specifies whether to allow the given application to show badge. + * @return Returns set result. + */ + ErrCode SetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool enabled); + + /** + * Obtains the flag that whether to allow a specified application to to show badge. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param enabled Specifies whether to allow the given application to show badge. + * @return Returns get result. + */ + ErrCode GetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool &enabled); + + /** + * Obtains the flag that whether to allow the current application to to show badge. + * + * @param enabled Specifies whether to allow the given application to show badge. + * @return Returns get result. + */ + ErrCode GetShowBadgeEnabled(bool &enabled); /** * Sets the type of the Do Not Disturb mode. The Do Not Disturb mode type specifies the type of notifications diff --git a/frameworks/ans/core/include/ans_subscriber_interface.h b/frameworks/ans/core/include/ans_subscriber_interface.h index 68808a23b13725c5b8927efff653225f2abbe2fb..539f22a6005d18cf0ff2d8b6e18fb512ea91e182 100644 --- a/frameworks/ans/core/include/ans_subscriber_interface.h +++ b/frameworks/ans/core/include/ans_subscriber_interface.h @@ -4,7 +4,7 @@ * 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 + * 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, diff --git a/frameworks/ans/core/include/ans_subscriber_proxy.h b/frameworks/ans/core/include/ans_subscriber_proxy.h index b4561feefd359609b002795165ba423e837f0190..1774567c236f3946efefca6d0b92785c3a9281e1 100644 --- a/frameworks/ans/core/include/ans_subscriber_proxy.h +++ b/frameworks/ans/core/include/ans_subscriber_proxy.h @@ -4,7 +4,7 @@ * 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 + * 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, diff --git a/frameworks/ans/core/include/ans_subscriber_stub.h b/frameworks/ans/core/include/ans_subscriber_stub.h index 415074d7ce149cc2be535624b00969b60fb8d55e..4d60ccfc00c3c37bd30c4b992bb05eff68ce3035 100644 --- a/frameworks/ans/core/include/ans_subscriber_stub.h +++ b/frameworks/ans/core/include/ans_subscriber_stub.h @@ -4,7 +4,7 @@ * 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 + * 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, diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index c113a25898d9ec5b9c9bd40c2f16a65ac2861b11..bbfa3b448b5bb356bc126f2cbaef5cb27813a9d9 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -14,7 +14,6 @@ */ #include "ans_manager_proxy.h" - #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" @@ -167,6 +166,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 +235,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 +285,7 @@ ErrCode AnsManagerProxy::RemoveAllSlots() return ERR_ANS_PARCELABLE_FAILED; } - return result; + return result; } ErrCode AnsManagerProxy::AddSlotGroups(std::vector> groups) @@ -300,7 +328,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())) { @@ -423,6 +451,45 @@ ErrCode AnsManagerProxy::GetSlotGroups(std::vector> return result; } +ErrCode AnsManagerProxy::GetSlotNumAsBundle(const sptr &bundleOption, int &num) +{ + if (bundleOption == nullptr) { + ANS_LOGW("[GetSlotNumAsBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetSlotNumAsBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteStrongParcelable(bundleOption)) { + ANS_LOGW("[GetSlotNumAsBundle] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_SLOT_NUM_AS_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetShowBadgeEnabledForBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetShowBadgeEnabledForBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadInt32(num)) { + ANS_LOGW("[GetShowBadgeEnabledForBundle] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + ErrCode AnsManagerProxy::RemoveSlotGroups(const std::vector &groupIds) { if (groupIds.empty()) { @@ -922,6 +989,85 @@ ErrCode AnsManagerProxy::GetPrivateNotificationsAllowed(bool &allow) return result; } +ErrCode AnsManagerProxy::RemoveNotification( + const sptr &bundleOption, int notificationId, const std::string &label) +{ + if (bundleOption == nullptr) { + 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.WriteStrongParcelable(bundleOption)) { + ANS_LOGW("[RemoveNotification] fail:: write bundle 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 sptr &bundleOption) +{ + if (bundleOption == nullptr) { + 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.WriteStrongParcelable(bundleOption)) { + ANS_LOGW("[RemoveAllNotifications] fail:: write bundle 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()) { @@ -956,9 +1102,9 @@ ErrCode AnsManagerProxy::Delete(const std::string &key) return result; } -ErrCode AnsManagerProxy::DeleteByBundle(const std::string &bundle) +ErrCode AnsManagerProxy::DeleteByBundle(const sptr &bundleOption) { - if (bundle.empty()) { + if (bundleOption == nullptr) { ANS_LOGW("[DeleteByBundle] fail: bundle is empty."); return ERR_ANS_INVALID_PARAM; } @@ -969,7 +1115,7 @@ ErrCode AnsManagerProxy::DeleteByBundle(const std::string &bundle) return ERR_ANS_PARCELABLE_FAILED; } - if (!data.WriteString(bundle)) { + if (!data.WriteStrongParcelable(bundleOption)) { ANS_LOGW("[DeleteByBundle] fail: write bundle failed"); return ERR_ANS_PARCELABLE_FAILED; } @@ -1014,10 +1160,11 @@ ErrCode AnsManagerProxy::DeleteAll() return result; } -ErrCode AnsManagerProxy::GetSlotsByBundle(const std::string &bundle, std::vector> &slots) +ErrCode AnsManagerProxy::GetSlotsByBundle( + const sptr &bundleOption, std::vector> &slots) { - if (bundle.empty()) { - ANS_LOGW("[GetSlotsByBundle] fail: bundle is empty."); + if (bundleOption == nullptr) { + ANS_LOGW("[GetSlotsByBundle] fail: bundleOption is empty."); return ERR_ANS_INVALID_PARAM; } @@ -1027,7 +1174,7 @@ ErrCode AnsManagerProxy::GetSlotsByBundle(const std::string &bundle, std::vector return ERR_ANS_PARCELABLE_FAILED; } - if (!data.WriteString(bundle)) { + if (!data.WriteParcelable(bundleOption)) { ANS_LOGW("[GetSlotsByBundle] fail:: write bundle failed"); return ERR_ANS_PARCELABLE_FAILED; } @@ -1048,10 +1195,11 @@ ErrCode AnsManagerProxy::GetSlotsByBundle(const std::string &bundle, std::vector return result; } -ErrCode AnsManagerProxy::UpdateSlots(const std::string &bundle, const std::vector> &slots) +ErrCode AnsManagerProxy::UpdateSlots( + const sptr &bundleOption, const std::vector> &slots) { - if (bundle.empty()) { - ANS_LOGW("[UpdateSlots] fail: bundle is empty."); + if (bundleOption == nullptr) { + ANS_LOGW("[UpdateSlots] fail: bundleOption is empty."); return ERR_ANS_INVALID_PARAM; } @@ -1072,8 +1220,8 @@ ErrCode AnsManagerProxy::UpdateSlots(const std::string &bundle, const std::vecto return ERR_ANS_PARCELABLE_FAILED; } - if (!data.WriteString(bundle)) { - ANS_LOGW("[UpdateSlots] fail:: write bundle failed"); + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGW("[UpdateSlots] fail:: write bundleoption failed"); return ERR_ANS_PARCELABLE_FAILED; } @@ -1099,10 +1247,10 @@ ErrCode AnsManagerProxy::UpdateSlots(const std::string &bundle, const std::vecto } ErrCode AnsManagerProxy::UpdateSlotGroups( - const std::string &bundle, const std::vector> &groups) + const sptr &bundleOption, const std::vector> &groups) { - if (bundle.empty()) { - ANS_LOGW("[UpdateSlotGroups] fail: bundle is empty."); + if (bundleOption == nullptr) { + ANS_LOGW("[UpdateSlotGroups] fail: bundleOption is empty."); return ERR_ANS_INVALID_PARAM; } @@ -1123,8 +1271,8 @@ ErrCode AnsManagerProxy::UpdateSlotGroups( return ERR_ANS_PARCELABLE_FAILED; } - if (!data.WriteString(bundle)) { - ANS_LOGW("[UpdateSlotGroups] fail:: write bundle failed."); + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGW("[UpdateSlotGroups] fail:: write bundleOption failed."); return ERR_ANS_PARCELABLE_FAILED; } @@ -1218,10 +1366,10 @@ ErrCode AnsManagerProxy::SetNotificationsEnabledForAllBundles(const std::string } ErrCode AnsManagerProxy::SetNotificationsEnabledForSpecialBundle( - const std::string &deviceId, const std::string &bundleName, bool enabled) + const std::string &deviceId, const sptr &bundleOption, bool enabled) { - if (bundleName.empty()) { - ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: bundleName is empty."); + if (bundleOption == nullptr) { + ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: bundleOption is empty."); return ERR_ANS_INVALID_PARAM; } @@ -1236,8 +1384,8 @@ ErrCode AnsManagerProxy::SetNotificationsEnabledForSpecialBundle( return ERR_ANS_PARCELABLE_FAILED; } - if (!data.WriteString(bundleName)) { - ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: write bundleName failed"); + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: write bundleOption failed"); return ERR_ANS_PARCELABLE_FAILED; } @@ -1248,7 +1396,7 @@ ErrCode AnsManagerProxy::SetNotificationsEnabledForSpecialBundle( MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(SET_NOTIFICATION_ENABLED_FOR_BUNDLE, option, data, reply); + ErrCode result = InnerTransact(SET_NOTIFICATION_ENABLED_FOR_SPECIAL_BUNDLE, option, data, reply); if (result != ERR_OK) { ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: transact ErrCode=%{public}d", result); return ERR_ANS_TRANSACT_FAILED; @@ -1262,9 +1410,9 @@ ErrCode AnsManagerProxy::SetNotificationsEnabledForSpecialBundle( return result; } -ErrCode AnsManagerProxy::SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) +ErrCode AnsManagerProxy::SetShowBadgeEnabledForBundle(const sptr &bundleOption, bool enabled) { - if (bundle.empty()) { + if (bundleOption == nullptr) { ANS_LOGW("[SetShowBadgeEnabledForBundle] fail: bundle is empty."); return ERR_ANS_INVALID_PARAM; } @@ -1275,7 +1423,7 @@ ErrCode AnsManagerProxy::SetShowBadgeEnabledForBundle(const std::string &bundle, return ERR_ANS_PARCELABLE_FAILED; } - if (!data.WriteString(bundle)) { + if (!data.WriteParcelable(bundleOption)) { ANS_LOGW("[SetShowBadgeEnabledForBundle] fail:: write bundle failed"); return ERR_ANS_PARCELABLE_FAILED; } @@ -1301,9 +1449,9 @@ ErrCode AnsManagerProxy::SetShowBadgeEnabledForBundle(const std::string &bundle, return result; } -ErrCode AnsManagerProxy::GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) +ErrCode AnsManagerProxy::GetShowBadgeEnabledForBundle(const sptr &bundleOption, bool &enabled) { - if (bundle.empty()) { + if (bundleOption == nullptr) { ANS_LOGW("[GetShowBadgeEnabledForBundle] fail: bundle is empty."); return ERR_ANS_INVALID_PARAM; } @@ -1314,7 +1462,7 @@ ErrCode AnsManagerProxy::GetShowBadgeEnabledForBundle(const std::string &bundle, return ERR_ANS_PARCELABLE_FAILED; } - if (!data.WriteString(bundle)) { + if (!data.WriteParcelable(bundleOption)) { ANS_LOGW("[GetShowBadgeEnabledForBundle] fail:: write bundle failed"); return ERR_ANS_PARCELABLE_FAILED; } @@ -1340,6 +1488,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) { @@ -1523,9 +1701,9 @@ ErrCode AnsManagerProxy::IsAllowedNotify(bool &allowed) return result; } -ErrCode AnsManagerProxy::IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) +ErrCode AnsManagerProxy::IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) { - if (bundle.empty()) { + if (bundleOption == nullptr) { ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: bundle is empty."); return ERR_ANS_INVALID_PARAM; } @@ -1536,7 +1714,7 @@ ErrCode AnsManagerProxy::IsSpecialBundleAllowedNotify(const std::string &bundle, return ERR_ANS_PARCELABLE_FAILED; } - if (!data.WriteString(bundle)) { + if (!data.WriteParcelable(bundleOption)) { ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: write bundle failed"); return ERR_ANS_PARCELABLE_FAILED; } diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 484dd0a499a2a50293032590f02f95fcfc0d5130..1185b647f71e43c2c84ec7f5df1f76ae850e15df 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -14,7 +14,6 @@ */ #include "ans_manager_stub.h" - #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" @@ -39,6 +38,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; @@ -406,6 +436,28 @@ ErrCode AnsManagerStub::HandleGetSlotGroups(MessageParcel &data, MessageParcel & return ERR_OK; } +ErrCode AnsManagerStub::HandleGetSlotNumAsBundle(MessageParcel &data, MessageParcel &reply) +{ + sptr bundleOption = data.ReadStrongParcelable(); + if (bundleOption == nullptr) { + ANS_LOGW("[HandleGetSlotNumAsBundle] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + int num = 0; + ErrCode result = GetSlotNumAsBundle(bundleOption, num); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetSlotNumAsBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteInt32(num)) { + ANS_LOGW("[HandleGetSlotNumAsBundle] fail: write enabled failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleRemoveSlotGroups(MessageParcel &data, MessageParcel &reply) { std::vector groupIds; @@ -667,6 +719,50 @@ ErrCode AnsManagerStub::HandleGetPrivateNotificationsAllowed(MessageParcel &data return ERR_OK; } +ErrCode AnsManagerStub::HandleRemoveNotification(MessageParcel &data, MessageParcel &reply) +{ + sptr bundleOption = data.ReadStrongParcelable(); + if (bundleOption == nullptr) { + ANS_LOGW("[HandleRemoveNotification] fail: read bundle 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(bundleOption, 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) +{ + sptr bundleOption = data.ReadStrongParcelable(); + if (bundleOption == nullptr) { + ANS_LOGW("[HandleRemoveAllNotifications] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = RemoveAllNotifications(bundleOption); + 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; @@ -685,13 +781,13 @@ ErrCode AnsManagerStub::HandleDelete(MessageParcel &data, MessageParcel &reply) ErrCode AnsManagerStub::HandleDeleteByBundle(MessageParcel &data, MessageParcel &reply) { - std::string bundle; - if (!data.ReadString(bundle)) { + sptr bundleOption = data.ReadStrongParcelable(); + if (bundleOption == nullptr) { ANS_LOGW("[HandleDeleteByBundle] fail: read bundle failed."); return ERR_ANS_PARCELABLE_FAILED; } - ErrCode result = DeleteByBundle(bundle); + ErrCode result = DeleteByBundle(bundleOption); if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleDeleteByBundle] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -711,14 +807,14 @@ ErrCode AnsManagerStub::HandleDeleteAll(MessageParcel &data, MessageParcel &repl ErrCode AnsManagerStub::HandleGetSlotsByBundle(MessageParcel &data, MessageParcel &reply) { - std::string bundle; - if (!data.ReadString(bundle)) { - ANS_LOGW("[HandleGetSlotsByBundle] fail: read bundle failed."); + sptr bundleOption = data.ReadParcelable(); + if (bundleOption == nullptr) { + ANS_LOGW("[HandleGetSlotsByBundle] fail: read bundleOption failed."); return ERR_ANS_PARCELABLE_FAILED; } std::vector> slots; - ErrCode result = GetSlotsByBundle(bundle, slots); + ErrCode result = GetSlotsByBundle(bundleOption, slots); if (!WriteParcelableVector(slots, reply, result)) { ANS_LOGW("[HandleGetSlotsByBundle] fail: write slots failed."); return ERR_ANS_PARCELABLE_FAILED; @@ -728,9 +824,9 @@ ErrCode AnsManagerStub::HandleGetSlotsByBundle(MessageParcel &data, MessageParce ErrCode AnsManagerStub::HandleUpdateSlots(MessageParcel &data, MessageParcel &reply) { - std::string bundle; - if (!data.ReadString(bundle)) { - ANS_LOGW("[HandleUpdateSlots] fail: read bundle failed."); + sptr bundleOption = data.ReadParcelable(); + if (bundleOption == nullptr) { + ANS_LOGW("[HandleUpdateSlots] fail: read bundleOption failed."); return ERR_ANS_PARCELABLE_FAILED; } @@ -740,7 +836,7 @@ ErrCode AnsManagerStub::HandleUpdateSlots(MessageParcel &data, MessageParcel &re return ERR_ANS_PARCELABLE_FAILED; } - ErrCode result = UpdateSlots(bundle, slots); + ErrCode result = UpdateSlots(bundleOption, slots); if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleUpdateSlots] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -750,8 +846,8 @@ ErrCode AnsManagerStub::HandleUpdateSlots(MessageParcel &data, MessageParcel &re ErrCode AnsManagerStub::HandleUpdateSlotGroups(MessageParcel &data, MessageParcel &reply) { - std::string bundle; - if (!data.ReadString(bundle)) { + sptr bundleOption = data.ReadParcelable(); + if (bundleOption == nullptr) { ANS_LOGW("[HandleUpdateSlotGroups] fail: read bundle failed."); return ERR_ANS_PARCELABLE_FAILED; } @@ -762,7 +858,7 @@ ErrCode AnsManagerStub::HandleUpdateSlotGroups(MessageParcel &data, MessageParce return ERR_ANS_PARCELABLE_FAILED; } - ErrCode result = UpdateSlotGroups(bundle, groups); + ErrCode result = UpdateSlotGroups(bundleOption, groups); if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleUpdateSlotGroups] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -822,9 +918,9 @@ ErrCode AnsManagerStub::HandleSetNotificationsEnabledForSpecialBundle(MessagePar return ERR_ANS_PARCELABLE_FAILED; } - std::string bundle; - if (!data.ReadString(bundle)) { - ANS_LOGW("[HandleSetNotificationsEnabledForSpecialBundle] fail: read bundle failed."); + sptr bundleOption = data.ReadParcelable(); + if (bundleOption == nullptr) { + ANS_LOGW("[HandleSetNotificationsEnabledForSpecialBundle] fail: read bundleOption failed."); return ERR_ANS_PARCELABLE_FAILED; } @@ -834,7 +930,7 @@ ErrCode AnsManagerStub::HandleSetNotificationsEnabledForSpecialBundle(MessagePar return ERR_ANS_PARCELABLE_FAILED; } - ErrCode result = SetNotificationsEnabledForSpecialBundle(deviceId, bundle, enabled); + ErrCode result = SetNotificationsEnabledForSpecialBundle(deviceId, bundleOption, enabled); if (!reply.WriteInt32(result)) { ANS_LOGW( "[HandleSetNotificationsEnabledForSpecialBundle] fail: write result failed, ErrCode=%{public}d", result); @@ -845,8 +941,8 @@ ErrCode AnsManagerStub::HandleSetNotificationsEnabledForSpecialBundle(MessagePar ErrCode AnsManagerStub::HandleSetShowBadgeEnabledForBundle(MessageParcel &data, MessageParcel &reply) { - std::string bundle; - if (!data.ReadString(bundle)) { + sptr bundleOption = data.ReadParcelable(); + if (bundleOption == nullptr) { ANS_LOGW("[HandleSetShowBadgeEnabledForBundle] fail: read bundle failed."); return ERR_ANS_PARCELABLE_FAILED; } @@ -857,7 +953,7 @@ ErrCode AnsManagerStub::HandleSetShowBadgeEnabledForBundle(MessageParcel &data, return ERR_ANS_PARCELABLE_FAILED; } - ErrCode result = SetShowBadgeEnabledForBundle(bundle, enabled); + ErrCode result = SetShowBadgeEnabledForBundle(bundleOption, enabled); if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleSetShowBadgeEnabledForBundle] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -867,14 +963,14 @@ ErrCode AnsManagerStub::HandleSetShowBadgeEnabledForBundle(MessageParcel &data, ErrCode AnsManagerStub::HandleGetShowBadgeEnabledForBundle(MessageParcel &data, MessageParcel &reply) { - std::string bundle; - if (!data.ReadString(bundle)) { + sptr bundleOption = data.ReadParcelable(); + if (bundleOption == nullptr) { ANS_LOGW("[HandleGetShowBadgeEnabledForBundle] fail: read bundle failed."); return ERR_ANS_PARCELABLE_FAILED; } bool enabled = false; - ErrCode result = GetShowBadgeEnabledForBundle(bundle, enabled); + ErrCode result = GetShowBadgeEnabledForBundle(bundleOption, enabled); if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleGetShowBadgeEnabledForBundle] fail: write result failed, ErrCode=%{public}d", result); @@ -888,6 +984,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(); @@ -896,7 +1009,7 @@ ErrCode AnsManagerStub::HandleSubscribe(MessageParcel &data, MessageParcel &repl return ERR_ANS_PARCELABLE_FAILED; } - bool subcribeInfo; + bool subcribeInfo = false; if (!data.ReadBool(subcribeInfo)) { ANS_LOGW("[HandleSubscribe] fail: read isSubcribeInfo failed"); return ERR_ANS_PARCELABLE_FAILED; @@ -927,7 +1040,7 @@ ErrCode AnsManagerStub::HandleUnsubscribe(MessageParcel &data, MessageParcel &re return ERR_ANS_PARCELABLE_FAILED; } - bool subcribeInfo; + bool subcribeInfo = false; if (!data.ReadBool(subcribeInfo)) { ANS_LOGW("[HandleUnsubscribe] fail: read isSubcribeInfo failed"); return ERR_ANS_PARCELABLE_FAILED; @@ -1003,14 +1116,14 @@ ErrCode AnsManagerStub::HandleIsAllowedNotify(MessageParcel &data, MessageParcel ErrCode AnsManagerStub::HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply) { - std::string bundle; - if (!data.ReadString(bundle)) { + sptr bundleOption = data.ReadParcelable(); + if (bundleOption == nullptr) { ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: read bundle failed."); return ERR_ANS_PARCELABLE_FAILED; } bool allowed = false; - ErrCode result = IsSpecialBundleAllowedNotify(bundle, allowed); + ErrCode result = IsSpecialBundleAllowedNotify(bundleOption, allowed); if (!reply.WriteInt32(result)) { ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: write result failed, ErrCode=%{public}d", result); @@ -1095,281 +1208,314 @@ bool AnsManagerStub::ReadParcelableVector(std::vector> &parcelableInfos, ErrCode AnsManagerStub::Publish(const std::string &label, const sptr ¬ification) { ANS_LOGW("AnsManagerStub::Publish called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::PublishToDevice(const sptr ¬ification, const std::string &deviceId) { ANS_LOGW("AnsManagerStub::PublishToDevice called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::Cancel(int notificationId, const std::string &label) { ANS_LOGW("AnsManagerStub::Cancel called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::CancelAll() { ANS_LOGW("AnsManagerStub::CancelAll called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::AddSlotByType(NotificationConstant::SlotType slotType) +{ + ANS_LOGW("AnsManagerStub::AddSlotByType called!"); + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::AddSlots(const std::vector> &slots) { ANS_LOGW("AnsManagerStub::AddSlots called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } -ErrCode AnsManagerStub::RemoveSlotByType(const NotificationConstant::SlotType slotType) +ErrCode AnsManagerStub::RemoveSlotByType(NotificationConstant::SlotType slotType) { ANS_LOGW("AnsManagerStub::RemoveSlotByType called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::RemoveAllSlots() { ANS_LOGW("AnsManagerStub::RemoveAllSlots called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::AddSlotGroups(std::vector> groups) { ANS_LOGW("AnsManagerStub::AddSlotGroups called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } -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; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetSlots(std::vector> &slots) { ANS_LOGW("AnsManagerStub::GetSlots called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetSlotGroup(const std::string &groupId, sptr &group) { ANS_LOGW("AnsManagerStub::GetSlotGroup called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetSlotGroups(std::vector> &groups) { ANS_LOGW("AnsManagerStub::GetSlotGroups called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::GetSlotNumAsBundle(const sptr &bundleOption, int &num) +{ + ANS_LOGW("AnsManagerStub::GetSlotNumAsBundle called!"); + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::RemoveSlotGroups(const std::vector &groupIds) { ANS_LOGW("AnsManagerStub::RemoveSlotGroups called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetActiveNotifications(std::vector> ¬ifications) { ANS_LOGW("AnsManagerStub::GetActiveNotifications called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetActiveNotificationNums(int &num) { ANS_LOGW("AnsManagerStub::GetActiveNotificationNums called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetAllActiveNotifications(std::vector> ¬ifications) { ANS_LOGW("AnsManagerStub::GetAllActiveNotifications called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetSpecialActiveNotifications( const std::vector &key, std::vector> ¬ifications) { ANS_LOGW("AnsManagerStub::GetSpecialActiveNotifications called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::SetNotificationAgent(const std::string &agent) { ANS_LOGW("AnsManagerStub::SetNotificationAgent called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetNotificationAgent(std::string &agent) { ANS_LOGW("AnsManagerStub::GetNotificationAgent called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) { ANS_LOGW("AnsManagerStub::CanPublishAsBundle called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::PublishAsBundle( const sptr notification, const std::string &representativeBundle) { ANS_LOGW("AnsManagerStub::PublishAsBundle called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::SetNotificationBadgeNum(int num) { ANS_LOGW("AnsManagerStub::SetNotificationBadgeNum called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetBundleImportance(int &importance) { ANS_LOGW("AnsManagerStub::GetBundleImportance called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::SetDisturbMode(NotificationConstant::DisturbMode mode) { ANS_LOGW("AnsManagerStub::SetDisturbMode called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetDisturbMode(NotificationConstant::DisturbMode &mode) { ANS_LOGW("AnsManagerStub::GetDisturbMode called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::HasNotificationPolicyAccessPermission(bool &granted) { ANS_LOGW("AnsManagerStub::HasNotificationPolicyAccessPermission called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::SetPrivateNotificationsAllowed(bool allow) { ANS_LOGW("AnsManagerStub::SetPrivateNotificationsAllowed called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetPrivateNotificationsAllowed(bool &allow) { ANS_LOGW("AnsManagerStub::GetPrivateNotificationsAllowed called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::RemoveNotification( + const sptr &bundleOption, int notificationId, const std::string &label) +{ + ANS_LOGW("AnsManagerStub::RemoveNotification called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::RemoveAllNotifications(const sptr &bundleOption) +{ + ANS_LOGW("AnsManagerStub::RemoveAllNotifications called!"); + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::Delete(const std::string &key) { ANS_LOGW("AnsManagerStub::Delete called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } -ErrCode AnsManagerStub::DeleteByBundle(const std::string &bundle) +ErrCode AnsManagerStub::DeleteByBundle(const sptr &bundleOption) { ANS_LOGW("AnsManagerStub::DeleteByBundle called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::DeleteAll() { ANS_LOGW("AnsManagerStub::DeleteAll called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } -ErrCode AnsManagerStub::GetSlotsByBundle(const std::string &bundle, std::vector> &slots) +ErrCode AnsManagerStub::GetSlotsByBundle( + const sptr &bundleOption, std::vector> &slots) { ANS_LOGW("AnsManagerStub::GetSlotsByBundle called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } -ErrCode AnsManagerStub::UpdateSlots(const std::string &bundle, const std::vector> &slots) +ErrCode AnsManagerStub::UpdateSlots( + const sptr &bundleOption, const std::vector> &slots) { ANS_LOGW("AnsManagerStub::UpdateSlots called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::UpdateSlotGroups( - const std::string &bundle, const std::vector> &groups) + const sptr &bundleOption, const std::vector> &groups) { ANS_LOGW("AnsManagerStub::UpdateSlotGroups called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::SetNotificationsEnabledForBundle(const std::string &bundle, bool enabled) { ANS_LOGW("AnsManagerStub::SetNotificationsEnabledForBundle called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) { ANS_LOGW("AnsManagerStub::SetNotificationsEnabledForAllBundles called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::SetNotificationsEnabledForSpecialBundle( - const std::string &deviceId, const std::string &bundleName, bool enabled) + const std::string &deviceId, const sptr &bundleOption, bool enabled) { ANS_LOGW("AnsManagerStub::SetNotificationsEnabledForSpecialBundle called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } -ErrCode AnsManagerStub::SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) +ErrCode AnsManagerStub::SetShowBadgeEnabledForBundle(const sptr &bundleOption, bool enabled) { ANS_LOGW("AnsManagerStub::SetShowBadgeEnabledForBundle called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } -ErrCode AnsManagerStub::GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) +ErrCode AnsManagerStub::GetShowBadgeEnabledForBundle(const sptr &bundleOption, bool &enabled) { ANS_LOGW("AnsManagerStub::GetShowBadgeEnabledForBundle called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::GetShowBadgeEnabled(bool &enabled) +{ + ANS_LOGW("AnsManagerStub::GetShowBadgeEnabled called!"); + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::Subscribe(const sptr &subscriber, const sptr &info) { ANS_LOGW("AnsManagerStub::Subscribe called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::Unsubscribe(const sptr &subscriber, const sptr &info) { ANS_LOGW("AnsManagerStub::Unsubscribe called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::AreNotificationsSuspended(bool &suspended) { ANS_LOGW("AnsManagerStub::AreNotificationsSuspended called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::GetCurrentAppSorting(sptr &sortingMap) { ANS_LOGW("AnsManagerStub::GetCurrentAppSorting called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::IsAllowedNotify(bool &allowed) { ANS_LOGW("AnsManagerStub::IsAllowedNotify called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } -ErrCode AnsManagerStub::IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) +ErrCode AnsManagerStub::IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) { ANS_LOGW("AnsManagerStub::IsSpecialBundleAllowedNotify called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AnsManagerStub::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) { ANS_LOGW("AnsManagerStub::ShellDump called!"); - return ERR_OK; + return ERR_INVALID_OPERATION; } } // namespace Notification diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index 57abd571899ee7cf765af6e38320a625e0f01304..5bf4a26c39ca4479362a2a138fe56aaa75bf845d 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) { @@ -43,7 +52,7 @@ ErrCode AnsNotification::AddNotificationSlots(const std::vector> slotsSptr; for (auto it = slots.begin(); it != slots.end(); ++it) { - sptr slot = new NotificationSlot(*it); + sptr slot = new (std::nothrow) NotificationSlot(*it); if (slot == nullptr) { ANS_LOGE("Failed to create NotificationSlot ptr."); return ERR_ANS_NO_MEMORY; @@ -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) { @@ -98,7 +116,7 @@ ErrCode AnsNotification::AddNotificationSlotGroups(const std::vector> slotGroupsSptr; for (auto it = slotGroups.begin(); it != slotGroups.end(); ++it) { - sptr slotGroup = new NotificationSlotGroup((*it).GetId(), (*it).GetName()); + sptr slotGroup = new (std::nothrow) NotificationSlotGroup(*it); if (slotGroup == nullptr) { ANS_LOGE("Failed to add notification slot groups with NotificationSlotGroup nullptr"); return ERR_ANS_NO_MEMORY; @@ -138,6 +156,17 @@ ErrCode AnsNotification::GetNotificationSlotGroups(std::vectorGetSlotGroups(groups); } +ErrCode AnsNotification::GetNotificationSlotNumAsBundle(const NotificationBundleOption &bundleOption, int &num) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->GetSlotNumAsBundle(bo, num); +} + ErrCode AnsNotification::PublishNotification(const NotificationRequest &request) { ANS_LOGI("enter"); @@ -462,13 +491,38 @@ ErrCode AnsNotification::RemoveNotification(const std::string &key) return ansManagerProxy_->Delete(key); } -ErrCode AnsNotification::RemoveNotifications(const std::string &bundleName) +ErrCode AnsNotification::RemoveNotification( + const NotificationBundleOption &bundleOption, const int32_t notificationId, const std::string &label) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->RemoveNotification(bo, notificationId, label); +} + +ErrCode AnsNotification::RemoveAllNotifications(const NotificationBundleOption &bundleOption) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->RemoveAllNotifications(bo); +} + +ErrCode AnsNotification::RemoveNotificationsByBundle(const NotificationBundleOption &bundleOption) { if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - return ansManagerProxy_->DeleteByBundle(bundleName); + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->DeleteByBundle(bo); } ErrCode AnsNotification::RemoveNotifications() @@ -481,9 +535,9 @@ ErrCode AnsNotification::RemoveNotifications() } ErrCode AnsNotification::GetNotificationSlotsForBundle( - const std::string &bundleName, std::vector> &slots) + const NotificationBundleOption &bundleOption, std::vector> &slots) { - if (bundleName.empty()) { + if (bundleOption.GetBundleName().empty()) { ANS_LOGE("Input bundleName is empty."); return ERR_ANS_INVALID_PARAM; } @@ -492,7 +546,33 @@ ErrCode AnsNotification::GetNotificationSlotsForBundle( ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - return ansManagerProxy_->GetSlotsByBundle(bundleName, slots); + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->GetSlotsByBundle(bo, slots); +} + +ErrCode AnsNotification::UpdateNotificationSlots( + const NotificationBundleOption &bundleOption, const std::vector> &slots) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->UpdateSlots(bo, slots); +} + +ErrCode AnsNotification::UpdateNotificationSlotGroups( + const NotificationBundleOption &bundleOption, const std::vector> &groups) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->UpdateSlotGroups(bo, groups); } ErrCode AnsNotification::GetAllActiveNotifications(std::vector> ¬ification) @@ -514,9 +594,9 @@ ErrCode AnsNotification::GetAllActiveNotifications( return ansManagerProxy_->GetSpecialActiveNotifications(key, notification); } -ErrCode AnsNotification::IsAllowedNotify(const std::string &bundle, bool &allowed) +ErrCode AnsNotification::IsAllowedNotify(const NotificationBundleOption &bundleOption, bool &allowed) { - if (bundle.empty()) { + if (bundleOption.GetBundleName().empty()) { ANS_LOGE("Input bundle is empty."); return ERR_ANS_INVALID_PARAM; } @@ -525,7 +605,9 @@ ErrCode AnsNotification::IsAllowedNotify(const std::string &bundle, bool &allowe ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - return ansManagerProxy_->IsSpecialBundleAllowedNotify(bundle, allowed); + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->IsSpecialBundleAllowedNotify(bo, allowed); } ErrCode AnsNotification::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) @@ -547,13 +629,47 @@ ErrCode AnsNotification::SetNotificationsEnabledForDefaultBundle(const std::stri } ErrCode AnsNotification::SetNotificationsEnabledForSpecifiedBundle( - const std::string &bundle, const std::string &deviceId, bool enabled) + const NotificationBundleOption &bundleOption, const std::string &deviceId, bool enabled) { if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - return ansManagerProxy_->SetNotificationsEnabledForSpecialBundle(deviceId, bundle, enabled); + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->SetNotificationsEnabledForSpecialBundle(deviceId, bo, enabled); +} + +ErrCode AnsNotification::SetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->SetShowBadgeEnabledForBundle(bo, enabled); +} + +ErrCode AnsNotification::GetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool &enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr bo(new NotificationBundleOption(bundleOption)); + return ansManagerProxy_->GetShowBadgeEnabledForBundle(bo, enabled); +} + +ErrCode AnsNotification::GetShowBadgeEnabled(bool &enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->GetShowBadgeEnabled(enabled); } ErrCode AnsNotification::SetDisturbMode(NotificationConstant::DisturbMode mode) diff --git a/frameworks/ans/core/src/ans_subscriber_stub.cpp b/frameworks/ans/core/src/ans_subscriber_stub.cpp index 31850df90bdc5473a9b9946c0e6a4fd533bfce4d..8ecb5721982416f3ddfd6cf698aeb97b4528c003 100644 --- a/frameworks/ans/core/src/ans_subscriber_stub.cpp +++ b/frameworks/ans/core/src/ans_subscriber_stub.cpp @@ -111,7 +111,7 @@ ErrCode AnsSubscriberStub::HandleOnConsumedMap(MessageParcel &data, MessageParce return ERR_ANS_PARCELABLE_FAILED; } - bool existMap; + bool existMap = false; if (!data.ReadBool(existMap)) { ANS_LOGW("[HandleOnConsumedMap] fail: read existMap failed"); return ERR_ANS_PARCELABLE_FAILED; @@ -150,7 +150,7 @@ ErrCode AnsSubscriberStub::HandleOnCanceledMap(MessageParcel &data, MessageParce return ERR_ANS_PARCELABLE_FAILED; } - bool existMap; + bool existMap = false; if (!data.ReadBool(existMap)) { ANS_LOGW("[HandleOnCanceledMap] fail: read existMap failed"); return ERR_ANS_PARCELABLE_FAILED; diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn old mode 100644 new mode 100755 index cc0cb3825ef69dc45d6ac51c841823355adfd0b2..e8c5dae3354643ff8289bbf258b2d5f4daaf9271 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -34,6 +34,7 @@ ohos_shared_library("ans_innerkits") { "${interfaces_path}/ans/native/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", "//utils/system/safwk/native/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -41,6 +42,7 @@ ohos_shared_library("ans_innerkits") { "src/notification.cpp", "src/notification_action_button.cpp", "src/notification_basic_content.cpp", + "src/notification_bundle_option.cpp", "src/notification_constant.cpp", "src/notification_content.cpp", "src/notification_conversational_content.cpp", @@ -73,6 +75,7 @@ ohos_shared_library("ans_innerkits") { "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/frameworks/ans/native/src/message_user.cpp b/frameworks/ans/native/src/message_user.cpp index d91769912626e673209de4cf48f7b1b85f8abafd..161d723871ddd8f38d0ddfbbc6621e41502ebc79 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 31b3763654c7228e01fd12dfbf8d5614eb4130da..c69e0864ccb221fb4cecb966032cc3da124ded72 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"){} + * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -31,6 +31,9 @@ Notification::Notification(const sptr &request) Notification::Notification(const Notification &other) { + enableSound_ = other.enableSound_; + enableLight_ = other.enableLight_; + enableViration_ = other.enableViration_; key_ = other.key_; ledLightColor_ = other.ledLightColor_; lockscreenVisibleness_ = other.lockscreenVisibleness_; @@ -40,28 +43,22 @@ Notification::Notification(const Notification &other) vibrationStyle_ = other.vibrationStyle_; } +Notification::~Notification() +{} + 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 +134,7 @@ Uri Notification::GetSound() const return Uri(""); } -uid_t Notification::GetUid() const +pid_t Notification::GetUid() const { if (request_ == nullptr) { return 0; @@ -145,7 +142,7 @@ uid_t Notification::GetUid() const return request_->GetCreatorUid(); } -uid_t Notification::GetPid() const +pid_t Notification::GetPid() const { if (request_ == nullptr) { return 0; @@ -176,17 +173,17 @@ bool Notification::IsFloatingIcon() const bool Notification::Marshalling(Parcel &parcel) const { - if(!parcel.WriteBool(enableLight_)){ + if (!parcel.WriteBool(enableLight_)) { ANS_LOGE("Can't write enableLight_"); return false; } - if(!parcel.WriteBool(enableSound_)) { + if (!parcel.WriteBool(enableSound_)) { ANS_LOGE("Can't write enableSound_"); return false; } - if(!parcel.WriteBool(enableViration_)) { + if (!parcel.WriteBool(enableViration_)) { ANS_LOGE("Can't write enableViration_"); return false; } @@ -219,7 +216,7 @@ bool Notification::Marshalling(Parcel &parcel) const if (!parcel.WriteString(sound_->ToString())) { ANS_LOGE("Can't write sound"); return false; - } + } } if (!parcel.WriteInt64Vector(vibrationStyle_)) { @@ -257,7 +254,7 @@ bool Notification::ReadFromParcel(Parcel &parcel) postTime_ = parcel.ReadInt64(); // Read sound_ - if (enableSound_) { + if (enableSound_) { sound_ = std::make_shared(parcel.ReadString()); } @@ -278,17 +275,17 @@ Notification *Notification::Unmarshalling(Parcel &parcel) return n; } -void Notification::SetEnableSound(const bool& enable) +void Notification::SetEnableSound(const bool &enable) { enableSound_ = enable; } -void Notification::SetEnableLight(const bool& enable) +void Notification::SetEnableLight(const bool &enable) { enableLight_ = enable; } -void Notification::SetEnableViration(const bool& enable) +void Notification::SetEnableViration(const bool &enable) { enableViration_ = enable; } @@ -331,7 +328,8 @@ std::string Notification::GenerateNotificationKey(int32_t uid, const std::string std::string Notification::Dump() const { std::string dump = "Notification{ key = " + key_ + ", ledLightColor = " + std::to_string(ledLightColor_) + - ", lockscreenVisbleness = " + std::to_string(static_cast(lockscreenVisibleness_)) + ",request = "; + ", lockscreenVisbleness = " + std::to_string(static_cast(lockscreenVisibleness_)) + + ",request = "; if (request_ == nullptr) { dump += "nullptr"; } else { diff --git a/frameworks/ans/native/src/notification_action_button.cpp b/frameworks/ans/native/src/notification_action_button.cpp index 80f7e40c994ba52744dc5b7489437385fd39af2b..62cf80e18d3442cac9b10053f06aaca0ac2ad1ee 100644 --- a/frameworks/ans/native/src/notification_action_button.cpp +++ b/frameworks/ans/native/src/notification_action_button.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * @@ -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_basic_content.cpp b/frameworks/ans/native/src/notification_basic_content.cpp index 718ecd0f39e0319f8bf34e74a2634bbb148b7c69..4942104e27005aed6c96a26185e47e50a81796ac 100644 --- a/frameworks/ans/native/src/notification_basic_content.cpp +++ b/frameworks/ans/native/src/notification_basic_content.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * 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 0000000000000000000000000000000000000000..acdfc939c52ab417da2cb34933ab6d92073e72e3 --- /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_constant.cpp b/frameworks/ans/native/src/notification_constant.cpp index 7fff8410e6e222a7c28b835469a36d226a44d101..744dc11f61a87dbcb02f6a481c664448e55bdf99 100644 --- a/frameworks/ans/native/src/notification_constant.cpp +++ b/frameworks/ans/native/src/notification_constant.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/ans/native/src/notification_content.cpp b/frameworks/ans/native/src/notification_content.cpp index 26106dea4a9542b5c811cbc1aafd4e4d84cdd7a4..1accb1daafbfaf6c272bebb5f8d45039291df2f0 100644 --- a/frameworks/ans/native/src/notification_content.cpp +++ b/frameworks/ans/native/src/notification_content.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/ans/native/src/notification_conversational_content.cpp b/frameworks/ans/native/src/notification_conversational_content.cpp index 51ce80bf6407a3ec95d774893676441fb72a86e0..2b1925d8432d563c48ef9a46e73001751b7a4051 100644 --- a/frameworks/ans/native/src/notification_conversational_content.cpp +++ b/frameworks/ans/native/src/notification_conversational_content.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/ans/native/src/notification_conversational_message.cpp b/frameworks/ans/native/src/notification_conversational_message.cpp index e2f3b9e3ae0705699948dff287685d92c91208b0..9274ef8aa3fa392e3c6700da980a0621328d65e0 100644 --- a/frameworks/ans/native/src/notification_conversational_message.cpp +++ b/frameworks/ans/native/src/notification_conversational_message.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/ans/native/src/notification_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp index 2570e4d09b1335da677fdff37f58f209d90cf41d..86ea093d9aa8230df5744fd492f6bd0099e5b391 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) { @@ -70,6 +80,11 @@ ErrCode NotificationHelper::GetNotificationSlotGroups(std::vector::GetInstance()->GetNotificationSlotGroups(groups); } +ErrCode NotificationHelper::GetNotificationSlotNumAsBundle(const NotificationBundleOption &bundleOption, int &num) +{ + return DelayedSingleton::GetInstance()->GetNotificationSlotNumAsBundle(bundleOption, num); +} + ErrCode NotificationHelper::PublishNotification(const NotificationRequest &request) { return DelayedSingleton::GetInstance()->PublishNotification(request); @@ -194,9 +209,20 @@ ErrCode NotificationHelper::RemoveNotification(const std::string &key) return DelayedSingleton::GetInstance()->RemoveNotification(key); } -ErrCode NotificationHelper::RemoveNotifications(const std::string &bundleName) +ErrCode NotificationHelper::RemoveNotification( + const NotificationBundleOption &bundleOption, const int32_t notificationId, const std::string &label) +{ + return DelayedSingleton::GetInstance()->RemoveNotification(bundleOption, notificationId, label); +} + +ErrCode NotificationHelper::RemoveAllNotifications(const NotificationBundleOption &bundleOption) +{ + return DelayedSingleton::GetInstance()->RemoveAllNotifications(bundleOption); +} + +ErrCode NotificationHelper::RemoveNotificationsByBundle(const NotificationBundleOption &bundleOption) { - return DelayedSingleton::GetInstance()->RemoveNotifications(bundleName); + return DelayedSingleton::GetInstance()->RemoveNotificationsByBundle(bundleOption); } ErrCode NotificationHelper::RemoveNotifications() @@ -205,9 +231,21 @@ ErrCode NotificationHelper::RemoveNotifications() } ErrCode NotificationHelper::GetNotificationSlotsForBundle( - const std::string &bundleName, std::vector> &slots) + const NotificationBundleOption &bundleOption, std::vector> &slots) { - return DelayedSingleton::GetInstance()->GetNotificationSlotsForBundle(bundleName, slots); + return DelayedSingleton::GetInstance()->GetNotificationSlotsForBundle(bundleOption, slots); +} + +ErrCode NotificationHelper::UpdateNotificationSlots( + const NotificationBundleOption &bundleOption, const std::vector> &slots) +{ + return DelayedSingleton::GetInstance()->UpdateNotificationSlots(bundleOption, slots); +} + +ErrCode NotificationHelper::UpdateNotificationSlotGroups( + const NotificationBundleOption &bundleOption, const std::vector> &groups) +{ + return DelayedSingleton::GetInstance()->UpdateNotificationSlotGroups(bundleOption, groups); } ErrCode NotificationHelper::GetAllActiveNotifications(std::vector> ¬ification) @@ -221,9 +259,9 @@ ErrCode NotificationHelper::GetAllActiveNotifications( return DelayedSingleton::GetInstance()->GetAllActiveNotifications(key, notification); } -ErrCode NotificationHelper::IsAllowedNotify(const std::string &bundle, bool &allowed) +ErrCode NotificationHelper::IsAllowedNotify(const NotificationBundleOption &bundleOption, bool &allowed) { - return DelayedSingleton::GetInstance()->IsAllowedNotify(bundle, allowed); + return DelayedSingleton::GetInstance()->IsAllowedNotify(bundleOption, allowed); } ErrCode NotificationHelper::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) @@ -237,10 +275,25 @@ ErrCode NotificationHelper::SetNotificationsEnabledForDefaultBundle(const std::s } ErrCode NotificationHelper::SetNotificationsEnabledForSpecifiedBundle( - const std::string &bundle, std::string &deviceId, bool enabled) + const NotificationBundleOption &bundleOption, std::string &deviceId, bool enabled) { return DelayedSingleton::GetInstance()->SetNotificationsEnabledForSpecifiedBundle( - bundle, deviceId, enabled); + bundleOption, deviceId, enabled); +} + +ErrCode NotificationHelper::SetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool enabled) +{ + return DelayedSingleton::GetInstance()->SetShowBadgeEnabledForBundle(bundleOption, enabled); +} + +ErrCode NotificationHelper::GetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool &enabled) +{ + return DelayedSingleton::GetInstance()->GetShowBadgeEnabledForBundle(bundleOption, enabled); +} + +ErrCode NotificationHelper::GetShowBadgeEnabled(bool &enabled) +{ + return DelayedSingleton::GetInstance()->GetShowBadgeEnabled(enabled); } ErrCode NotificationHelper::SetDisturbMode(NotificationConstant::DisturbMode mode) diff --git a/frameworks/ans/native/src/notification_long_text_content.cpp b/frameworks/ans/native/src/notification_long_text_content.cpp index e7dc470b24a9d48ea86b9da94d49279fdf0a6b41..f17afa07b8ac74e9d010ee6fca666b60ed651d24 100644 --- a/frameworks/ans/native/src/notification_long_text_content.cpp +++ b/frameworks/ans/native/src/notification_long_text_content.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/ans/native/src/notification_media_content.cpp b/frameworks/ans/native/src/notification_media_content.cpp index daf3ace8b4f65eb09ae4fac851d1b73537607ef1..f6d3e65b3290b46ccbb925cf94dce901b1832517 100644 --- a/frameworks/ans/native/src/notification_media_content.cpp +++ b/frameworks/ans/native/src/notification_media_content.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/ans/native/src/notification_multiline_content.cpp b/frameworks/ans/native/src/notification_multiline_content.cpp index 495c2571544d77dbabd587600502ddefffbef91b..4d0df649db1c693bfd780287d79d1ef067b85d24 100644 --- a/frameworks/ans/native/src/notification_multiline_content.cpp +++ b/frameworks/ans/native/src/notification_multiline_content.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/ans/native/src/notification_normal_content.cpp b/frameworks/ans/native/src/notification_normal_content.cpp index dec172656caebe5792ce98c0aa80956e69e6d44c..e9e253789e260af7f117c2cda145b396160ef0a2 100644 --- a/frameworks/ans/native/src/notification_normal_content.cpp +++ b/frameworks/ans/native/src/notification_normal_content.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/ans/native/src/notification_picture_content.cpp b/frameworks/ans/native/src/notification_picture_content.cpp index d155eb4a657e99eb6e71fea97352284cc623788d..385e3c467ecb0268dcaab06a9903406db2937a1d 100644 --- a/frameworks/ans/native/src/notification_picture_content.cpp +++ b/frameworks/ans/native/src/notification_picture_content.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index 1b850292c405959fd20e2432c71f2ea5f9a4c863..809de5494c5077d8db051ea0d4dce56cdd165065 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * @@ -37,9 +37,9 @@ const std::string NotificationRequest::CLASSIFICATION_STATUS{"status"}; const std::string NotificationRequest::CLASSIFICATION_SYSTEM{"sys"}; const std::string NotificationRequest::CLASSIFICATION_TRANSPORT{"transport"}; -const int32_t NotificationRequest::COLOR_DEFAULT{0}; +const uint32_t NotificationRequest::COLOR_DEFAULT{0}; -const int32_t NotificationRequest::COLOR_MASK{0xFF000000}; +const uint32_t NotificationRequest::COLOR_MASK{0xFF000000}; const std::size_t NotificationRequest::MAX_USER_INPUT_HISTORY{5}; const std::size_t NotificationRequest::MAX_ACTION_BUTTONS{3}; @@ -108,9 +108,6 @@ NotificationRequest::NotificationRequest(const NotificationRequest &other) this->littleIcon_ = other.littleIcon_; this->bigIcon_ = other.bigIcon_; this->notificationContent_ = other.notificationContent_; - this->customBigView_ = other.customBigView_; - this->customFloatView_ = other.customFloatView_; - this->customView_ = other.customView_; this->publicNotification_ = other.publicNotification_; this->actionButtons_ = other.actionButtons_; @@ -170,9 +167,6 @@ NotificationRequest &NotificationRequest::operator=(const NotificationRequest &o this->littleIcon_ = other.littleIcon_; this->bigIcon_ = other.bigIcon_; this->notificationContent_ = other.notificationContent_; - this->customBigView_ = other.customBigView_; - this->customFloatView_ = other.customFloatView_; - this->customView_ = other.customView_; this->publicNotification_ = other.publicNotification_; this->actionButtons_ = other.actionButtons_; @@ -380,15 +374,15 @@ std::string NotificationRequest::GetClassification() const return classification_; } -void NotificationRequest::SetColor(int32_t color) +void NotificationRequest::SetColor(uint32_t color) { color_ = color; - if (NotificationRequest::COLOR_DEFAULT != color) { - color_ = color | NotificationRequest::COLOR_MASK; + if (NotificationRequest::COLOR_DEFAULT != color_) { + color_ = color_ | NotificationRequest::COLOR_MASK; } } -int32_t NotificationRequest::GetColor() const +uint32_t NotificationRequest::GetColor() const { return color_; } @@ -458,36 +452,6 @@ void NotificationRequest::SetCountdownTimer(bool isCountDown) isCountdown_ = isCountDown; } -void NotificationRequest::SetCustomBigView(const std::shared_ptr &view) -{ - customBigView_ = view; -} - -const std::shared_ptr NotificationRequest::GetCustomBigView() const -{ - return customBigView_; -} - -void NotificationRequest::SetCustomFloatView(const std::shared_ptr &view) -{ - customFloatView_ = view; -} - -const std::shared_ptr NotificationRequest::GetCustomFloatView() const -{ - return customFloatView_; -} - -void NotificationRequest::SetCustomView(const std::shared_ptr &view) -{ - customView_ = view; -} - -const std::shared_ptr NotificationRequest::GetCustomView() const -{ - return customView_; -} - void NotificationRequest::SetGroupAlertType(NotificationRequest::GroupAlertType type) { groupAlertType_ = type; @@ -727,12 +691,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_; } @@ -785,9 +749,6 @@ std::string NotificationRequest::Dump() ", littleIcon = " + (littleIcon_ ? "not null" : "null") + ", bigIcon = " + (bigIcon_ ? "not null" : "null") + ", notificationContent = " + (notificationContent_ ? "not null" : "null") + - ", customBigView = " + (customBigView_ ? "not null" : "null") + - ", customFloatView = " + (customFloatView_ ? "not null" : "null") + - ", customView = " + (customView_ ? "not null" : "null") + ", publicNotification = " + (publicNotification_ ? "not null" : "null") + ", actionButtons = " + (!actionButtons_.empty() ? "not empty" : "empty") + ", messageUsers = " + (!messageUsers_.empty() ? "not empty" : "empty") + @@ -802,7 +763,7 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const return false; } - if (!parcel.WriteInt32(color_)) { + if (!parcel.WriteUint32(color_)) { ANS_LOGE("Failed to write color"); return false; } @@ -1080,45 +1041,6 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const } } - // valid = customBigView_ ? true : false; - // if (!parcel.WriteBool(valid)) { - // ANS_LOGE("Failed to write the flag which indicate whether customBigView is null"); - // return false; - // } - - // if (valid) { - // if (!parcel.WriteParcelable(customBigView_.get())) { - // ANS_LOGE("Failed to write customBigView"); - // return false; - // } - // } - - // valid = customFloatView_ ? true : false; - // if (!parcel.WriteBool(valid)) { - // ANS_LOGE("Failed to write the flag which indicate whether customFloatView is null"); - // return false; - // } - - // if (valid) { - // if (!parcel.WriteParcelable(customFloatView_.get())) { - // ANS_LOGE("Failed to write customFloatView"); - // return false; - // } - // } - - // valid = customView_ ? true : false; - // if (!parcel.WriteBool(valid)) { - // ANS_LOGE("Failed to write the flag which indicate whether customView is null"); - // return false; - // } - - // if (valid) { - // if (!parcel.WriteParcelable(customView_.get())) { - // ANS_LOGE("Failed to write customView"); - // return false; - // } - // } - valid = publicNotification_ ? true : false; if (!parcel.WriteBool(valid)) { ANS_LOGE("Failed to write the flag which indicate whether publicNotification is null"); @@ -1179,7 +1101,7 @@ NotificationRequest *NotificationRequest::Unmarshalling(Parcel &parcel) bool NotificationRequest::ReadFromParcel(Parcel &parcel) { notificationId_ = parcel.ReadInt32(); - color_ = parcel.ReadInt32(); + color_ = parcel.ReadUint32(); badgeNumber_ = parcel.ReadInt32(); progressValue_ = parcel.ReadInt32(); progressMax_ = parcel.ReadInt32(); @@ -1188,7 +1110,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"); @@ -1320,33 +1242,6 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) } } - // valid = parcel.ReadBool(); - // if (valid) { - // customBigView_ = std::shared_ptr(parcel.ReadParcelable()); - // if (!customBigView_) { - // ANS_LOGE("Failed to read customBigView"); - // return false; - // } - // } - - // valid = parcel.ReadBool(); - // if (valid) { - // customFloatView_ = std::shared_ptr(parcel.ReadParcelable()); - // if (!customFloatView_) { - // ANS_LOGE("Failed to read customFloatView"); - // return false; - // } - // } - - // valid = parcel.ReadBool(); - // if (valid) { - // customView_ = std::shared_ptr(parcel.ReadParcelable()); - // if (!customView_) { - // ANS_LOGE("Failed to read customView"); - // return false; - // } - // } - valid = parcel.ReadBool(); if (valid) { publicNotification_ = std::shared_ptr(parcel.ReadParcelable()); diff --git a/frameworks/ans/native/src/notification_slot.cpp b/frameworks/ans/native/src/notification_slot.cpp index 05223bd1c1a6d076013a29063db7bc1a9a9d232f..cf83dbca40d8a9a96c1f22b191184877f34bdf3b 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 6de656121b37f8f3a3c68633e1a705f34c0d06ec..8146d343529cfee726e729c7e162e97fd338755c 100644 --- a/frameworks/ans/native/src/notification_slot_group.cpp +++ b/frameworks/ans/native/src/notification_slot_group.cpp @@ -49,6 +49,11 @@ std::string NotificationSlotGroup::GetName() const return name_; } +void NotificationSlotGroup::SetSlots(const std::vector &slots) +{ + slots_ = slots; +} + std::vector NotificationSlotGroup::GetSlots() const { return slots_; @@ -77,7 +82,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 @@ -121,22 +126,17 @@ bool NotificationSlotGroup::ReadFromParcel(Parcel &parcel) id_ = parcel.ReadString(); name_ = parcel.ReadString(); description_ = parcel.ReadString(); - - if (slots_.size() == 0) { - if (!parcel.ReadInt32()) { - return false; - } - } else { - if (!parcel.ReadInt32()) { - return false; - } - for (auto it = slots_.begin(); it != slots_.end(); ++it) { - slots_.emplace_back(*it->Unmarshalling(parcel)); + int32_t size = parcel.ReadInt32(); + if (size) { + for (int32_t i = 0; i < size; ++i) { + auto slot = parcel.ReadParcelable(); + if (nullptr == slot) { + return false; + } + slots_.emplace_back(*slot); } } - isDisabled_ = parcel.ReadBool(); - return true; } @@ -144,7 +144,7 @@ NotificationSlotGroup *NotificationSlotGroup::Unmarshalling(Parcel &parcel) { NotificationSlotGroup *notificationSlotGroup = new NotificationSlotGroup(); - if (!notificationSlotGroup && !notificationSlotGroup->ReadFromParcel(parcel)) { + if (notificationSlotGroup && !notificationSlotGroup->ReadFromParcel(parcel)) { delete notificationSlotGroup; notificationSlotGroup = nullptr; } diff --git a/frameworks/ans/native/src/notification_sorting.cpp b/frameworks/ans/native/src/notification_sorting.cpp index 22fbba79b3db18f20cecb59e7e6937c349990c93..6315d338d4bdff27b44464daa88b386415a13b79 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_sorting_map.cpp b/frameworks/ans/native/src/notification_sorting_map.cpp index 6fa30aae2b3630e5f56321ab59e6be1b29889010..8e32c8bfe406d54ab29d6fdebf38f98b5d8a6888 100644 --- a/frameworks/ans/native/src/notification_sorting_map.cpp +++ b/frameworks/ans/native/src/notification_sorting_map.cpp @@ -82,13 +82,15 @@ NotificationSortingMap *NotificationSortingMap::Unmarshalling(Parcel &parcel) { std::vector sortings; // read sorting num - int32_t size; + int32_t size = 0; parcel.ReadInt32(size); for (int i = 0; i < size; i++) { // read sorting - NotificationSorting a = *parcel.ReadParcelable(); - sortings.push_back(a); + NotificationSorting *sorting = parcel.ReadParcelable(); + if (sorting != nullptr) { + sortings.push_back(*sorting); + } } NotificationSortingMap *sortingMap = new NotificationSortingMap(sortings); diff --git a/frameworks/ans/native/src/notification_subscriber.cpp b/frameworks/ans/native/src/notification_subscriber.cpp index cc16b284521736098262fb48b0e03d3bd42f8bb5..4220ea0ec500180a2ec75ba27dd12ed3f56cccc9 100644 --- a/frameworks/ans/native/src/notification_subscriber.cpp +++ b/frameworks/ans/native/src/notification_subscriber.cpp @@ -21,6 +21,14 @@ namespace OHOS { namespace Notification { +NotificationSubscriber::NotificationSubscriber() +{ + impl_ = new SubscriberImpl(*this); +}; + +NotificationSubscriber::~NotificationSubscriber() +{} + const sptr NotificationSubscriber::GetImpl() const { return impl_; diff --git a/frameworks/ans/native/src/notification_user_input.cpp b/frameworks/ans/native/src/notification_user_input.cpp index 5c6e96027e7bdc33adb981f8e84955d4a9b32362..e14dd2f75e9062072b6b8a30926a80a6bc4f2641 100644 --- a/frameworks/ans/native/src/notification_user_input.cpp +++ b/frameworks/ans/native/src/notification_user_input.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * @@ -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 old mode 100644 new mode 100755 index cc524695c7ce06474579878813859366ca909472..db73e3179276ada1f1889ec346d66a57da579c88 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -65,7 +65,11 @@ ohos_moduletest("ans_fw_module_test") { "${interfaces_path}/innerkits/ans/native/include", "${interfaces_path}/innerkits/wantAgent/include", "//utils/native/base/include", + "//third_party/jsoncpp/include", "//base/notification/ans_standard/frameworks/ans/test/moduletest/mock/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include/", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils/", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log/", ] sources = [ @@ -76,11 +80,12 @@ ohos_moduletest("ans_fw_module_test") { "//base/notification/ans_standard/frameworks/ans/core/src/ans_subscriber_stub.cpp", "//base/notification/ans_standard/frameworks/ans/native/src/notification.cpp", "ans_fw_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_event_handler.cpp", "mock/mock_ipc.cpp", - "mock/mock_ipc_object_proxy.cpp", + "mock/mock_single_kv_store.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -94,8 +99,242 @@ 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/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//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" +} + +ohos_moduletest("ans_innerkits_module_publish_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 = [ + "ans_innerkits_module_publish_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_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/frameworks/kits/ability/native:abilitykit_native", + "//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" +} + +ohos_moduletest("ans_innerkits_module_slot_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 = [ + "ans_innerkits_module_slot_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_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" +} + +ohos_moduletest("ans_innerkits_module_setting_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 = [ + "ans_innerkits_module_setting_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_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", @@ -123,5 +362,10 @@ group("moduletest") { testonly = true deps = [] - deps += [ ":ans_fw_module_test" ] + deps += [ + ":ans_fw_module_test", + ":ans_innerkits_module_publish_test", + ":ans_innerkits_module_setting_test", + ":ans_innerkits_module_slot_test", + ] } diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index 6a33dab286b54ad5511a9a0ca73e24a6f0f928f8..7a35c46c2a3fa607abeb1a99218b17ec423d83f8 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -1,9 +1,32 @@ -#include +/* + * 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 +#include +#include +#include +#include +#include +#include +#include "advanced_notification_service.h" +#include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_manager_proxy.h" -#include "advanced_notification_service.h" +#include "ans_mt_constant.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "notification_content.h" @@ -16,40 +39,257 @@ using namespace testing::ext; namespace OHOS { namespace Notification { -const int32_t USLEEP_TIME = 10000; -bool callBackFunReceived = false; -bool OnConsumedReceived = false; -bool OnCanceledReceived = false; +enum class SubscriberEventType { + ON_SUBSCRIBERESULT, + ON_UNSUBSCRIBERESULT, + ON_DIED, + ON_UPDATE, + ON_DISTURBMODECHANGED, + ON_CANCELED, + ON_CANCELED_WITH_SORTINGMAP_AND_DELETEREASON, + ON_CONSUMED, + ON_CONSUMED_WITH_SORTINGMAP, + UNKNOWN, +}; + +class SubscriberEvent { +public: + ~SubscriberEvent() + {} + SubscriberEventType GetType() + { + return type_; + } + +protected: + SubscriberEvent(SubscriberEventType type) : type_(type) + {} + + SubscriberEventType type_; +}; + +class OnSubscribeResultEvent : public SubscriberEvent { +public: + ~OnSubscribeResultEvent() + {} + OnSubscribeResultEvent(NotificationConstant::SubscribeResult result) + : SubscriberEvent(SubscriberEventType::ON_SUBSCRIBERESULT), subscribeResult_(result) + {} + NotificationConstant::SubscribeResult GetSubscribeResult() + { + return subscribeResult_; + } + +private: + NotificationConstant::SubscribeResult subscribeResult_; +}; + +class OnUnSubscribeResultEvent : public SubscriberEvent { +public: + OnUnSubscribeResultEvent(NotificationConstant::SubscribeResult result) + : SubscriberEvent(SubscriberEventType::ON_UNSUBSCRIBERESULT), unSubscribeResult_(result) + {} + NotificationConstant::SubscribeResult GetUnSubscribeResult() + { + return unSubscribeResult_; + } + +private: + NotificationConstant::SubscribeResult unSubscribeResult_; +}; + +class OnDiedEvent : public SubscriberEvent { +public: + OnDiedEvent() : SubscriberEvent(SubscriberEventType::ON_DIED) + {} +}; + +class OnUpdatedEvent : public SubscriberEvent { +public: + OnUpdatedEvent(const std::shared_ptr &sortingMap) + : SubscriberEvent(SubscriberEventType::ON_UPDATE), sortingMap_(sortingMap) + {} + + std::shared_ptr GetNotificationSortingMap() + { + return sortingMap_; + } + +private: + std::shared_ptr sortingMap_; +}; + +class OnDisturbModeChangedEvent : public SubscriberEvent { +public: + OnDisturbModeChangedEvent(int disturbMode) + : SubscriberEvent(SubscriberEventType::ON_DISTURBMODECHANGED), disturbMode_(disturbMode) + {} + + int GetDisturbModeChanged() + { + return disturbMode_; + } + +private: + int disturbMode_; +}; + +class OnOnCanceledEvent : public SubscriberEvent { +public: + OnOnCanceledEvent(const std::shared_ptr &request) + : SubscriberEvent(SubscriberEventType::ON_CANCELED), request_(request) + {} + + std::shared_ptr GetRequest() + { + return request_; + } + +private: + std::shared_ptr request_; +}; + +class OnOnCanceledWithSortingMapAndDeleteReasonEvent : public SubscriberEvent { +public: + OnOnCanceledWithSortingMapAndDeleteReasonEvent(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) + : SubscriberEvent(SubscriberEventType::ON_CANCELED_WITH_SORTINGMAP_AND_DELETEREASON), + request_(request), + sortingMap_(sortingMap), + deleteReason_(deleteReason) + {} + + std::shared_ptr GetRequest() + { + return request_; + } + std::shared_ptr GetSortingMap() + { + return sortingMap_; + } + int GetDeleteReason() + { + return deleteReason_; + } + +private: + std::shared_ptr request_; + std::shared_ptr sortingMap_; + int deleteReason_; +}; + +class OnConsumedEvent : public SubscriberEvent { +public: + OnConsumedEvent(const std::shared_ptr &request) + : SubscriberEvent(SubscriberEventType::ON_CONSUMED), request_(request) + {} + + std::shared_ptr GetRequest() + { + return request_; + } + +private: + std::shared_ptr request_; +}; + +class OnConsumedWithSortingMapEvent : public SubscriberEvent { +public: + OnConsumedWithSortingMapEvent( + const std::shared_ptr &request, const std::shared_ptr &sortingMap) + : SubscriberEvent(SubscriberEventType::ON_CONSUMED_WITH_SORTINGMAP), request_(request), sortingMap_(sortingMap) + { + type_ = SubscriberEventType::ON_CONSUMED_WITH_SORTINGMAP; + } + + std::shared_ptr GetRequest() + { + return request_; + } + + std::shared_ptr GetSortingMap() + { + return sortingMap_; + } + +private: + std::shared_ptr request_; + std::shared_ptr sortingMap_; +}; + class TestAnsSubscriber : public NotificationSubscriber { public: virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override - {} + { + std::shared_ptr event = std::make_shared(result); + std::unique_lock lck(mtx_); + events_.push_back(event); + } virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override - {} + { + std::shared_ptr event = std::make_shared(result); + std::unique_lock lck(mtx_); + events_.push_back(event); + } virtual void OnDied() override {} virtual void OnUpdate(const std::shared_ptr &sortingMap) override - {} + { + std::shared_ptr event = std::make_shared(sortingMap); + std::unique_lock lck(mtx_); + events_.push_back(event); + } virtual void OnDisturbModeChanged(int disturbMode) override - {} + { + std::shared_ptr event = std::make_shared(disturbMode); + std::unique_lock lck(mtx_); + events_.push_back(event); + } virtual void OnCanceled(const std::shared_ptr &request) override { - OnCanceledReceived = true; + std::shared_ptr event = std::make_shared(request); + std::unique_lock lck(mtx_); + events_.push_back(event); } virtual void OnCanceled(const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason) override { - callBackFunReceived = false; + std::shared_ptr event = + std::make_shared(request, sortingMap, deleteReason); + std::unique_lock lck(mtx_); + events_.push_back(event); } virtual void OnConsumed(const std::shared_ptr &request) override { - OnConsumedReceived = true; + std::shared_ptr event = std::make_shared(request); + std::unique_lock lck(mtx_); + events_.push_back(event); } + virtual void OnConsumed(const std::shared_ptr &request, const std::shared_ptr &sortingMap) override { - callBackFunReceived = true; + std::shared_ptr event = + std::make_shared(request, sortingMap); + std::unique_lock lck(mtx_); + events_.push_back(event); } + + std::list> GetEvents() + { + std::unique_lock lck(mtx_); + return events_; + } + + void ClearEvents() + { + std::unique_lock lck(mtx_); + events_.clear(); + } + +private: + std::mutex mtx_; + std::list> events_; }; class AnsFWModuleTest : public testing::Test { @@ -58,816 +298,771 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + inline void SleepForFC() + { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } }; -sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); -void AnsFWModuleTest::SetUpTestCase() -{ - sptr service = OHOS::Notification::AdvancedNotificationService::GetInstance(); - OHOS::ISystemAbilityManager::SAExtraProp saExtraProp; - systemAbilityManager->AddSystemAbility(OHOS::ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, service, saExtraProp); -} +class EventParser { +public: + EventParser() + { + waitOnSubscriber_ = 0; + waitOnUnSubscriber_ = 0; + waitOnConsumed_ = false; + onConsumedReq_.clear(); + onConsumedWithSortingMapReq_.clear(); + onConsumedWithSortingMapSor_.clear(); + waitOnConsumedWithSortingMap_ = false; + waitOnCanceled_ = false; + onCanceledReq_.clear(); + onCanceledWithSortingMapReq_.clear(); + onCanceledWithSortingMapSor_.clear(); + onCanceledWithSortingMapDelRea_.clear(); + waitOnCanceledWithSortingMapAndDeleteReason_ = false; + } -void AnsFWModuleTest::TearDownTestCase() -{} + void parse(std::list> events) + { + for (auto event : events) { + if (event->GetType() == SubscriberEventType::ON_SUBSCRIBERESULT) { + std::shared_ptr ev = std::static_pointer_cast(event); + waitOnSubscriber_ = ev->GetSubscribeResult(); + } else if (event->GetType() == SubscriberEventType::ON_CONSUMED) { + std::shared_ptr ev = std::static_pointer_cast(event); + waitOnConsumed_ = true; + onConsumedReq_.push_back(ev->GetRequest()); + } else if (event->GetType() == SubscriberEventType::ON_CONSUMED_WITH_SORTINGMAP) { + std::shared_ptr ev = + std::static_pointer_cast(event); + waitOnConsumedWithSortingMap_ = true; + onConsumedWithSortingMapReq_.push_back(ev->GetRequest()); + onConsumedWithSortingMapSor_.push_back(ev->GetSortingMap()); + } else if (event->GetType() == SubscriberEventType::ON_CANCELED) { + std::shared_ptr ev = std::static_pointer_cast(event); + waitOnCanceled_ = true; + onCanceledReq_.push_back(ev->GetRequest()); + } else if (event->GetType() == SubscriberEventType::ON_CANCELED_WITH_SORTINGMAP_AND_DELETEREASON) { + std::shared_ptr ev = + std::static_pointer_cast(event); + waitOnCanceledWithSortingMapAndDeleteReason_ = true; + onCanceledWithSortingMapReq_.push_back(ev->GetRequest()); + onCanceledWithSortingMapSor_.push_back(ev->GetSortingMap()); + onCanceledWithSortingMapDelRea_.push_back(ev->GetDeleteReason()); + } else if (event->GetType() == SubscriberEventType::ON_UNSUBSCRIBERESULT) { + std::shared_ptr ev = + std::static_pointer_cast(event); + waitOnUnSubscriber_ = ev->GetUnSubscribeResult(); + } + } + } -void AnsFWModuleTest::SetUp() -{ - callBackFunReceived = false; - OnConsumedReceived = false; - OnCanceledReceived = false; -} + void setWaitOnConsumed(bool bl) + { + waitOnConsumed_ = bl; + } -void AnsFWModuleTest::TearDown() -{ - NotificationHelper::CancelAllNotifications(); - sleep(1); -} + void setWaitOnCanceled(bool bl) + { + waitOnCanceled_ = bl; + } -/** - * @tc.number : ANS_FW_MT_RemoveNotification_00100 - * @tc.name : - * @tc.desc : The subscriber remove all notifications from the notification queue. - * The subscriber receives the notification of the deletion. - */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00100, Function | MediumTest | Level1) -{ - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - + void setWaitOnCanceledWithSortingMapAndDeleteReason(bool bl) + { + waitOnCanceledWithSortingMapAndDeleteReason_ = bl; + } - std::shared_ptr implContent = std::make_shared(); - std::shared_ptr content = std::make_shared(implContent); + void setWaitOnUnSubscriber() + { + waitOnUnSubscriber_ = NotificationConstant::SubscribeResult::RESOURCES_FAIL; + } - std::string label = "Label"; - NotificationRequest req(0); - req.SetLabel(label); - req.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); - EXPECT_EQ(OnConsumedReceived, true); - - EXPECT_EQ(0, NotificationHelper::RemoveNotifications()); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, true); - usleep(USLEEP_TIME); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); -} + uint32_t getWaitOnSubscriber() + { + return waitOnSubscriber_; + } -/** - * @tc.number : ANS_FW_MT_RemoveNotification_00200 - * @tc.name : - * @tc.desc : The subscriber remove the notification from the notification queue according to the specified Key. - * The subscriber receives the notification of the deletion. - */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00200, Function | MediumTest | Level1) -{ - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + uint32_t getWaitOnUnSubscriber() + { + return waitOnUnSubscriber_; + } - std::shared_ptr implContent = std::make_shared(); - std::shared_ptr content = std::make_shared(implContent); + bool getwaitOnConsumed() + { + return waitOnConsumed_; + } - std::string label = "Label"; - NotificationRequest req(0); - req.SetLabel(label); - req.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); - EXPECT_EQ(OnConsumedReceived, true); + std::vector> getOnConsumedReq() + { + return onConsumedReq_; + } - std::vector> notifications; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notifications)); - std::string key = notifications[0]->GetKey().c_str(); + std::vector> getOnConsumedWithSortingMapReq() + { + return onConsumedWithSortingMapReq_; + } - EXPECT_EQ(0, NotificationHelper::RemoveNotification(key)); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, true); - usleep(USLEEP_TIME); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); -} + std::vector> getOnConsumedWithSortingMapSor() + { + return onConsumedWithSortingMapSor_; + } -/** - * @tc.number : ANS_FW_MT_RemoveNotification_00300 - * @tc.name : - * @tc.desc : An empty key was used when deleting the notification. - */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00300, Function | MediumTest | Level1) -{ - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + bool getWaitOnConsumedWithSortingMap() + { + return waitOnConsumedWithSortingMap_; + } - std::shared_ptr implContent = std::make_shared(); - std::shared_ptr content = std::make_shared(implContent); + bool getWaitOnCanceled() + { + return waitOnCanceled_; + } - std::string label = "Label"; - NotificationRequest req(0); - req.SetLabel(label); - req.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); - EXPECT_EQ(OnConsumedReceived, true); + bool getWaitOnCanceledWithSortingMapAndDeleteReason() + { + return waitOnCanceledWithSortingMapAndDeleteReason_; + } - std::vector> notifications; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notifications)); - std::string key = notifications[0]->GetKey().c_str(); + std::vector> getOnCanceledReq() + { + return onCanceledReq_; + } - EXPECT_EQ((int)ERR_ANS_INVALID_PARAM, (int)NotificationHelper::RemoveNotification(std::string())); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, false); - usleep(USLEEP_TIME); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); -} + std::vector> getOnCanceledWithSortingMapReq() + { + return onCanceledWithSortingMapReq_; + } -/** - * @tc.number : ANS_FW_MT_RemoveNotification_00400 - * @tc.name : - * @tc.desc : A non-existent key was used when deleting the notification. - */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00400, Function | MediumTest | Level1) -{ - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + std::vector> getOnCanceledWithSortingMapSor() + { + return onCanceledWithSortingMapSor_; + } - std::shared_ptr implContent = std::make_shared(); - std::shared_ptr content = std::make_shared(implContent); + std::vector getOnCanceledWithSortingMapDelRea() + { + return onCanceledWithSortingMapDelRea_; + } - std::string label = "Label"; - NotificationRequest req(0); - req.SetLabel(label); - req.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); - EXPECT_EQ(OnConsumedReceived, true); - - std::vector> notifications; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notifications)); - std::string key = "A non-existent key"; - - EXPECT_EQ((int)ERR_ANS_NOTIFICATION_NOT_EXISTS, (int)NotificationHelper::RemoveNotification(key)); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, false); - usleep(USLEEP_TIME); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); -} +private: + uint32_t waitOnSubscriber_; + uint32_t waitOnUnSubscriber_; + bool waitOnConsumed_ = false; + std::vector> onConsumedReq_; + std::vector> onConsumedWithSortingMapReq_; + std::vector> onConsumedWithSortingMapSor_; + bool waitOnConsumedWithSortingMap_ = false; + bool waitOnCanceled_ = false; + std::vector> onCanceledReq_; + std::vector> onCanceledWithSortingMapReq_; + std::vector> onCanceledWithSortingMapSor_; + std::vector onCanceledWithSortingMapDelRea_; + bool waitOnCanceledWithSortingMapAndDeleteReason_ = false; +}; -/** - * @tc.number : ANS_FW_MT_RemoveNotification_00500 - * @tc.name : - * @tc.desc : Use the same key to delete repeatedly. - */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00500, Function | MediumTest | Level1) +sptr g_systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); +void AnsFWModuleTest::SetUpTestCase() { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - std::shared_ptr implContent = std::make_shared(); - std::shared_ptr content = std::make_shared(implContent); + sptr service = OHOS::Notification::AdvancedNotificationService::GetInstance(); + OHOS::ISystemAbilityManager::SAExtraProp saExtraProp; + g_systemAbilityManager->AddSystemAbility(OHOS::ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, service, saExtraProp); +} - std::string label = "Label"; - NotificationRequest req(0); - req.SetLabel(label); - req.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); - EXPECT_EQ(OnConsumedReceived, true); +void AnsFWModuleTest::TearDownTestCase() +{} - std::vector> notifications; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notifications)); - std::string key = notifications[0]->GetKey().c_str(); +void AnsFWModuleTest::SetUp() +{} - EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotification(key)); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, true); - OnCanceledReceived = false; - EXPECT_EQ((int)ERR_ANS_NOTIFICATION_NOT_EXISTS, (int)NotificationHelper::RemoveNotification(key)); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, false); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); +void AnsFWModuleTest::TearDown() +{ + NotificationHelper::CancelAllNotifications(); + NotificationHelper::RemoveAllSlots(); + NotificationHelper::RemoveNotifications(); + std::vector> groups; + NotificationHelper::GetNotificationSlotGroups(groups); + for (auto group : groups) { + NotificationHelper::RemoveNotificationSlotGroup(group->GetId().c_str()); + } + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_RemoveNotification_00600 - * @tc.name : - * @tc.desc : Delete an Unremovable notification. + * + * @tc.number : ANS_FW_MT_FlowControl_00100 + * @tc.name : FlowControl_00100 + * @tc.desc : Test notification's flow control. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00600, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_FlowControl_00100, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - std::shared_ptr implContent = std::make_shared(); + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; + info.AddAppName(APP_NAME); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); + std::shared_ptr implContent = std::make_shared(); std::shared_ptr content = std::make_shared(implContent); - - std::string label = "Label"; - NotificationRequest req(0); - req.SetLabel(label); - req.SetContent(content); - req.SetUnremovable(false); // TODO should be true - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); - EXPECT_EQ(OnConsumedReceived, true); - - std::vector> notifications; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notifications)); - std::string key = notifications[0]->GetKey().c_str(); - - EXPECT_EQ((int)ERR_ANS_NOTIFICATION_IS_UNREMOVABLE, (int)NotificationHelper::RemoveNotification(key)); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, false); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + for (uint32_t i = 0; i <= MAX_ACTIVE_NUM_PERSECOND; i++) { + std::string label = std::to_string(i); + NotificationRequest req(i); + req.SetLabel(label); + req.SetContent(content); + if (i < MAX_ACTIVE_NUM_PERSECOND) { + EXPECT_EQ(NotificationHelper::PublishNotification(req), ERR_OK); + } else { + EXPECT_EQ(NotificationHelper::PublishNotification(req), (int)ERR_ANS_OVER_MAX_ACITVE_PERSECOND); + } + } + SleepForFC(); + EXPECT_EQ(NotificationHelper::RemoveNotifications(), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + SleepForFC(); + std::list> events = subscriber.GetEvents(); + EventParser eventParser; + eventParser.parse(events); + for (uint32_t i = 0; i <= MAX_ACTIVE_NUM_PERSECOND; i++) { + std::string notificationLabel = std::to_string(i); + std::string notificationIdStr = std::to_string(i); + int32_t notificationIdInt = i; + if (i < MAX_ACTIVE_NUM_PERSECOND) { + std::stringstream stream; + stream << UID << KEY_SPLITER << notificationLabel << KEY_SPLITER << notificationIdInt; + std::string notificationKey = stream.str(); + NotificationSorting sorting; + EXPECT_EQ(eventParser.getOnConsumedReq()[i]->GetLabel().c_str(), notificationLabel); + EXPECT_EQ(eventParser.getOnConsumedReq()[i]->GetId(), notificationIdInt); + EXPECT_EQ(eventParser.getOnConsumedReq()[i]->GetKey(), notificationKey); + EXPECT_EQ(eventParser.getOnConsumedWithSortingMapReq()[i]->GetLabel().c_str(), notificationLabel); + EXPECT_EQ(eventParser.getOnConsumedWithSortingMapReq()[i]->GetId(), notificationIdInt); + EXPECT_EQ(eventParser.getOnConsumedWithSortingMapReq()[i]->GetKey(), notificationKey); + EXPECT_TRUE( + eventParser.getOnConsumedWithSortingMapSor()[i]->GetNotificationSorting(notificationKey, sorting)); + EXPECT_EQ(sorting.GetKey().c_str(), notificationKey); + } + } + EXPECT_EQ((uint32_t)eventParser.getOnConsumedReq().size(), MAX_ACTIVE_NUM_PERSECOND); + EXPECT_EQ((uint32_t)eventParser.getOnConsumedWithSortingMapReq().size(), MAX_ACTIVE_NUM_PERSECOND); + EXPECT_EQ(eventParser.getWaitOnSubscriber(), NotificationConstant::SubscribeResult::SUCCESS); + EXPECT_EQ(eventParser.getWaitOnUnSubscriber(), NotificationConstant::SubscribeResult::SUCCESS); + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_RemoveNotification_00700 - * @tc.name : - * @tc.desc : Delete all notifications including Unremovable notifications. + * + * @tc.number : ANS_FW_MT_RemoveNotificaitonsByKey_00100 + * @tc.name : RemoveNotificaitonsByKey_00100 + * @tc.desc : Remove Notification by key. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00700, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitonsByKey_00100, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - std::shared_ptr implContent = std::make_shared(); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); + std::shared_ptr implContent = std::make_shared(); std::shared_ptr content = std::make_shared(implContent); - - std::string label1 = "Label1"; - NotificationRequest req1(0); - req1.SetLabel(label1); - req1.SetContent(content); - req1.SetUnremovable(false); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label2 = "Label2"; - NotificationRequest req2(0); - req2.SetLabel(label2); - req2.SetContent(content); - req2.SetUnremovable(false); // TODO should be true - EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); - EXPECT_EQ(OnConsumedReceived, true); - - std::vector> notificationsBefor; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notificationsBefor)); - EXPECT_EQ(2, (int)notificationsBefor.size()); - - EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotifications()); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, true); - - std::vector> notificationsAfter; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notificationsAfter)); - // EXPECT_EQ(1, (int)notificationsAfter.size()); TODO - // EXPECT_EQ("Label2", notificationsAfter[0]->GetLabel()); TODO - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + req.SetContent(content); + EXPECT_EQ(NotificationHelper::PublishNotification(req), ERR_OK); + std::vector> notifications; + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + std::string key = notifications[0]->GetKey().c_str(); + EXPECT_EQ(NotificationHelper::RemoveNotification(key), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + SleepForFC(); + std::list> events = subscriber.GetEvents(); + EventParser eventParser; + eventParser.parse(events); + EXPECT_TRUE(eventParser.getwaitOnConsumed()); + EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.getWaitOnCanceled()); + EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); + EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetId(), 0); + std::stringstream stream; + stream << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 0; + std::string notificationKey = stream.str(); + NotificationSorting sorting; + EXPECT_EQ(eventParser.getOnCanceledReq()[0]->GetKey(), notificationKey); + EXPECT_EQ(eventParser.getOnCanceledWithSortingMapReq()[0]->GetKey(), notificationKey); + EXPECT_TRUE(eventParser.getOnConsumedWithSortingMapSor()[0]->GetNotificationSorting(notificationKey, sorting)); + EXPECT_EQ(sorting.GetKey().c_str(), notificationKey); + EXPECT_EQ(eventParser.getOnCanceledWithSortingMapDelRea()[0], CANCEL_REASON_DELETE); + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_RemoveNotification_00800 - * @tc.name : - * @tc.desc : Delete notification based on bundle. + * + * @tc.number : ANS_FW_MT_RemoveNotificaitonsByKey_00200 + * @tc.name : RemoveNotificaitonsByKey_00200 + * @tc.desc : Remove Notification by a nonexistent key. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00800, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitonsByKey_00200, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - std::shared_ptr implContent = std::make_shared(); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); + std::shared_ptr implContent = std::make_shared(); std::shared_ptr content = std::make_shared(implContent); - - std::string label1 = "Label1"; - NotificationRequest req1(0); - req1.SetLabel(label1); - req1.SetContent(content); - req1.SetUnremovable(false); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::vector> notificationsBefor; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notificationsBefor)); - EXPECT_EQ(1, (int)notificationsBefor.size()); - - EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotifications("bundleName")); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, false); - - std::vector> notificationsAfter; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notificationsAfter)); - EXPECT_EQ(0, (int)notificationsAfter.size()); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + req.SetContent(content); + EXPECT_EQ(NotificationHelper::PublishNotification(req), ERR_OK); + std::vector> notifications; + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_EQ(NotificationHelper::RemoveNotification(AN_NOT_EXIST_KEY), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + std::string key = notifications[0]->GetKey().c_str(); + EXPECT_EQ(NotificationHelper::RemoveNotification(key), (int)ERR_OK); + SleepForFC(); + std::list> events = subscriber.GetEvents(); + EventParser eventParser; + eventParser.parse(events); + EXPECT_TRUE(eventParser.getWaitOnCanceled()); + eventParser.setWaitOnCanceled(false); + EXPECT_EQ(NotificationHelper::RemoveNotification(key), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + events = subscriber.GetEvents(); + eventParser.parse(events); + EXPECT_TRUE(eventParser.getWaitOnCanceled()); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + SleepForFC(); + events = subscriber.GetEvents(); + eventParser.parse(events); + EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_RemoveNotification_00900 - * @tc.name : - * @tc.desc : Delete notification based on A non-existent bundle. + * + * @tc.number : ANS_FW_MT_RemoveNotificaitons_00100 + * @tc.name : RemoveNotificaitons_00100 + * @tc.desc : Remove all Notifications. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00900, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitons_00100, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); - std::shared_ptr implContent = std::make_shared(); + std::shared_ptr implContent = std::make_shared(); std::shared_ptr content = std::make_shared(implContent); - - std::string label1 = "Label1"; - NotificationRequest req1(0); - req1.SetLabel(label1); + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + req.SetContent(content); + EXPECT_EQ(NotificationHelper::PublishNotification(req), ERR_OK); + SleepForFC(); + EventParser eventParser; + std::list> events = subscriber.GetEvents(); + eventParser.parse(events); + EXPECT_TRUE(eventParser.getwaitOnConsumed()); + eventParser.setWaitOnConsumed(false); + + NotificationRequest req1(1); + req1.SetLabel(NOTIFICATION_LABEL_0); req1.SetContent(content); - req1.SetUnremovable(false); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::vector> notificationsBefor; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notificationsBefor)); - EXPECT_EQ(1, (int)notificationsBefor.size()); - - std::string bundleName = "A non-existent bundle"; - EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotifications(bundleName)); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, false); - - std::vector> notificationsAfter; - EXPECT_EQ(0, NotificationHelper::GetAllActiveNotifications(notificationsAfter)); - EXPECT_EQ(1, (int)notificationsAfter.size()); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + events = subscriber.GetEvents(); + EXPECT_EQ(NotificationHelper::PublishNotification(req1), ERR_OK); + SleepForFC(); + eventParser.parse(events); + EXPECT_TRUE(eventParser.getwaitOnConsumed()); + SleepForFC(); + EXPECT_EQ(NotificationHelper::RemoveNotifications(), ERR_OK); + std::vector> notifications; + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_EQ((int)notifications.size(), (int)0); + + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + events = subscriber.GetEvents(); + eventParser.parse(events); + EXPECT_TRUE(eventParser.getWaitOnCanceled()); + EXPECT_TRUE(eventParser.getWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_GetActiveNotificationNums_00100 - * @tc.name : - * @tc.desc : Get the number of active notifications for the current application. + * + * @tc.number : ANS_FW_MT_RemoveNotificaitons_00200 + * @tc.name : RemoveNotificaitons_00200 + * @tc.desc : Remove Notifications when no Notification. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetActiveNotificationNums_00100, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitons_00200, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); + EventParser eventParser; + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - std::shared_ptr implContent = std::make_shared(); - std::shared_ptr content = std::make_shared(implContent); - - int countBefor = 0; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countBefor)); - EXPECT_EQ(0, countBefor); - - std::string label1 = "Label1"; - NotificationRequest req1(0); - req1.SetLabel(label1); - req1.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label2 = "Label2"; - NotificationRequest req2(0); - req2.SetLabel(label2); - req2.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label3 = "Label3"; - NotificationRequest req3(0); - req3.SetLabel(label3); - req3.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req3)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - int countAfter = 0; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countAfter)); - EXPECT_EQ(3, countAfter); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); + EXPECT_EQ(NotificationHelper::RemoveNotifications(), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + std::list> events = subscriber.GetEvents(); + eventParser.parse(events); + EXPECT_FALSE(eventParser.getwaitOnConsumed()); + EXPECT_FALSE(eventParser.getWaitOnConsumedWithSortingMap()); + EXPECT_FALSE(eventParser.getWaitOnCanceled()); + EXPECT_FALSE(eventParser.getWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_GetActiveNotificationNums_00200 - * @tc.name : - * @tc.desc : Get the number of active notifications for the current application. + * + * @tc.number : ANS_FW_MT_UnSubscriber_00100 + * @tc.name : UnSubscriber_00100 + * @tc.desc : Remove Subscriber. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetActiveNotificationNums_00200, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_UnSubscriber_00100, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - std::shared_ptr implContent = std::make_shared(); - std::shared_ptr content = std::make_shared(implContent); - - int countBefor = 0; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countBefor)); - EXPECT_EQ(0, countBefor); + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; + info.AddAppName("ANS_FW_MT_UnSubscriber_00100"); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + SleepForFC(); + std::list> events = subscriber.GetEvents(); + uint32_t waitOnSubscriber_; + uint32_t waitOnUnSubscriber_; + + for (auto event : events) { + if (event->GetType() == SubscriberEventType::ON_SUBSCRIBERESULT) { + std::shared_ptr ev = std::static_pointer_cast(event); + waitOnSubscriber_ = ev->GetSubscribeResult(); + } else if (event->GetType() == SubscriberEventType::ON_UNSUBSCRIBERESULT) { + std::shared_ptr ev = std::static_pointer_cast(event); + waitOnUnSubscriber_ = ev->GetUnSubscribeResult(); + } + } + EXPECT_EQ(waitOnSubscriber_, NotificationConstant::SubscribeResult::SUCCESS); - std::string label1 = "Label1"; - NotificationRequest req1(0); - req1.SetLabel(label1); - req1.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label2 = "Label2"; - NotificationRequest req2(0); - req2.SetLabel(label2); - req2.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label3 = "Label3"; - NotificationRequest req3(0); - req3.SetLabel(label3); - req3.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req3)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - int countBefore = 0; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countBefore)); - EXPECT_EQ(3, countBefore); - - EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotifications()); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, true); - - int countAfter = 0; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countAfter)); - EXPECT_EQ(0, countAfter); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_GetActiveNotifications_00100 - * @tc.name : - * @tc.desc : Get the active notifications for the current application. + * + * @tc.number : ANS_FW_MT_UnSubscriber_00200 + * @tc.name : UnSubscriber_00200 + * @tc.desc : Remove Subscriber. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetActiveNotifications_00100, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_UnSubscriber_00200, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - std::shared_ptr implContent = std::make_shared(); - std::shared_ptr content = std::make_shared(implContent); - - int countBefor = 0; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countBefor)); - EXPECT_EQ(0, countBefor); - - std::string label1 = "Label1"; - NotificationRequest req1(0); - req1.SetLabel(label1); - req1.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label2 = "Label2"; - NotificationRequest req2(0); - req2.SetLabel(label2); - req2.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label3 = "Label3"; - NotificationRequest req3(0); - req3.SetLabel(label3); - req3.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req3)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::vector> requests; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotifications(requests)); - EXPECT_EQ("Label1", requests[0]->GetLabel().c_str()); - EXPECT_EQ("Label2", requests[1]->GetLabel().c_str()); - EXPECT_EQ("Label3", requests[2]->GetLabel().c_str()); - - EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotifications()); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, true); - - std::vector> requestsRemoved; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotifications(requestsRemoved)); - EXPECT_EQ(0, (int)requestsRemoved.size()); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + EventParser eventParser; + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; + info.AddAppName("ANS_FW_MT_UnSubscriber_00100"); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), (int)ERR_OK); + SleepForFC(); + std::list> events = subscriber.GetEvents(); + uint32_t waitOnSubscriber_; + uint32_t waitOnUnSubscriber_; + for (auto event : events) { + if (event->GetType() == SubscriberEventType::ON_SUBSCRIBERESULT) { + std::shared_ptr ev = std::static_pointer_cast(event); + waitOnSubscriber_ = ev->GetSubscribeResult(); + } else if (event->GetType() == SubscriberEventType::ON_UNSUBSCRIBERESULT) { + std::shared_ptr ev = std::static_pointer_cast(event); + waitOnUnSubscriber_ = ev->GetUnSubscribeResult(); + } + } + EXPECT_EQ(waitOnSubscriber_, NotificationConstant::SubscribeResult::SUCCESS); + waitOnSubscriber_ = NotificationConstant::SubscribeResult::PREMISSION_FAIL; + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), (int)ERR_OK); + events = subscriber.GetEvents(); + for (auto event : events) { + if (event->GetType() == SubscriberEventType::ON_UNSUBSCRIBERESULT) { + std::shared_ptr ev = std::static_pointer_cast(event); + waitOnUnSubscriber_ = ev->GetUnSubscribeResult(); + } + } + EXPECT_EQ(waitOnUnSubscriber_, NotificationConstant::SubscribeResult::SUCCESS); + subscriber.ClearEvents(); + SleepForFC(); } - /** - * @tc.number : ANS_FW_MT_GetActiveNotifications_00200 - * @tc.name : - * @tc.desc : Get the active notifications for the current application. + * + * @tc.number : ANS_FW_MT_Subscriber_00100 + * @tc.name : Subscriber_00100 + * @tc.desc : Subscriber Notifications. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetActiveNotifications_00200, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_Subscriber_00100, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - NotificationRequest req1(0); - req1.SetNotificationId(1); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - NotificationRequest req2(0); - req2.SetNotificationId(2); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - NotificationRequest req3(0); - req3.SetNotificationId(3); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req3)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotifications()); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, true); - - std::vector> notifications; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotifications(notifications)); - EXPECT_EQ(nullptr, notifications[0]); - NotificationHelper::GetActiveNotifications(notifications); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; + info.AddAppName("ANS_FW_MT_UnSubscriber_00100"); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); + SleepForFC(); + std::list> events = subscriber.GetEvents(); + uint32_t waitOnSubscriber_; + uint32_t waitOnUnSubscriber_; + for (auto event : events) { + if (event->GetType() == SubscriberEventType::ON_SUBSCRIBERESULT) { + std::shared_ptr ev = std::static_pointer_cast(event); + waitOnSubscriber_ = ev->GetSubscribeResult(); + } else if (event->GetType() == SubscriberEventType::ON_UNSUBSCRIBERESULT) { + std::shared_ptr ev = std::static_pointer_cast(event); + waitOnUnSubscriber_ = ev->GetUnSubscribeResult(); + } + } + EXPECT_EQ(waitOnSubscriber_, NotificationConstant::SubscribeResult::SUCCESS); + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_GetAllActiveNotifications_00100 - * @tc.name : - * @tc.desc : Get all of active notifications for the current application. + * + * @tc.number : ANS_FW_MT_CancelNotificationById_00100 + * @tc.name : CancelNotificationById_00100 + * @tc.desc : Cancel Notification By Id. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetAllActiveNotifications_00100, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelNotificationById_00100, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); + EventParser eventParser; + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - std::shared_ptr implContent = std::make_shared(); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); + std::shared_ptr implContent = std::make_shared(); std::shared_ptr content = std::make_shared(implContent); - - std::string label1 = "Label1"; - NotificationRequest req1(0); - req1.SetLabel(label1); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label2 = "Label2"; - NotificationRequest req2(0); - req2.SetLabel(label2); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label3 = "Label3"; - NotificationRequest req3(0); - req3.SetLabel(label3); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req3)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - + NotificationRequest req(1); + req.SetLabel(NOTIFICATION_LABEL_0); + req.SetContent(content); + EXPECT_EQ(NotificationHelper::PublishNotification(req), ERR_OK); + SleepForFC(); std::vector> notifications; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetAllActiveNotifications(notifications)); - EXPECT_EQ(label1, notifications[0]->GetLabel()); - EXPECT_EQ(label2, notifications[1]->GetLabel()); - EXPECT_EQ(label3, notifications[2]->GetLabel()); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + int32_t id = notifications[0]->GetId(); + SleepForFC(); + EXPECT_EQ(NotificationHelper::CancelNotification(NOTIFICATION_LABEL_0, id), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + + SleepForFC(); + std::list> events = subscriber.GetEvents(); + + eventParser.parse(events); + EXPECT_TRUE(eventParser.getwaitOnConsumed()); + EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.getWaitOnCanceled()); + EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); + EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetId(), 1); + std::stringstream stream; + stream << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 1; + std::string notificationKey = stream.str(); + NotificationSorting sorting; + EXPECT_EQ(eventParser.getOnCanceledReq()[0]->GetKey(), notificationKey); + EXPECT_EQ(eventParser.getOnCanceledWithSortingMapReq()[0]->GetKey(), notificationKey); + EXPECT_TRUE(eventParser.getOnConsumedWithSortingMapSor()[0]->GetNotificationSorting(notificationKey, sorting)); + EXPECT_EQ(sorting.GetKey().c_str(), notificationKey); + EXPECT_EQ(eventParser.getOnCanceledWithSortingMapDelRea()[0], APP_CANCEL_REASON_DELETE); + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_GetAllActiveNotifications_00200 - * @tc.name : - * @tc.desc : Get all of active notifications for the current application. + * + * @tc.number : ANS_FW_MT_CancelNotificationById_00200 + * @tc.name : CancelNotificationById_00200 + * @tc.desc : Cancel Notification By Id when Id is not exist. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetAllActiveNotifications_00200, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelNotificationById_00200, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); + EventParser eventParser; + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); - std::shared_ptr implContent = std::make_shared(); + std::shared_ptr implContent = std::make_shared(); std::shared_ptr content = std::make_shared(implContent); - - std::string label1 = "Label1"; - NotificationRequest req1(0); - req1.SetLabel(label1); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label2 = "Label2"; - NotificationRequest req2(0); - req2.SetLabel(label2); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::string label3 = "Label3"; - NotificationRequest req3(0); - req3.SetLabel(label3); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req3)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotifications()); - usleep(USLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, true); - + NotificationRequest req(1); + req.SetLabel(NOTIFICATION_LABEL_0); + req.SetContent(content); + EXPECT_EQ(NotificationHelper::PublishNotification(req), ERR_OK); + SleepForFC(); std::vector> notifications; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetAllActiveNotifications(notifications)); - EXPECT_EQ(nullptr, notifications[0]); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + int32_t id = 0; + SleepForFC(); + + eventParser.setWaitOnCanceled(false); + eventParser.setWaitOnCanceledWithSortingMapAndDeleteReason(false); + EXPECT_EQ(NotificationHelper::CancelNotification(NOTIFICATION_LABEL_0, id), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + + SleepForFC(); + std::list> events = subscriber.GetEvents(); + eventParser.parse(events); + EXPECT_TRUE(eventParser.getwaitOnConsumed()); + EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); + EXPECT_FALSE(eventParser.getWaitOnCanceled()); + EXPECT_FALSE(eventParser.getWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_GetAllActiveNotifications_key_00100 + * + * @tc.number : ANS_FW_MT_CancelAllNotifications_00100 * @tc.name : - * @tc.desc : Get the active notifications related by key for the current application. + * @tc.desc : Cancel all notifications. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetAllActiveNotifications_key_00100, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelAllNotifications_00100, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - - std::vector key{"key_type1", "key_type2"}; - - std::string label1 = "label1"; - std::string label2 = "label2"; - std::string label3 = "label3"; - - NotificationRequest req1(0); - req1.SetSortingKey(key[0]); - req1.SetLabel(label1); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - NotificationRequest req2(0); - req2.SetSortingKey(key[0]); - req2.SetLabel(label2); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - NotificationRequest req3(0); - req3.SetSortingKey(key[1]); - req3.SetLabel(label3); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - EXPECT_EQ(OnConsumedReceived, true); - OnConsumedReceived = false; - - std::vector> notifications; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetAllActiveNotifications(key, notifications)); - EXPECT_EQ(label1, notifications[0]->GetLabel()); - EXPECT_EQ(label2, notifications[1]->GetLabel()); - EXPECT_EQ(label3, notifications[2]->GetLabel()); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); -} + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); -/** - * @tc.number : ANS_FW_MT_UnSubscribeNotification_00100 - * @tc.name : - * @tc.desc : Cancel a subscribe. - */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_UnSubscribeNotification_00100, Function | MediumTest | Level1) -{ - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); + NotificationRequest req0(0); + req0.SetLabel(NOTIFICATION_LABEL_0); + req0.SetContent(content); + EXPECT_EQ(NotificationHelper::PublishNotification(req0), ERR_OK); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + NotificationRequest req1(1); + req1.SetLabel(NOTIFICATION_LABEL_1); + req1.SetContent(content); + EXPECT_EQ(NotificationHelper::PublishNotification(req1), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::CancelAllNotifications(), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + + SleepForFC(); + std::list> events = subscriber.GetEvents(); + + EventParser eventParser; + eventParser.parse(events); + EXPECT_TRUE(eventParser.getwaitOnConsumed()); + EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.getWaitOnCanceled()); + EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); + EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetId(), 0); + std::stringstream stream0; + stream0 << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 0; + std::string notificationKey0 = stream0.str(); + NotificationSorting sorting0; + EXPECT_EQ(eventParser.getOnCanceledReq()[0]->GetKey(), notificationKey0); + EXPECT_EQ(eventParser.getOnCanceledWithSortingMapReq()[0]->GetKey(), notificationKey0); + EXPECT_TRUE(eventParser.getOnConsumedWithSortingMapSor()[0]->GetNotificationSorting(notificationKey0, sorting0)); + EXPECT_EQ(sorting0.GetKey().c_str(), notificationKey0); + EXPECT_EQ(eventParser.getOnCanceledWithSortingMapDelRea()[0], APP_CANCEL_ALL_REASON_DELETE); + + EXPECT_EQ(eventParser.getOnConsumedReq()[1]->GetLabel().c_str(), NOTIFICATION_LABEL_1); + EXPECT_EQ(eventParser.getOnConsumedReq()[1]->GetId(), 1); + std::stringstream stream1; + stream1 << UID << KEY_SPLITER << NOTIFICATION_LABEL_1 << KEY_SPLITER << 1; + std::string notificationKey1 = stream1.str(); + NotificationSorting sorting1; + EXPECT_EQ(eventParser.getOnCanceledReq()[1]->GetKey(), notificationKey1); + EXPECT_EQ(eventParser.getOnCanceledWithSortingMapReq()[1]->GetKey(), notificationKey1); + EXPECT_TRUE(eventParser.getOnConsumedWithSortingMapSor()[1]->GetNotificationSorting(notificationKey1, sorting1)); + EXPECT_EQ(sorting1.GetKey().c_str(), notificationKey1); + EXPECT_EQ(eventParser.getOnCanceledWithSortingMapDelRea()[1], APP_CANCEL_ALL_REASON_DELETE); + + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_Subscribe_00100 + * + * @tc.number : ANS_FW_MT_PublishSoundNotification_00100 * @tc.name : - * @tc.desc : produce a subscribe + * @tc.desc : Publish a sound notification. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_WantAgent_00100, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_PublishSoundNotification_00100, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); + std::vector> slots; + NotificationSlot slot1; + slot1.SetType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slot1.SetSound(Uri(".")); + slot1.SetVibrationStyle(std::vector(1, 1)); + EXPECT_EQ(NotificationHelper::AddNotificationSlot(slot1), (int)ERR_OK); + + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + req.SetContent(content); + req.SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + EXPECT_EQ(NotificationHelper::PublishNotification(req), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::CancelAllNotifications(), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + SleepForFC(); + std::list> events = subscriber.GetEvents(); + + EventParser eventParser; + eventParser.parse(events); + EXPECT_TRUE(eventParser.getwaitOnConsumed()); + EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.getWaitOnCanceled()); + EXPECT_TRUE(eventParser.getWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); } /** - * @tc.number : ANS_FW_MT_DeleteSlots_00100 + * + * @tc.number : ANS_FW_MT_PublishVibrationNotification_00100 * @tc.name : - * @tc.desc : Delete slots. + * @tc.desc : Publish a vibration notification. */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_DeleteSlots_00100, Function | MediumTest | Level1) +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_PublishVibrationNotification_00100, Function | MediumTest | Level1) { - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); + std::vector> slots; + NotificationSlot slot1; + slot1.SetType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slot1.SetEnableVibration(true); + slot1.SetVibrationStyle(std::vector(1, 1)); + EXPECT_EQ(NotificationHelper::AddNotificationSlot(slot1), (int)ERR_OK); + + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; info.AddAppName("bundleName"); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); -} - -/** - * @tc.number : ANS_FW_MT_SlotGroupId_00100 - * @tc.name : - * @tc.desc : Delete all Notifications of the app. - */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_SlotGroupId_00100, Function | MediumTest | Level1) -{ - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - std::string AppName = "bundleName"; - info.AddAppName(AppName); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - EXPECT_EQ(0, NotificationHelper::RemoveNotifications(AppName)); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); -} - -/** - * @tc.number : ANS_FW_MT_RemoveNotifications_00100 - * @tc.name : - * @tc.desc : Delete all Notifications of the app. - */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotifications_00100, Function | MediumTest | Level1) -{ - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - std::string AppName = "bundleName"; - info.AddAppName(AppName); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - EXPECT_EQ(0, NotificationHelper::RemoveNotifications(AppName)); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); -} - -/** - * @tc.number : ANS_FW_MT_SoundSlotNotification_00100 - * @tc.name : - * @tc.desc : App published a sound notification . - */ -HWTEST_F(AnsFWModuleTest, ANS_FW_MT_SoundSlotNotification_00100, Function | MediumTest | Level1) -{ - auto subscriber = TestAnsSubscriber(); - NotificationSubscribeInfo info = NotificationSubscribeInfo(); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); - - std::string str{"test"}; - std::shared_ptr implContent = std::make_shared(str); + std::shared_ptr implContent = std::make_shared(); std::shared_ptr content = std::make_shared(implContent); - NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); req.SetContent(content); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); - EXPECT_EQ(OnConsumedReceived, true); - - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + req.SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + EXPECT_EQ(NotificationHelper::PublishNotification(req), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::CancelAllNotifications(), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + SleepForFC(); + std::list> events = subscriber.GetEvents(); + EventParser eventParser; + eventParser.parse(events); + EXPECT_TRUE(eventParser.getwaitOnConsumed()); + EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.getWaitOnCanceled()); + EXPECT_TRUE(eventParser.getWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); } + } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fbf6f3116f2490dc5fb5901a24aeea65c47bc785 --- /dev/null +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -0,0 +1,1130 @@ +/* + * 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 "context.h" +#include "datetime_ex.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "notification_helper.h" +#include "mock_bundle_manager.h" +#include "mock_ipc_skeleton.h" +#include "system_ability_definition.h" +#include "want_agent_info.h" +#include "want_agent_helper.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +static sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); +bool OnConsumedReceived = false; +bool OnCanceledReceived = false; +bool OnWantReceived = false; +const int32_t SLEEP_TIME = 5; +const int32_t ACTIVE_NUMS = 2; +const int32_t CASE_ONE = 1; +const int32_t CASE_TWO = 2; +const int32_t CASE_THREE = 3; +const int32_t CASE_FOUR = 4; +const int32_t CASE_FIVE = 5; +const int32_t CASE_SIX = 6; +const int32_t CASE_SEVEN = 7; +const int32_t CASE_EIGHT = 8; +const int32_t CASE_NINE = 9; +const int32_t CASE_TEN = 10; +const int32_t CASE_ELEVEN = 11; +const int32_t CASE_TWELVE = 12; +const int32_t CASE_THIRTEEN = 13; +const int32_t CASE_FOURTEEN = 14; +const int32_t CASE_FIFTEEN = 15; +const int32_t CASE_SIXTEEN = 16; +const int32_t CALLING_UID = 9999; +std::mutex g_subscribe_mtx; +std::mutex g_consumed_mtx; +std::mutex g_unsubscribe_mtx; +std::mutex g_send_finished_mtx; +AAFwk::Want g_want; + +const time_t TIME_OUT_SECONDS_LIMIT = 5; +const std::string CLASSIFICATION_ALARM{"alarm"}; + +class TestAnsSubscriber : public NotificationSubscriber { +public: + virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override + { + g_subscribe_mtx.unlock(); + } + + virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override + { + g_unsubscribe_mtx.unlock(); + } + + virtual void OnDied() override + {} + + virtual void OnUpdate(const std::shared_ptr &sortingMap) override + {} + + virtual void OnDisturbModeChanged(int disturbMode) override + {} + + virtual void OnCanceled(const std::shared_ptr &request) override + { + OnCanceledReceived = true; + } + + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override + {} + + virtual void OnConsumed(const std::shared_ptr &request) override + { + OnConsumedReceived = true; + g_consumed_mtx.unlock(); + NotificationRequest notificationRequest = request->GetNotificationRequest(); + NotificationConstant::DisturbMode disturbMode; + if (CASE_ONE == notificationRequest.GetNotificationId()) { + CheckCaseOneResult(notificationRequest); + } else if (CASE_TWO == notificationRequest.GetNotificationId()) { + CheckCaseTwoResult(notificationRequest); + } else if (CASE_THREE == notificationRequest.GetNotificationId()) { + CheckCaseThreeResult(notificationRequest); + } else if (CASE_FOUR == notificationRequest.GetNotificationId()) { + CheckCaseFourResult(notificationRequest); + } else if (CASE_FIVE == notificationRequest.GetNotificationId()) { + CheckCaseFiveResult(notificationRequest); + } else if (CASE_SIX == notificationRequest.GetNotificationId()) { + CheckCaseSixResult(notificationRequest); + } else if (CASE_SEVEN == notificationRequest.GetNotificationId()) { + CheckCaseSevenResult(notificationRequest); + } else if (CASE_EIGHT == notificationRequest.GetNotificationId()) { + CheckCaseEightResult(notificationRequest); + } else if (CASE_NINE == notificationRequest.GetNotificationId()) { + CheckCaseNineResult(notificationRequest); + } else if (CASE_TEN == notificationRequest.GetNotificationId()) { + EXPECT_EQ(NotificationConstant::SERVICE_REMINDER, notificationRequest.GetSlotType()); + } else if (CASE_ELEVEN == notificationRequest.GetNotificationId()) { + EXPECT_EQ(NotificationConstant::SOCIAL_COMMUNICATION, notificationRequest.GetSlotType()); + } else if (CASE_TWELVE == notificationRequest.GetNotificationId()) { + EXPECT_EQ(NotificationConstant::CUSTOM, notificationRequest.GetSlotType()); + } else if (CASE_THIRTEEN == notificationRequest.GetNotificationId()) { + EXPECT_EQ(0, NotificationHelper::GetDisturbMode(disturbMode)); + EXPECT_EQ(NotificationConstant::ALLOW_ALARMS, disturbMode); + } else if (CASE_FOURTEEN == notificationRequest.GetNotificationId()) { + EXPECT_EQ(0, NotificationHelper::GetDisturbMode(disturbMode)); + EXPECT_EQ(NotificationConstant::ALLOW_ALL, disturbMode); + } else if (CASE_FIFTEEN == notificationRequest.GetNotificationId()) { + EXPECT_EQ(0, NotificationHelper::GetDisturbMode(disturbMode)); + EXPECT_EQ(NotificationConstant::ALLOW_NONE, disturbMode); + } else if (CASE_SIXTEEN == notificationRequest.GetNotificationId()) { + EXPECT_EQ(NotificationRequest::GroupAlertType::ALL, notificationRequest.GetGroupAlertType()); + EXPECT_EQ(true, notificationRequest.IsGroupOverview()); + } else { + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish::OnConsumed do nothing!!!!!"; + } + } + + virtual void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override + {} + +private: + void CheckCaseOneResult(NotificationRequest notificationRequest) + { + std::shared_ptr notificationContent = notificationRequest.GetContent(); + if (notificationContent != nullptr) { + EXPECT_EQ(NotificationContent::Type::MEDIA, notificationContent->GetContentType()); + std::shared_ptr notificationMediaContent = + std::static_pointer_cast(notificationContent->GetNotificationContent()); + if (notificationMediaContent != nullptr) { + EXPECT_EQ(nullptr, notificationMediaContent->GetAVToken()); + for (auto it : notificationMediaContent->GetShownActions()) { + EXPECT_EQ((uint32_t)0, it); + } + } + } + EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); + for (auto it : notificationRequest.GetNotificationUserInputHistory()) { + EXPECT_EQ("style", it); + } + EXPECT_EQ("bundleName", notificationRequest.GetOwnerBundleName()); + EXPECT_EQ("bundleName", notificationRequest.GetCreatorBundleName()); + EXPECT_EQ("ANS_Interface_MT_Publish_00100", notificationRequest.GetLabel()); + std::shared_ptr NotificationRequestPtr = notificationRequest.GetPublicNotification(); + if (NotificationRequestPtr != nullptr) { + EXPECT_EQ("ANS_Interface_MT_Publish_00100_REQUEST", NotificationRequestPtr->GetLabel()); + } + EXPECT_EQ(nullptr, notificationRequest.GetBigIcon()); + EXPECT_EQ(nullptr, notificationRequest.GetLittleIcon()); + EXPECT_EQ(nullptr, notificationRequest.GetLittleIcon()); + std::vector> messageUser = notificationRequest.GetMessageUsers(); + for (auto it : messageUser) { + if (it != nullptr) { + EXPECT_EQ("ANS_Interface_MT_Publish_00100_Message_User", it->GetName()); + EXPECT_EQ("key", it->GetKey()); + EXPECT_EQ(nullptr, it->GetPixelMap()); + EXPECT_EQ(Uri("."), it->GetUri()); + EXPECT_EQ(false, it->IsMachine()); + EXPECT_EQ(false, it->IsUserImportant()); + } + } + } + + void CheckCaseTwoResult(NotificationRequest notificationRequest) + { + EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); + std::vector> actionButtons = notificationRequest.GetActionButtons(); + for (auto actionButton : actionButtons) { + std::vector> userInputs = actionButton->GetUserInputs(); + for (auto userInput : userInputs) { + EXPECT_EQ(NotificationConstant::FREE_FORM_INPUT, userInput->GetInputsSource(g_want)); + EXPECT_EQ(nullptr, userInput->GetInputsFromWant(g_want)); + std::map> map = userInput->GetMimeInputsFromWant(g_want, ""); + EXPECT_EQ(unsigned(0), map.size()); + EXPECT_EQ("inputKey", userInput->GetInputKey()); + EXPECT_NE(nullptr, userInput->GetAdditionalData()); + EXPECT_EQ(NotificationConstant::InputEditType::EDIT_DISABLED, userInput->GetEditType()); + for (auto option : userInput->GetOptions()) { + EXPECT_EQ("", option); + } + for (auto type : userInput->GetPermitMimeTypes()) { + EXPECT_EQ("mimeType", type); + } + EXPECT_EQ(false, userInput->IsMimeTypeOnly()); + EXPECT_EQ("tag", userInput->GetTag()); + EXPECT_EQ(false, userInput->IsPermitFreeFormInput()); + } + } + } + + void CheckCaseThreeResult(NotificationRequest notificationRequest) + { + EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); + std::vector> actionButtons = notificationRequest.GetActionButtons(); + for (auto actionButton : actionButtons) { + EXPECT_EQ(nullptr, actionButton->GetIcon()); + EXPECT_EQ("title", actionButton->GetTitle()); + EXPECT_EQ(nullptr, actionButton->GetWantAgent()); + EXPECT_NE(nullptr, actionButton->GetAdditionalData()); + EXPECT_EQ(NotificationConstant::NONE_ACTION_BUTTON, actionButton->GetSemanticActionButton()); + for (auto userInputs : actionButton->GetMimeTypeOnlyUserInputs()) { + EXPECT_EQ("onlyUserInputKey", userInputs->GetInputKey()); + } + EXPECT_EQ(true, actionButton->IsAutoCreatedReplies()); + EXPECT_EQ(true, actionButton->IsContextDependent()); + } + } + + void CheckCaseFourResult(NotificationRequest notificationRequest) + { + std::shared_ptr notificationContent = notificationRequest.GetContent(); + if (notificationContent != nullptr) { + EXPECT_EQ(NotificationContent::Type::CONVERSATION, notificationContent->GetContentType()); + std::shared_ptr notificationConversationContent = + std::static_pointer_cast( + notificationContent->GetNotificationContent()); + if (notificationConversationContent != nullptr) { + EXPECT_EQ("ConversationTitle", notificationConversationContent->GetConversationTitle()); + EXPECT_EQ(false, notificationConversationContent->IsConversationGroup()); + std::vector> messagesPtr = + notificationConversationContent->GetAllConversationalMessages(); + EXPECT_EQ(unsigned(CASE_TWO), messagesPtr.size()); + MessageUser user = notificationConversationContent->GetMessageUser(); + EXPECT_EQ("key", user.GetKey()); + EXPECT_EQ("Name", user.GetName()); + EXPECT_EQ(nullptr, user.GetPixelMap()); + EXPECT_EQ(Uri("."), user.GetUri()); + EXPECT_EQ(false, user.IsUserImportant()); + EXPECT_EQ(false, user.IsMachine()); + } + } + EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); + } + + void CheckCaseFiveResult(NotificationRequest notificationRequest) + { + std::shared_ptr notificationContent = notificationRequest.GetContent(); + if (notificationContent != nullptr) { + EXPECT_EQ(NotificationContent::Type::MULTILINE, notificationContent->GetContentType()); + std::shared_ptr notificationMultineContent = + std::static_pointer_cast(notificationContent->GetNotificationContent()); + if (notificationMultineContent != nullptr) { + EXPECT_EQ("expandedtitle", notificationMultineContent->GetExpandedTitle()); + EXPECT_EQ("brieftext", notificationMultineContent->GetBriefText()); + for (auto allLine : notificationMultineContent->GetAllLines()) { + EXPECT_EQ("singleLine", allLine); + } + } + } + EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); + } + + void CheckCaseSixResult(NotificationRequest notificationRequest) + { + std::shared_ptr notificationContent = notificationRequest.GetContent(); + if (notificationContent != nullptr) { + EXPECT_EQ(NotificationContent::Type::PICTURE, notificationContent->GetContentType()); + std::shared_ptr notificationPictureContent = + std::static_pointer_cast(notificationContent->GetNotificationContent()); + if (notificationPictureContent != nullptr) { + EXPECT_EQ("expendedtitle", notificationPictureContent->GetExpandedTitle()); + EXPECT_EQ("brieftext", notificationPictureContent->GetBriefText()); + EXPECT_EQ(nullptr, notificationPictureContent->GetBigPicture()); + } + } + EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); + } + + void CheckCaseSevenResult(NotificationRequest notificationRequest) + { + std::shared_ptr notificationContent = notificationRequest.GetContent(); + if (notificationContent != nullptr) { + EXPECT_EQ(NotificationContent::Type::LONG_TEXT, notificationContent->GetContentType()); + std::shared_ptr notificationLongContent = + std::static_pointer_cast(notificationContent->GetNotificationContent()); + if (notificationLongContent != nullptr) { + EXPECT_EQ("expendedtitle", notificationLongContent->GetExpandedTitle()); + EXPECT_EQ("brieftext", notificationLongContent->GetBriefText()); + EXPECT_EQ("longtext", notificationLongContent->GetLongText()); + } + } + EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); + } + + void CheckCaseEightResult(NotificationRequest notificationRequest) + { + EXPECT_EQ(NotificationConstant::CONTENT_INFORMATION, notificationRequest.GetSlotType()); + EXPECT_EQ(false, notificationRequest.IsInProgress()); + EXPECT_EQ(false, notificationRequest.IsUnremovable()); + EXPECT_EQ(0, notificationRequest.GetBadgeNumber()); + EXPECT_EQ(0, notificationRequest.GetDeliveryTime()); + EXPECT_EQ(false, notificationRequest.IsShowDeliveryTime()); + EXPECT_EQ(false, notificationRequest.IsPermitSystemGeneratedContextualActionButtons()); + EXPECT_EQ(false, notificationRequest.IsAlertOneTime()); + EXPECT_EQ(0, notificationRequest.GetAutoDeletedTime()); + EXPECT_EQ("classification", notificationRequest.GetClassification()); + EXPECT_EQ(0, notificationRequest.GetColor()); + } + + void CheckCaseNineResult(NotificationRequest notificationRequest) + { + EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); + EXPECT_EQ(false, notificationRequest.IsColorEnabled()); + EXPECT_EQ(false, notificationRequest.IsCountdownTimer()); + EXPECT_EQ("groupvalue", notificationRequest.GetGroupValue()); + EXPECT_EQ(true, notificationRequest.IsOnlyLocal()); + EXPECT_EQ("setting text", notificationRequest.GetSettingsText()); + EXPECT_EQ(false, notificationRequest.IsShowStopwatch()); + EXPECT_EQ("sortingkey", notificationRequest.GetSortingKey()); + EXPECT_EQ("statusbartext", notificationRequest.GetStatusBarText()); + EXPECT_EQ(false, notificationRequest.IsTapDismissed()); + auto visibleness = notificationRequest.GetVisibleness(); + EXPECT_EQ((int)NotificationConstant::VisiblenessType::PUBLIC, (int)visibleness); + EXPECT_EQ(NotificationRequest::BadgeStyle::NONE, notificationRequest.GetBadgeIconStyle()); + EXPECT_EQ("shortcutid", notificationRequest.GetShortcutId()); + EXPECT_EQ(false, notificationRequest.IsFloatingIcon()); + EXPECT_EQ(0, notificationRequest.GetProgressMax()); + EXPECT_EQ(0, notificationRequest.GetProgressValue()); + EXPECT_EQ(false, notificationRequest.IsProgressIndeterminate()); + } +}; + +class CompletedCallbackTest : public WantAgent::CompletedCallback { + void OnSendFinished( + const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) + { + g_send_finished_mtx.unlock(); + OnWantReceived = true; + } +}; + +class AnsInterfaceModulePublishTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + void WaitOnSubscribeResult(); + void WaitOnConsumed(); + void WaitOnUnsubscribeResult(); +}; + +void AnsInterfaceModulePublishTest::SetUpTestCase() +{ + sptr service = OHOS::Notification::AdvancedNotificationService::GetInstance(); + OHOS::ISystemAbilityManager::SAExtraProp saExtraProp; + systemAbilityManager->AddSystemAbility(OHOS::ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, service, saExtraProp); + IPCSkeleton::SetCallingUid(CALLING_UID); +} + +void AnsInterfaceModulePublishTest::TearDownTestCase() +{} + +void AnsInterfaceModulePublishTest::SetUp() +{} + +void AnsInterfaceModulePublishTest::TearDown() +{ + OnConsumedReceived = false; + g_subscribe_mtx.unlock(); + g_consumed_mtx.unlock(); + g_unsubscribe_mtx.unlock(); +} + +void AnsInterfaceModulePublishTest::WaitOnSubscribeResult() +{ + struct tm subscribeTime = {0}; + EXPECT_EQ(OHOS::GetSystemCurrentTime(&subscribeTime), true); + struct tm subscribeDoingTime = {0}; + EXPECT_EQ(OHOS::GetSystemCurrentTime(&subscribeDoingTime), true); + int64_t subscribeSeconds = 0; + while (!g_subscribe_mtx.try_lock()) { + EXPECT_EQ(OHOS::GetSystemCurrentTime(&subscribeDoingTime), true); + subscribeSeconds = OHOS::GetSecondsBetween(subscribeTime, subscribeDoingTime); + if (subscribeSeconds >= TIME_OUT_SECONDS_LIMIT) { + GTEST_LOG_(INFO) << "g_subscribe_mtx.try_lock overtime"; + break; + } + } +} + +void AnsInterfaceModulePublishTest::WaitOnConsumed() +{ + struct tm publishTime = {0}; + EXPECT_EQ(OHOS::GetSystemCurrentTime(&publishTime), true); + struct tm publishDoingTime = {0}; + EXPECT_EQ(OHOS::GetSystemCurrentTime(&publishDoingTime), true); + int64_t publishSeconds = 0; + while (!g_consumed_mtx.try_lock()) { + EXPECT_EQ(OHOS::GetSystemCurrentTime(&publishDoingTime), true); + publishSeconds = OHOS::GetSecondsBetween(publishTime, publishDoingTime); + if (publishSeconds >= TIME_OUT_SECONDS_LIMIT) { + GTEST_LOG_(INFO) << "g_consumed_mtx.try_lock overtime"; + break; + } + } + EXPECT_EQ(OnConsumedReceived, true); +} + +void AnsInterfaceModulePublishTest::WaitOnUnsubscribeResult() +{ + struct tm unsubscribeTime = {0}; + EXPECT_EQ(OHOS::GetSystemCurrentTime(&unsubscribeTime), true); + struct tm unsubscribeDoingTime = {0}; + EXPECT_EQ(OHOS::GetSystemCurrentTime(&unsubscribeDoingTime), true); + int64_t unSubscribeseconds = 0; + while (!g_unsubscribe_mtx.try_lock()) { + EXPECT_EQ(OHOS::GetSystemCurrentTime(&unsubscribeTime), true); + unSubscribeseconds = OHOS::GetSecondsBetween(unsubscribeTime, unsubscribeDoingTime); + if (unSubscribeseconds >= TIME_OUT_SECONDS_LIMIT) { + GTEST_LOG_(INFO) << "Ag_unsubscribe_mtx.try_lock overtime"; + break; + } + } +} + +/** + * @tc.number : ANS_Interface_MT_Publish_00100 + * @tc.name : Publish_00100 + * @tc.desc : Add notification slot(type is OTHER), make a subscriber and publish a media notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a media notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00100, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00100::SubscribeInfo:" << info.Dump(); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + WaitOnSubscribeResult(); + std::shared_ptr mediaContent = std::make_shared(); + mediaContent->SetAVToken(nullptr); + std::vector actions; + actions.push_back(0); + mediaContent->SetShownActions(actions); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00100::mediaContent:" << mediaContent->Dump(); + std::shared_ptr content = std::make_shared(mediaContent); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00100::Content:" << content->Dump(); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::OTHER); + req.SetNotificationId(CASE_ONE); + std::vector style; + style.push_back("style"); + req.SetNotificationUserInputHistory(style); + req.SetOwnerBundleName("ownerbundlename"); + req.SetCreatorBundleName("creatorbundlename"); + req.SetLabel("ANS_Interface_MT_Publish_00100"); + std::shared_ptr requestPtr = std::make_shared(); + requestPtr->SetLabel("ANS_Interface_MT_Publish_00100_REQUEST"); + req.SetPublicNotification(requestPtr); + req.SetBigIcon(nullptr); + req.SetLittleIcon(nullptr); + std::shared_ptr messageUserPtr = std::make_shared(); + messageUserPtr->SetName("ANS_Interface_MT_Publish_00100_Message_User"); + messageUserPtr->SetKey("key"); + messageUserPtr->SetPixelMap(nullptr); + messageUserPtr->SetUri(Uri(".")); + messageUserPtr->SetMachine(false); + messageUserPtr->SetUserAsImportant(false); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00100::messageUser is::" << messageUserPtr->Dump(); + req.AddMessageUser(messageUserPtr); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00100::messageUser is::" << req.Dump(); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_00200 + * @tc.name : Publish_00200 + * @tc.desc : Add notification slot(type is OTHER), make a subscriber and publish a local notification with input + * box. + * @tc.expected : Add notification slot success, make a subscriber and publish a local notification with input box + * success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00200, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + WaitOnSubscribeResult(); + std::shared_ptr mediaContent = std::make_shared(); + std::shared_ptr content = std::make_shared(mediaContent); + WantAgent::WantAgentInfo paramsInfo; + std::shared_ptr wantAgent = WantAgent::WantAgentHelper::GetWantAgent(paramsInfo); + std::shared_ptr actionButton = + NotificationActionButton::Create(nullptr, "title", wantAgent); + std::shared_ptr userInput = NotificationUserInput::Create("inputKey"); + std::vector> userInputs; + AppExecFwk::PacMap pacMap; + std::map> results; + std::vector options; + std::set permitMimeTypes; + std::shared_ptr pacMapPtr; + userInput->SetInputsSource(g_want, NotificationConstant::FREE_FORM_INPUT); + userInput->AddInputsToWant(userInputs, g_want, pacMap); + std::shared_ptr userInputMine = NotificationUserInput::Create( + "Key", "tag", options, false, permitMimeTypes, pacMapPtr, NotificationConstant::EDIT_AUTO); + userInput->AddMimeInputToWant(*userInputMine, g_want, results); + userInput->AddAdditionalData(pacMap); + userInput->SetEditType(NotificationConstant::EDIT_DISABLED); + userInput->SetOptions(options); + userInput->SetPermitMimeTypes("mimeType", false); + userInput->SetTag("tag"); + userInput->SetPermitFreeFormInput(false); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00200::userInput is::" << userInput->Dump(); + actionButton->AddNotificationUserInput(userInput); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::OTHER); + req.AddActionButton(actionButton); + req.SetNotificationId(CASE_TWO); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_00300 + * @tc.name : Publish_00300 + * @tc.desc : Add notification slot(type is OTHER), make a subscriber and publish a local notification with + * ActionButton. + * @tc.expected : Add notification slot success, make a subscriber and publish a local notification with ActionButton + * success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00300, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + WaitOnSubscribeResult(); + std::shared_ptr mediaContent = std::make_shared(); + std::shared_ptr content = std::make_shared(mediaContent); + WantAgent::WantAgentInfo paramsInfo; + std::shared_ptr wantAgent = WantAgent::WantAgentHelper::GetWantAgent(paramsInfo); + if (nullptr == wantAgent) { + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00300::wantAgent is nullptr"; + } + std::shared_ptr actionButton = + NotificationActionButton::Create(nullptr, "title", wantAgent); + std::shared_ptr onlyUserInput = NotificationUserInput::Create("onlyUserInputKey"); + AppExecFwk::PacMap pacMap; + actionButton->AddAdditionalData(pacMap); + actionButton->SetSemanticActionButton(NotificationConstant::NONE_ACTION_BUTTON); + actionButton->SetAutoCreatedReplies(true); + actionButton->AddMimeTypeOnlyUserInput(onlyUserInput); + actionButton->SetContextDependent(true); + GTEST_LOG_(INFO) << actionButton->Dump(); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::OTHER); + req.AddActionButton(actionButton); + req.SetNotificationId(CASE_THREE); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_00400 + * @tc.name : Publish_00400 + * @tc.desc : Add notification slot(type is OTHER), make a subscriber and publish a local conversation + * notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local conversation notification + * success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00400, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + WaitOnSubscribeResult(); + MessageUser messageUser, sender; + messageUser.SetKey("key"); + messageUser.SetName("Name"); + messageUser.SetPixelMap(nullptr); + messageUser.SetUri(Uri(".")); + messageUser.SetUserAsImportant(false); + messageUser.SetMachine(false); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00400::messgaeUser is::" << messageUser.Dump(); + std::shared_ptr conversationContent = + std::make_shared(messageUser); + conversationContent->SetConversationTitle("ConversationTitle"); + conversationContent->SetConversationGroup(false); + conversationContent->AddConversationalMessage("text", 0, sender); + std::shared_ptr messagePtr = + std::make_shared("messageptr", 0, sender); + conversationContent->AddConversationalMessage(messagePtr); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00400::conversationContent is::" << conversationContent->Dump(); + std::shared_ptr content = std::make_shared(conversationContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::OTHER); + req.SetNotificationId(CASE_FOUR); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_00500 + * @tc.name : Publish_00500 + * @tc.desc : Add notification slot(type is OTHER), make a subscriber and publish a local multiline notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local multiline notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00500, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + WaitOnSubscribeResult(); + MessageUser messageUser; + std::shared_ptr multiLineContent = std::make_shared(); + multiLineContent->SetExpandedTitle("expandedtitle"); + multiLineContent->SetBriefText("brieftext"); + multiLineContent->AddSingleLine("singleLine"); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00500::multiLineContent::" << multiLineContent->Dump(); + std::shared_ptr content = std::make_shared(multiLineContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::OTHER); + req.SetNotificationId(CASE_FIVE); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_00600 + * @tc.name : Publish_00600 + * @tc.desc : Add notification slot(type is OTHER), make a subscriber and publish a local picture notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local picture notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00600, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + WaitOnSubscribeResult(); + MessageUser messageUser; + std::shared_ptr pictureContent = std::make_shared(); + pictureContent->SetExpandedTitle("expendedtitle"); + pictureContent->SetBriefText("brieftext"); + pictureContent->SetBigPicture(nullptr); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00600::pictureContent is::" << pictureContent->Dump(); + std::shared_ptr content = std::make_shared(pictureContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::OTHER); + req.SetNotificationId(CASE_SIX); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_00700 + * @tc.name : Publish_00700 + * @tc.desc : Add notification slot(type is OTHER), make a subscriber and publish a local long text notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local long text notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00700, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + WaitOnSubscribeResult(); + MessageUser messageUser; + std::shared_ptr longTextContent = + std::make_shared("longtext"); + longTextContent->SetExpandedTitle("expendedtitle"); + longTextContent->SetBriefText("brieftext"); + longTextContent->SetLongText("longtext"); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00700::longTextContentis::" << longTextContent->Dump(); + std::shared_ptr content = std::make_shared(longTextContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::OTHER); + req.SetNotificationId(CASE_SEVEN); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_00800 + * @tc.name : Publish_00800 + * @tc.desc : Add notification slot(type is CONTENT_INFORMATION), make a subscriber and publish a local normal + * notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local normal notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00800, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::CONTENT_INFORMATION); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + WaitOnSubscribeResult(); + MessageUser messageUser; + std::shared_ptr normalContent = std::make_shared(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00800::normalContentis::" << normalContent->Dump(); + std::shared_ptr content = std::make_shared(normalContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::CONTENT_INFORMATION); + req.SetNotificationId(CASE_EIGHT); + req.SetInProgress(false); + req.SetUnremovable(false); + req.SetBadgeNumber(0); + req.SetDeliveryTime(0); + req.SetShowDeliveryTime(false); + req.SetPermitSystemGeneratedContextualActionButtons(false); + req.SetAlertOneTime(false); + req.SetAutoDeletedTime(0); + req.SetClassification("classification"); + req.SetColor(0); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_00900 + * @tc.name : Publish_00900 + * @tc.desc : Add notification slot(type is OTHER), make a subscriber and publish a local normal + * notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local normal notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00900, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + WaitOnSubscribeResult(); + MessageUser messageUser; + std::shared_ptr normalContent = std::make_shared(); + std::shared_ptr content = std::make_shared(normalContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::OTHER); + req.SetNotificationId(CASE_NINE); + req.SetColorEnabled(false); + req.SetCountdownTimer(false); + req.SetGroupValue("groupvalue"); + req.SetOnlyLocal(true); + req.SetSettingsText("setting text"); + req.SetShowStopwatch(false); + req.SetSortingKey("sortingkey"); + req.SetStatusBarText("statusbartext"); + req.SetTapDismissed(false); + req.SetVisibleness(NotificationConstant::VisiblenessType::PUBLIC); + req.SetBadgeIconStyle(NotificationRequest::BadgeStyle::NONE); + req.SetShortcutId("shortcutid"); + req.SetFloatingIcon(false); + req.SetProgressBar(0, 0, false); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_01000 + * @tc.name : Publish_01000 + * @tc.desc : Add notification slot(type is SERVICE_REMINDER), make a subscriber and publish a local normal + * notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local normal notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_01000, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SERVICE_REMINDER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + // Wait OnSubscribeResult + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + WaitOnSubscribeResult(); + MessageUser messageUser; + std::shared_ptr normalContent = std::make_shared(); + std::shared_ptr content = std::make_shared(normalContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::SERVICE_REMINDER); + req.SetNotificationId(CASE_TEN); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + WaitOnUnsubscribeResult(); + sleep(SLEEP_TIME); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_02000 + * @tc.name : Publish_02000 + * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a local normal + * notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local normal notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_02000, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + WaitOnSubscribeResult(); + MessageUser messageUser; + std::shared_ptr normalContent = std::make_shared(); + std::shared_ptr content = std::make_shared(normalContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); + req.SetNotificationId(CASE_ELEVEN); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_03000 + * @tc.name : Publish_03000 + * @tc.desc : Add notification slot(type is CUSTOM), make a subscriber and publish a local normal + * notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local normal notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_03000, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::CUSTOM); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + WaitOnSubscribeResult(); + MessageUser messageUser; + std::shared_ptr normalContent = std::make_shared(); + std::shared_ptr content = std::make_shared(normalContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::CUSTOM); + req.SetNotificationId(CASE_TWELVE); + GTEST_LOG_(INFO) << "request is ::" << req.Dump(); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_04000 + * @tc.name : Publish_04000 + * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a notification in + * disturbed mode (mode is ALLOW_ALARMS) + * @tc.expected : Add notification slot success, make a subscriber and a publish notification in undisturbed mode + * success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_04000, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + WaitOnSubscribeResult(); + EXPECT_EQ(0, NotificationHelper::SetDisturbMode(NotificationConstant::ALLOW_ALARMS)); + MessageUser messageUser; + std::shared_ptr normalContent = std::make_shared(); + std::shared_ptr content = std::make_shared(normalContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); + req.SetClassification(CLASSIFICATION_ALARM); + req.SetNotificationId(CASE_THIRTEEN); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_05000 + * @tc.name : Publish_05000 + * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a notification + * in disturbed mode (mode is ALLOW_ALL) + * @tc.expected : Add notification slot success, make a subscriber and pulish a notification in undisturbed mode + * success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_05000, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + WaitOnSubscribeResult(); + EXPECT_EQ(0, NotificationHelper::SetDisturbMode(NotificationConstant::ALLOW_ALL)); + MessageUser messageUser; + std::shared_ptr normalContent = std::make_shared(); + std::shared_ptr content = std::make_shared(normalContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); + req.SetNotificationId(CASE_FOURTEEN); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + // Wait OnUnsubscribeResult + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_06000 + * @tc.name : Publish_06000 + * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a notification + * in disturbed mode (mode is ALLOW_NONE) + * @tc.expected : Add notification slot success, make a subscriber and pulush a notification in undisturbed mode + * success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_06000, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); + slot.EnableBypassDnd(true); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + WaitOnSubscribeResult(); + EXPECT_EQ(0, NotificationHelper::SetDisturbMode(NotificationConstant::ALLOW_NONE)); + MessageUser messageUser; + std::shared_ptr normalContent = std::make_shared(); + std::shared_ptr content = std::make_shared(normalContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); + req.SetNotificationId(CASE_FIFTEEN); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_07000 + * @tc.name : Publish_07000 + * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a local group + * notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local group notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_07000, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); + slot.EnableBypassDnd(true); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + auto subscriber = TestAnsSubscriber(); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + WaitOnSubscribeResult(); + MessageUser messageUser; + std::shared_ptr normalContent = std::make_shared(); + std::shared_ptr content = std::make_shared(normalContent); + NotificationRequest req; + req.SetContent(content); + req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); + req.SetGroupValue("groupnotifcation"); + req.SetGroupOverview(true); + req.SetNotificationId(CASE_SIXTEEN); + req.SetGroupAlertType(NotificationRequest::GroupAlertType::ALL); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + WaitOnUnsubscribeResult(); +} + +/** + * @tc.number : ANS_FW_MT_GetActiveNotifications_00100 + * @tc.name : GetActiveNotifications_00100 + * @tc.desc : Get the active notifications and the number of active notifications of the current application. + * @tc.expected : Get the active notifications success and the number of active notifications of the current + * application is right. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_GetActiveNotifications_00100, Function | MediumTest | Level1) +{ + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + WaitOnSubscribeResult(); + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); + EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::CancelAllNotifications()); + sleep(SLEEP_TIME); + EXPECT_EQ(OnCanceledReceived, true); + int countBefor = 0; + EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countBefor)); + EXPECT_EQ(0, countBefor); + std::string label1 = "Label1"; + NotificationRequest req1(0); + req1.SetLabel(label1); + req1.SetContent(content); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); + WaitOnConsumed(); + OnConsumedReceived = false; + g_consumed_mtx.unlock(); + std::string label2 = "Label2"; + NotificationRequest req2(0); + req2.SetLabel(label2); + req2.SetContent(content); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); + WaitOnConsumed(); + int countAfter = 0; + EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countAfter)); + EXPECT_EQ(ACTIVE_NUMS, countAfter); + std::vector> requests; + EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotifications(requests)); + EXPECT_EQ("Label1", requests[0]->GetLabel()); + EXPECT_EQ("Label2", requests[1]->GetLabel()); + EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotifications()); + sleep(SLEEP_TIME); + EXPECT_EQ(OnCanceledReceived, true); + EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countAfter)); + EXPECT_EQ(0, countAfter); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + WaitOnUnsubscribeResult(); + OnCanceledReceived = false; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/ans_innerkits_module_setting_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_setting_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98a38c06f1a527c1853775734f460935c608b9c6 --- /dev/null +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_setting_test.cpp @@ -0,0 +1,139 @@ +/* + * 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 "mock_ipc_skeleton.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +static sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); +const int32_t CALLING_UID = 9998; + +class AnsInterfaceModuleSettingTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AnsInterfaceModuleSettingTest::SetUpTestCase() +{ + sptr service = OHOS::Notification::AdvancedNotificationService::GetInstance(); + OHOS::ISystemAbilityManager::SAExtraProp saExtraProp; + systemAbilityManager->AddSystemAbility(OHOS::ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, service, saExtraProp); + IPCSkeleton::SetCallingUid(CALLING_UID); +} + +void AnsInterfaceModuleSettingTest::TearDownTestCase() +{} + +void AnsInterfaceModuleSettingTest::SetUp() +{} + +void AnsInterfaceModuleSettingTest::TearDown() +{} + +/** + * @tc.number : ANS_Interface_MT_NotificationSetting_00100 + * @tc.name : NotificationSetting_00100 + * @tc.desc : Set a specified application to show badge, get the specified application can show badge. + * @tc.expected : Set a specified application to show badge success, get the specified application can show badge. + */ +HWTEST_F(AnsInterfaceModuleSettingTest, ANS_Interface_MT_NotificationSetting_00100, Function | MediumTest | Level1) +{ + NotificationBundleOption bundleOption; + bundleOption.SetBundleName("bundlename"); + bundleOption.SetUid(CALLING_UID); + GTEST_LOG_(INFO) << "BundleOption is:"< +#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 "mock_ipc_skeleton.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +static sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); +const int32_t CALLING_UID = 9998; + +class AnsInterfaceModuleSlotTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AnsInterfaceModuleSlotTest::SetUpTestCase() +{ + sptr service = OHOS::Notification::AdvancedNotificationService::GetInstance(); + OHOS::ISystemAbilityManager::SAExtraProp saExtraProp; + systemAbilityManager->AddSystemAbility(OHOS::ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, service, saExtraProp); + IPCSkeleton::SetCallingUid(CALLING_UID); +} + +void AnsInterfaceModuleSlotTest::TearDownTestCase() +{} + +void AnsInterfaceModuleSlotTest::SetUp() +{} + +void AnsInterfaceModuleSlotTest::TearDown() +{} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlot_00100 + * @tc.name : NotificationSlot_00100 + * @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(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00100, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); + slot.SetEnableLight(true); + slot.SetDescription("description"); + slot.SetLedLightColor(0); + slot.SetLevel(NotificationSlot::NotificationLevel::LEVEL_LOW); + slot.SetSlotGroup("group"); + slot.SetSound(Uri(".")); + std::vector style; + style.push_back(0); + slot.SetVibrationStyle(style); + slot.EnableBypassDnd(true); + slot.EnableBadge(true); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + + sptr spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::SOCIAL_COMMUNICATION, spSlot)); + if (spSlot == nullptr) { + GTEST_LOG_(INFO) << "get slot is empty"; + } else { + GTEST_LOG_(INFO) << "after get slot dump slot information:" << spSlot->Dump(); + EXPECT_EQ(true, spSlot->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 : NotificationSlot_00200 + * @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(AnsInterfaceModuleSlotTest, 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); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + sptr spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::SERVICE_REMINDER, spSlot)); + + if (spSlot == nullptr) { + GTEST_LOG_(INFO) << "get slot is empty"; + } else { + EXPECT_EQ(true, spSlot->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 : NotificationSlot_00300 + * @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(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00300, Function | MediumTest | Level1) +{ + 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); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + sptr spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::CONTENT_INFORMATION, spSlot)); + + if (spSlot == nullptr) { + GTEST_LOG_(INFO) << "get slot is empty"; + } else { + EXPECT_EQ(true, spSlot->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 : NotificationSlot_00400 + * @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(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00400, Function | MediumTest | Level1) +{ + 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); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + sptr spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::OTHER, spSlot)); + + if (spSlot == nullptr) { + GTEST_LOG_(INFO) << "get slot is empty"; + } else { + EXPECT_EQ(true, spSlot->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 : NotificationSlot_00500 + * @tc.desc : Add notification slot(type is OTHER), slot set description character length exceed 1000 + * characters, get notification slot and remove notification slot. + * @tc.expected : Add notification slot success, get notification slot correctly and remove notification slot success. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00500, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + slot.SetEnableLight(true); + std::string description(2000, 'c'); + slot.SetDescription(description); + slot.SetLedLightColor(0); + slot.SetLevel(NotificationSlot::NotificationLevel::LEVEL_LOW); + slot.SetSlotGroup("group"); + slot.SetSound(Uri(".")); + std::vector style; + style.push_back(0); + slot.SetVibrationStyle(style); + slot.EnableBypassDnd(true); + slot.EnableBadge(true); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + sptr spSlot; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlot(NotificationConstant::OTHER, spSlot)); + + if (spSlot == nullptr) { + GTEST_LOG_(INFO) << "get slot is empty"; + } else { + GTEST_LOG_(INFO) << "get slot is:" << spSlot->Dump(); + EXPECT_EQ(true, spSlot->CanEnableLight()); + EXPECT_EQ(true, spSlot->CanVibrate()); + std::string expecteDescription(1000, 'c'); + EXPECT_EQ(expecteDescription, 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_NotificationSlotGroup_00100 + * @tc.name : NotificationSlotGroup_00100 + * @tc.desc : Add notification slot group, get notification slot group and remove notification slot group. + * @tc.expected : Add notification slot group success, get notification slot group correctly and remove notification + * slot group success. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlotGroup_00100, Function | MediumTest | Level1) +{ + NotificationSlotGroup slotGroup("id", "name"); + slotGroup.SetDescription("description"); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlotGroup(slotGroup)); + sptr spSlotGroup; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlotGroup("id", spSlotGroup)); + + if (spSlotGroup == nullptr) { + GTEST_LOG_(INFO) << "get slot group is empty"; + } else { + GTEST_LOG_(INFO) << "get slot group is:" << spSlotGroup->Dump(); + EXPECT_EQ("description", spSlotGroup->GetDescription()); + EXPECT_EQ("id", spSlotGroup->GetId()); + EXPECT_EQ("name", spSlotGroup->GetName()); + EXPECT_EQ(false, spSlotGroup->IsDisabled()); + } + EXPECT_EQ(0, NotificationHelper::RemoveNotificationSlotGroup("id")); + EXPECT_EQ((int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST, + NotificationHelper::GetNotificationSlotGroup("id", spSlotGroup)); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlotGroup_00200 + * @tc.name : NotificationSlotGroup_00200 + * @tc.desc : Add notification slot group, slot group set description character length exceed 1000 + * characters, get notification slot group and remove notification slot group. + * @tc.expected : Add notification slot group success, get notification slot group correctly and remove notification + * slot group success. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlotGroup_00200, Function | MediumTest | Level1) +{ + NotificationSlotGroup slotGroup("id", "name"); + std::string description(2000, 'c'); + slotGroup.SetDescription(description); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlotGroup(slotGroup)); + GTEST_LOG_(INFO) << "after add group is:" << slotGroup.Dump(); + sptr spSlotGroup; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlotGroup("id", spSlotGroup)); + + if (spSlotGroup == nullptr) { + GTEST_LOG_(INFO) << "get slot group is empty"; + } else { + GTEST_LOG_(INFO) << "get slot group is:" << spSlotGroup->Dump(); + std::string expectDescription(1000, 'c'); + EXPECT_EQ(expectDescription, spSlotGroup->GetDescription()); + EXPECT_EQ("id", spSlotGroup->GetId()); + EXPECT_EQ("name", spSlotGroup->GetName()); + EXPECT_EQ(false, spSlotGroup->IsDisabled()); + } + EXPECT_EQ(0, NotificationHelper::RemoveNotificationSlotGroup("id")); + EXPECT_EQ((int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST, + NotificationHelper::GetNotificationSlotGroup("id", spSlotGroup)); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlotGroup_00300 + * @tc.name : NotificationSlotGroup_00300 + * @tc.desc : Two different slots added to the same slot group. + * @tc.expected : Add success. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlotGroup_00300, Function | MediumTest | Level1) +{ + NotificationSlot slotA(NotificationConstant::OTHER); + slotA.SetSlotGroup("id"); + + NotificationSlot slotB(NotificationConstant::CUSTOM); + slotA.SetSlotGroup("id"); + + NotificationSlotGroup slotGroup("id", "name"); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlotGroup(slotGroup)); + + sptr spSlotGroup; + EXPECT_EQ(0, NotificationHelper::GetNotificationSlotGroup("id", spSlotGroup)); + + if (spSlotGroup == nullptr) { + GTEST_LOG_(INFO) << "get slot group is empty"; + } else { + std::vector slots = spSlotGroup->GetSlots(); + for (auto it : slots) { + if (NotificationConstant::OTHER == it.GetType()) { + EXPECT_EQ("OTHER", it.GetId()); + } else if (NotificationConstant::CUSTOM == it.GetType()) { + EXPECT_EQ("CUSTOM", it.GetId()); + } else { + GTEST_LOG_(INFO) << "slot group has wrong slot"; + } + } + } + EXPECT_EQ(0, NotificationHelper::RemoveNotificationSlotGroup("id")); + EXPECT_EQ((int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST, + NotificationHelper::GetNotificationSlotGroup("id", spSlotGroup)); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/ans_mt_constant.h b/frameworks/ans/test/moduletest/ans_mt_constant.h new file mode 100644 index 0000000000000000000000000000000000000000..99d2a2796c785265f89070fdb27fa00c94273d0d --- /dev/null +++ b/frameworks/ans/test/moduletest/ans_mt_constant.h @@ -0,0 +1,41 @@ +/* + * 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_FRAMEWORKS_ANS_TEST_MODULETEST_ANS_MT_CONSTANT_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_TEST_MODULETEST_ANS_MT_CONSTANT_H + +#include + +namespace OHOS { +namespace Notification { + +namespace { +const std::string APP_NAME = "bundleName"; +const std::string NOTIFICATION_LABEL_0 = "Label0"; +const std::string NOTIFICATION_LABEL_1 = "Label1"; +const std::string NOTIFICATION_LABEL_2 = "Label2"; +const std::string AN_NOT_EXIST_KEY = "AN_NOT_EXIST_KEY"; +const std::string KEY_SPLITER = "_"; + +constexpr int UID = 1; +constexpr int CANCEL_REASON_DELETE = 2; +constexpr int APP_CANCEL_REASON_DELETE = 8; +constexpr int APP_CANCEL_ALL_REASON_DELETE = 9; +} // namespace + +} // namespace Notification +} // namespace OHOS + +#endif diff --git a/frameworks/ans/test/moduletest/mock/blob.cpp b/frameworks/ans/test/moduletest/mock/blob.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93d2c34700f2b1d15a38ad135a6299d3450168bb --- /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 0000000000000000000000000000000000000000..656932c2043bb1da4c864add54ab2edf13eae208 --- /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 960b2aa7ba3a36c6b849dbf2b88728dae7186684..de0de2d65dcb58b881bd32989fae29e85001eaa8 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_ipc_skeleton.h b/frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h new file mode 100755 index 0000000000000000000000000000000000000000..7881f108a8231f3a90fef2faa6ca2266f94e4b09 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_IPC_IPC_SKELETON_H +#define OHOS_IPC_IPC_SKELETON_H + +#include "iremote_object.h" + +namespace OHOS { +class IPCSkeleton { +public: + IPCSkeleton() = default; + ~IPCSkeleton() = default; + + // default max is 4, only if you need a customize value + static bool SetMaxWorkThreadNum(int maxThreadNum); + + // join current thread into work loop. + static void JoinWorkThread(); + + // remove current thread from work loop. + static void StopWorkThread(); + + static int GetCallingPid(); + + static int GetCallingUid(); + + static std::string GetLocalDeviceID(); + + static std::string GetCallingDeviceID(); + + static bool IsLocalCalling(); + + static IPCSkeleton &GetInstance(); + + static sptr GetContextObject(); + + static bool SetContextObject(sptr &object); + + static int FlushCommands(IRemoteObject *object); + + static std::string ResetCallingIdentity(); + + static bool SetCallingIdentity(std::string &identity); + + static void SetCallingUid(int uid); +}; +} // namespace OHOS +#endif // OHOS_IPC_IPC_SKELETON_H diff --git a/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h b/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h new file mode 100644 index 0000000000000000000000000000000000000000..8a777ea02ea632ddcbd69ebd89a4a6240a9b2a2c --- /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_ipc.cpp b/frameworks/ans/test/moduletest/mock/mock_ipc.cpp index 1acbe4a3fd7b60e0a044d5f21d3fdfa60c25f879..35f5b7b31c49f5178fb52e9d8016c9f564236807 100644 --- a/frameworks/ans/test/moduletest/mock/mock_ipc.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_ipc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,15 +13,28 @@ * limitations under the License. */ -#include "ipc_skeleton.h" +#include "mock_ipc_skeleton.h" namespace OHOS { #ifdef CONFIG_IPC_SINGLE using namespace IPC_SINGLE; #endif -pid_t IPCSkeleton::GetCallingUid() + +int uid_ = 1; + +int IPCSkeleton::GetCallingUid() +{ + return uid_; +} + +int IPCSkeleton::GetCallingPid() +{ + uid_ = 1; + return uid_; +} + +void IPCSkeleton::SetCallingUid(int uid) { - pid_t uid = 1; - return uid; + uid_ = uid; } } // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/mock_ipc_object_proxy.cpp b/frameworks/ans/test/moduletest/mock/mock_ipc_object_proxy.cpp deleted file mode 100644 index 4c184d7ebdedf02e998885a16bec6549bff2e97c..0000000000000000000000000000000000000000 --- a/frameworks/ans/test/moduletest/mock/mock_ipc_object_proxy.cpp +++ /dev/null @@ -1,369 +0,0 @@ -/* - * 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 "ipc_object_proxy.h" - -#include "dbinder_error_code.h" -#include "ipc_types.h" -#include "ipc_debug.h" -#include "ipc_thread_skeleton.h" -#include "log_tags.h" -#include "securec.h" -#include "ans_manager_interface.h" -#include "ans_manager_stub.h" -#ifndef CONFIG_IPC_SINGLE -#endif - -namespace OHOS { -#ifdef CONFIG_IPC_SINGLE -using namespace IPC_SINGLE; -#endif - -static constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_ID_IPC, "IPCObjectProxy" }; -IPCObjectProxy::IPCObjectProxy(int handle, std::u16string descriptor, int proto) - : IRemoteObject(std::move(descriptor)), handle_(handle), proto_(proto), isFinishInit_(false), isRemoteDead_(false) -{} - -IPCObjectProxy::~IPCObjectProxy() -{ - ZLOGW(LABEL, "handle = %{public}u destroyed", handle_); -} - -int32_t IPCObjectProxy::GetObjectRefCount() -{ - MessageParcel dummy, reply; - MessageOption option; - option.SetFlags(MessageOption::TF_SYNC); - if (SendRequestInner(false, SYNCHRONIZE_REFERENCE, dummy, reply, option) == ERR_NONE) { - return reply.ReadInt32(); - } - return 0; -} - -int IPCObjectProxy::Dump(int fd, const std::vector &args) -{ - MessageParcel data, reply; - MessageOption option { MessageOption::TF_SYNC }; - data.WriteFileDescriptor(fd); - data.WriteString16Vector(args); - return SendRequestInner(false, DUMP_TRANSACTION, data, reply, option); -} - -int IPCObjectProxy::SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) -{ - return SendRequestInner(false, code, data, reply, option); -} - -int IPCObjectProxy::SendLocalRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) -{ - return SendRequestInner(true, code, data, reply, option); -} - -int IPCObjectProxy::SendRequestInner(bool isLocal, uint32_t code, MessageParcel &data, MessageParcel &reply, - MessageOption &option) -{ - if (IsObjectDead()) { - return ERR_DEAD_OBJECT; - } - - IRemoteInvoker *invoker = nullptr; - if (isLocal) { - invoker = IPCThreadSkeleton::GetDefaultInvoker(); - } else { - invoker = IPCThreadSkeleton::GetRemoteInvoker(proto_); - } - if (invoker == nullptr) { - ZLOGE(LABEL, "%s: null invoker, type = %d", __func__, proto_); - return ERR_NULL_OBJECT; - } - - int status = invoker->SendRequest(handle_, code, data, reply, option); - if (status == ERR_DEAD_OBJECT) { - MarkObjectDied(); - } - Notification::AnsManagerStub ansManagerStub; - ansManagerStub.OnRemoteRequest(code,data,reply,option); - return status; -} - -std::u16string IPCObjectProxy::GetInterfaceDescriptor() -{ - std::lock_guard lockGuard(initMutex_); - if (!remoteDescriptor_.empty()) { - return remoteDescriptor_; - } - if (handle_ == 0) { - ZLOGI(LABEL, "handle == 0, do nothing"); - return std::u16string(); - } - - MessageParcel data, reply; - MessageOption option; - - uint32_t err = SendRequestInner(false, INTERFACE_TRANSACTION, data, reply, option); - if (err != ERR_NONE) { - ZLOGE(LABEL, "INTERFACE_TRANSACTION transact return error = %{public}u", err); - return std::u16string(); - } - remoteDescriptor_ = reply.ReadString16(); - - return remoteDescriptor_; -} - -std::string IPCObjectProxy::GetPidAndUidInfo() -{ - MessageParcel data, reply; - MessageOption option; - - uint32_t err = SendRequestInner(false, GET_UIDPID_INFO, data, reply, option); - if (err != ERR_NONE) { - ZLOGE(LABEL, "GetPidAndUidInfo SendRequestInner return error = %{public}u", err); - return std::string(""); - } - return reply.ReadString(); -} - -std::string IPCObjectProxy::GetDataBusName() -{ - MessageParcel data, reply; - MessageOption option; - - uint32_t err = SendRequestInner(false, GRANT_DATABUS_NAME, data, reply, option); - if (err != ERR_NONE) { - ZLOGE(LABEL, "GetDataBusName transact return error = %{public}u", err); - return std::string(""); - } - - if (reply.ReadUint32() != IRemoteObject::IF_PROT_DATABUS) { - ZLOGE(LABEL, "GetDataBusName normal binder"); - return std::string(""); - } - - return reply.ReadString(); -} - -void IPCObjectProxy::OnFirstStrongRef(const void *objectId) -{ - return WaitForInit(); -} - -void IPCObjectProxy::WaitForInit() -{ -#ifndef CONFIG_IPC_SINGLE - int type = 0; -#endif - - { - bool acquire = true; - std::lock_guard lockGuard(initMutex_); - if (IsObjectDead()) { - ZLOGI(LABEL, "check a dead proxy, init again"); - isRemoteDead_ = false; - isFinishInit_ = false; - acquire = false; - } - - // check again is this object been initialized - if (isFinishInit_) { - return; - } - IRemoteInvoker *invoker = IPCThreadSkeleton::GetDefaultInvoker(); - if (invoker != nullptr && acquire == true) { - invoker->AcquireHandle(handle_); - } -#ifndef CONFIG_IPC_SINGLE - type = UpdateProto(); -#endif - isFinishInit_ = true; - } -#ifndef CONFIG_IPC_SINGLE - if (type == IRemoteObject::IF_PROT_DATABUS) { - IncRefToRemote(); - } -#endif -} - -void IPCObjectProxy::OnLastStrongRef(const void *objectId) -{ -} - - -/* mutex_ should be called before set or get isRemoteDead_ status */ -void IPCObjectProxy::MarkObjectDied() -{ - isRemoteDead_ = true; -} - -bool IPCObjectProxy::IsObjectDead() const -{ - return isRemoteDead_; -} - -bool IPCObjectProxy::AddDeathRecipient(const sptr &recipient) -{ - return true; -} - -bool IPCObjectProxy::RemoveDeathRecipient(const sptr &recipient) -{ - return true; -} - -void IPCObjectProxy::SendObituary() -{ -} - -int IPCObjectProxy::GetProto() const -{ - return proto_; -} - -int32_t IPCObjectProxy::NoticeServiceDie() -{ - MessageParcel data; - MessageParcel reply; - MessageOption option(MessageOption::TF_SYNC); - data.WriteInt32(IRemoteObject::DeathRecipient::NOTICE_DEATH_RECIPIENT); - - int status = SendLocalRequest(DBINDER_OBITUARY_TRANSACTION, data, reply, option); - if (status != ERR_NONE || reply.ReadInt32() != ERR_NONE) { - ZLOGE(LABEL, "%s: send local request fail, status = %d", __func__, status); - return IPC_PROXY_TRANSACTION_ERR; - } - - return ERR_NONE; -} - -int IPCObjectProxy::InvokeListenThread(MessageParcel &data, MessageParcel &reply) -{ - MessageOption option; - return SendRequestInner(false, INVOKE_LISTEN_THREAD, data, reply, option); -} - -#ifndef CONFIG_IPC_SINGLE -int IPCObjectProxy::UpdateProto() -{ - int type = GetSessionFromDBinderService(); - SetProto(type); - return type; -} - -void IPCObjectProxy::IncRefToRemote() -{ - MessageParcel data, reply; - MessageOption option; - - int32_t err = SendRequestInner(false, DBINDER_INCREFS_TRANSACTION, data, reply, option); - if (err != ERR_NONE) { - ZLOGE(LABEL, "DBINDER_INCREFS_TRANSACTION transact return error = %{public}d", err); - // do nothing - } -} - - -void IPCObjectProxy::ReleaseProto() -{ - switch (GetProto()) { - case IRemoteObject::IF_PROT_BINDER: { - ZLOGW(LABEL, "it is normal binder, try to delete handle to index"); - ReleaseBinderProto(); - break; - } - case IRemoteObject::IF_PROT_DATABUS: { - ReleaseDatabusProto(); - break; - } - default: { - ZLOGE(LABEL, "ReleaseProto Invalid Type"); - break; - } - } - - return; -} - -void IPCObjectProxy::SetProto(int proto) -{ - proto_ = proto; -} - -int IPCObjectProxy::GetSessionFromDBinderService() -{ - MessageParcel data, reply; - MessageOption option; - uint32_t type = IRemoteObject::IF_PROT_BINDER; - - if (CheckHaveSession(type)) { - ZLOGE(LABEL, "GetSessionFromDBinderService type = %u", type); - return type; - } - - uint32_t err = SendRequestInner(true, GET_PROTO_INFO, data, reply, option); - if (err != ERR_NONE) { - ZLOGI(LABEL, "GET_PROTO_INFO transact return error = %{public}u", err); - return IRemoteObject::IF_PROT_BINDER; - } - - switch (reply.ReadUint32()) { - case IRemoteObject::IF_PROT_BINDER: { - ZLOGW(LABEL, "it is normal binder, not dbinder"); - break; - } - case IRemoteObject::IF_PROT_DATABUS: { - if (UpdateDatabusClientSession(handle_, reply)) { - ZLOGW(LABEL, "it is dbinder, not binder"); - return IRemoteObject::IF_PROT_DATABUS; - } - break; - } - default: { - ZLOGE(LABEL, "GetSessionFromDBinderService Invalid Type"); - break; - } - } - - return IRemoteObject::IF_PROT_BINDER; -} - -bool IPCObjectProxy::AddDbinderDeathRecipient() -{ - return true; -} - -bool IPCObjectProxy::RemoveDbinderDeathRecipient() -{ - return true; -} - -bool IPCObjectProxy::CheckHaveSession(uint32_t &type) -{ - return true; -} - -bool IPCObjectProxy::UpdateDatabusClientSession(int handle, MessageParcel &reply) -{ - return true; -} - -void IPCObjectProxy::ReleaseDatabusProto() -{ - return; -} - -void IPCObjectProxy::ReleaseBinderProto() -{ -} -#endif -} // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp b/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp index 0e4751f1ccf8fd8400b60f7099fc2b3ed9040a95..26b6304c7930522d66ea3a2c6e8fefefb1826ce4 100644 --- a/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 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 0000000000000000000000000000000000000000..4b580d297471fb6658f861e020621e89b8cb9382 --- /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/src/pending_want.cpp b/frameworks/wantagent/src/pending_want.cpp index a65cc57b9de86790c441d9f526c5199801eb1d5c..d5d86db34149ebe610de1c79b72029a9fab72c7c 100644 --- a/frameworks/wantagent/src/pending_want.cpp +++ b/frameworks/wantagent/src/pending_want.cpp @@ -398,8 +398,7 @@ PendingWant *PendingWant::Unmarshalling(Parcel &parcel) PendingWant *pendingWant = new (std::nothrow) PendingWant(); if (pendingWant == nullptr) { WANT_AGENT_LOGE("read from parcel failed"); - delete pendingWant; - pendingWant = nullptr; + return nullptr; } sptr target = iface_cast(parcel.ReadParcelable()); if (target == nullptr) { diff --git a/frameworks/wantagent/src/trigger_info.cpp b/frameworks/wantagent/src/trigger_info.cpp index 1e5763b3468a1a89f109206417c7f49f03e9273b..aec2c92a9cf7712d49c908ea71b8a613f4d15126 100644 --- a/frameworks/wantagent/src/trigger_info.cpp +++ b/frameworks/wantagent/src/trigger_info.cpp @@ -46,6 +46,20 @@ TriggerInfo::TriggerInfo(const TriggerInfo ¶mInfo) resultCode_ = paramInfo.GetResultCode(); } +const TriggerInfo &TriggerInfo::operator=(const TriggerInfo ¶mInfo) +{ + permission_ = paramInfo.GetPermission(); + if (paramInfo.GetExtraInfo() != nullptr) { + extraInfo_ = std::make_shared(*paramInfo.GetExtraInfo()); + } + if (paramInfo.GetWant() != nullptr) { + want_ = std::make_shared(*paramInfo.GetWant()); + } + resultCode_ = paramInfo.GetResultCode(); + + return *this; +} + std::string TriggerInfo::GetPermission() const { return permission_; diff --git a/frameworks/wantagent/src/want_agent.cpp b/frameworks/wantagent/src/want_agent.cpp index 0cf03073a230d0f124b13714c8b7f0849f432778..d0d529d45b94e083ebd061e8b8a7be9ca6da92f1 100644 --- a/frameworks/wantagent/src/want_agent.cpp +++ b/frameworks/wantagent/src/want_agent.cpp @@ -47,8 +47,7 @@ WantAgent *WantAgent::Unmarshalling(Parcel &parcel) WantAgent *agent = new (std::nothrow) WantAgent(); if (agent == nullptr) { WANT_AGENT_LOGE("read from parcel failed"); - delete agent; - agent = nullptr; + return nullptr; } std::shared_ptr pendingWant(parcel.ReadParcelable()); agent->SetPendingWant(pendingWant); diff --git a/frameworks/wantagent/src/want_agent_helper.cpp b/frameworks/wantagent/src/want_agent_helper.cpp index 3c59c41a82035aeafac069077f376163083f7b69..5b3c49c1ba755a35394003c0e1e74be14e4ce8b3 100644 --- a/frameworks/wantagent/src/want_agent_helper.cpp +++ b/frameworks/wantagent/src/want_agent_helper.cpp @@ -138,7 +138,7 @@ std::shared_ptr WantAgentHelper::GetWantAgent(const WantAgentInfo &pa WantsInfo wantsInfo; wantsInfo.want = *want; - wantsInfo.resolvedTypes = want != nullptr ? want->GetType() : ""; + wantsInfo.resolvedTypes = want->GetType(); if (paramsInfo.GetExtraInfo() != nullptr) { wantsInfo.want.SetParams(*paramsInfo.GetExtraInfo()); } diff --git a/frameworks/wantagent/src/want_agent_info.cpp b/frameworks/wantagent/src/want_agent_info.cpp index 4d66a12aeedeefacbc46d462260d042cdb1d4266..b0fe01159843af11f910fdc83143b09d2cab2497 100644 --- a/frameworks/wantagent/src/want_agent_info.cpp +++ b/frameworks/wantagent/src/want_agent_info.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/frameworks/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp b/frameworks/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp index 2dfb828e125034321dabc2168ba86d4fb14ab94c..3c6c28bba9b2fb04d07748e4315f0222c41e3545 100644 --- a/frameworks/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp +++ b/frameworks/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp @@ -27,6 +27,7 @@ #include "want.h" #include "want_params.h" #include "want_receiver_stub.h" +#include "ohos/aafwk/base/bool_wrapper.h" using namespace testing::ext; using namespace OHOS::AAFwk; @@ -53,12 +54,12 @@ public: * Called when a Send operation as completed. * * @param want The original Want that was sent. - * @param resultCode_ The final result code determined by the Send. + * @param resultCode The final result code determined by the Send. * @param resultData The final data collected by a broadcast. * @param resultExtras The final extras collected by a broadcast. */ public: - void OnSendFinished(const AAFwk::Want &want, int resultCode_, const std::string &resultData, + void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) override; static int code; }; @@ -67,7 +68,7 @@ public: int CompletedDispatcherTest::CompletedCallbackSon::code = 0; void CompletedDispatcherTest::CompletedCallbackSon::OnSendFinished( - const AAFwk::Want &want, int resultCode_, const std::string &resultData, const AAFwk::WantParams &resultExtras) + const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) { code = 100; } 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 1fd7b5c73c3f636ecfdaea267f5338c2bc46c205..b4346f66894a4e2ebfa868f6eafeed2f614878dd 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 @@ -39,6 +39,16 @@ #include "want_agent_helper.h" #include "want_sender_info.h" #include "want_sender_stub.h" +#include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/bool_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" +#include "ohos/aafwk/base/byte_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" +#include "ohos/aafwk/base/int_wrapper.h" +#include "ohos/aafwk/base/long_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/string_wrapper.h" using namespace testing::ext; using namespace OHOS::AAFwk; @@ -62,21 +72,6 @@ public: static int callBackCancelListenerConnt; - class CompletedCallbackSon : public CompletedCallback { - /** - * Called when a Send operation as completed. - * - * @param want The original Want that was sent. - * @param resultCode The final result code determined by the Send. - * @param resultData The final data collected by a broadcast. - * @param resultExtras The final extras collected by a broadcast. - */ - public: - void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, - const AAFwk::WantParams &resultExtras) override; - static int code; - }; - class WantSender : public AAFwk::WantSenderStub { public: virtual void Send(SenderInfo &senderInfo) override; @@ -88,15 +83,8 @@ public: }; }; -int PendingWantTest::CompletedCallbackSon::code = 0; int PendingWantTest::callBackCancelListenerConnt = 0; -void PendingWantTest::CompletedCallbackSon::OnSendFinished( - const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) -{ - code = 100; -} - void PendingWantTest::WantSender::Send(SenderInfo &senderInfo) {} @@ -145,7 +133,7 @@ HWTEST_F(PendingWantTest, PendingWant_0100, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_0200, Function | MediumTest | Level1) { - sptr target(new (std::nothrow) WantSender()); + sptr target(new (std::nothrow) WantSender()); PendingWant pendingWant(target); EXPECT_EQ(pendingWant.target_, target); EXPECT_EQ(pendingWant.cancelReceiver_, nullptr); @@ -159,7 +147,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); @@ -176,7 +164,7 @@ HWTEST_F(PendingWantTest, PendingWant_0400, Function | MediumTest | Level1) std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetAbility(nullptr, requestCode, want, flags); EXPECT_EQ(pendingWant, nullptr); @@ -194,7 +182,7 @@ HWTEST_F(PendingWantTest, PendingWant_0500, Function | MediumTest | Level1) std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetAbility(context, requestCode, want, flags); EXPECT_NE(pendingWant, nullptr); @@ -216,7 +204,7 @@ HWTEST_F(PendingWantTest, PendingWant_0600, Function | MediumTest | Level1) std::string key = "key"; std::shared_ptr wParams = std::make_shared(); wParams->SetParam(key, Boolean::Box(value)); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetAbility(context, requestCode, want, flags, wParams); EXPECT_NE(pendingWant, nullptr); @@ -239,7 +227,7 @@ HWTEST_F(PendingWantTest, PendingWant_0700, Function | MediumTest | Level1) std::vector> wants; wants.emplace_back(want); wants.emplace_back(want2); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetAbilities(nullptr, requestCode, wants, flags); EXPECT_EQ(pendingWant, nullptr); @@ -263,7 +251,7 @@ HWTEST_F(PendingWantTest, PendingWant_0800, Function | MediumTest | Level1) std::vector> wants; wants.emplace_back(want); wants.emplace_back(want2); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetAbilities(context, requestCode, wants, flags); EXPECT_NE(pendingWant, nullptr); @@ -291,7 +279,7 @@ HWTEST_F(PendingWantTest, PendingWant_0900, Function | MediumTest | Level1) std::string key = "key"; std::shared_ptr wParams = std::make_shared(); wParams->SetParam(key, Boolean::Box(value)); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetAbilities(context, requestCode, wants, flags, wParams); EXPECT_NE(pendingWant, nullptr); @@ -308,7 +296,7 @@ HWTEST_F(PendingWantTest, PendingWant_1000, Function | MediumTest | Level1) std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser(nullptr, requestCode, want, flags, 0); EXPECT_EQ(pendingWant, nullptr); @@ -326,7 +314,7 @@ HWTEST_F(PendingWantTest, PendingWant_1100, Function | MediumTest | Level1) std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser(context, requestCode, want, flags, 0); EXPECT_NE(pendingWant, nullptr); @@ -342,7 +330,7 @@ HWTEST_F(PendingWantTest, PendingWant_1200, Function | MediumTest | Level1) std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want; - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser(context, requestCode, want, flags, 0); EXPECT_NE(pendingWant, nullptr); @@ -358,7 +346,7 @@ HWTEST_F(PendingWantTest, PendingWant_1300, Function | MediumTest | Level1) std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want; - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetService(context, requestCode, want, flags); EXPECT_NE(pendingWant, nullptr); @@ -375,7 +363,7 @@ HWTEST_F(PendingWantTest, PendingWant_1400, Function | MediumTest | Level1) std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetService(nullptr, requestCode, want, flags); EXPECT_EQ(pendingWant, nullptr); @@ -391,7 +379,7 @@ HWTEST_F(PendingWantTest, PendingWant_1500, Function | MediumTest | Level1) std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want; - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetForegroundService(context, requestCode, want, flags); EXPECT_NE(pendingWant, nullptr); @@ -408,7 +396,7 @@ HWTEST_F(PendingWantTest, PendingWant_1600, Function | MediumTest | Level1) std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; std::shared_ptr pendingWant = PendingWant::GetForegroundService(nullptr, requestCode, want, flags); EXPECT_EQ(pendingWant, nullptr); @@ -424,7 +412,7 @@ HWTEST_F(PendingWantTest, PendingWant_1700, Function | MediumTest | Level1) std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want; - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; WantAgentConstant::OperationType type = WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; std::shared_ptr pendingWant = @@ -443,7 +431,7 @@ HWTEST_F(PendingWantTest, PendingWant_1800, Function | MediumTest | Level1) std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; WantAgentConstant::OperationType type = WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; std::shared_ptr pendingWant = @@ -458,11 +446,11 @@ HWTEST_F(PendingWantTest, PendingWant_1800, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_1900, Function | MediumTest | Level1) { - sptr target(new (std::nothrow) WantSender()); + sptr target(new (std::nothrow) WantSender()); std::shared_ptr pendingWant = std::make_shared(target); - sptr target2(nullptr); + 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); } /* @@ -472,7 +460,7 @@ HWTEST_F(PendingWantTest, PendingWant_1900, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_2000, Function | MediumTest | Level1) { - sptr target(new (std::nothrow) WantSender()); + sptr target(new (std::nothrow) WantSender()); std::shared_ptr pendingWant = std::make_shared(target); std::shared_ptr pendingWant2(nullptr); EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), false); @@ -495,7 +483,7 @@ HWTEST_F(PendingWantTest, PendingWant_2100, Function | MediumTest | Level1) std::shared_ptr wParams = std::make_shared(); std::string key = "key"; wParams->SetParam(key, Boolean::Box(value)); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; AbilityManagerClient::GetInstance()->Connect(); EXPECT_EQ(INNER_ERR, @@ -518,7 +506,7 @@ HWTEST_F(PendingWantTest, PendingWant_2200, Function | MediumTest | Level1) std::shared_ptr wParams = std::make_shared(); std::string key = "key"; wParams->SetParam(key, Boolean::Box(value)); - int flags = 1; + unsigned int flags = 1; flags |= FLAG_NO_CREATE; AbilityManagerClient::GetInstance()->Connect(); EXPECT_EQ(1, pendingWant.SendAndReturnResult(nullptr, requestCode, want, nullptr, "Permission", nullptr, nullptr)); @@ -531,7 +519,7 @@ HWTEST_F(PendingWantTest, PendingWant_2200, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_2300, Function | MediumTest | Level1) { - sptr target(new (std::nothrow) WantSender()); + sptr target(new (std::nothrow) WantSender()); std::shared_ptr pendingWant = std::make_shared(target); std::shared_ptr pendingWant2 = std::make_shared(target); EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), true); @@ -556,7 +544,7 @@ HWTEST_F(PendingWantTest, PendingWant_2400, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_2500, Function | MediumTest | Level1) { - sptr target(new (std::nothrow) WantSender()); + sptr target(new (std::nothrow) WantSender()); PendingWant pendingWant(target); auto target1 = pendingWant.GetTarget(); EXPECT_EQ(target1, target); diff --git a/frameworks/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp b/frameworks/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp index 0fb2e984fb19bcb5c23160a2d197caacc7a74102..08c195f16af3898159e3d556a979ce1cf5f27fc6 100644 --- a/frameworks/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp +++ b/frameworks/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp @@ -28,6 +28,7 @@ #include "want.h" #include "want_params.h" #include "want_receiver_stub.h" +#include "ohos/aafwk/base/bool_wrapper.h" using namespace testing::ext; using namespace OHOS::AAFwk; diff --git a/frameworks/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp b/frameworks/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp index 95712307846388a3979a3c1c357c994164f66d5b..3b1ebfddaa6e6c965a7c4f18eba4ea9337745284 100644 --- a/frameworks/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp +++ b/frameworks/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp @@ -34,6 +34,7 @@ #include "want_params.h" #include "want_receiver_stub.h" #include "want_sender_stub.h" +#include "ohos/aafwk/base/bool_wrapper.h" using namespace testing::ext; using namespace OHOS::AAFwk; diff --git a/frameworks/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp b/frameworks/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp index bdf8d138408e0a253d43a1b62b3fac848f65dff3..03e10f936d58df85e12fb73d4033c71cb2906c06 100644 --- a/frameworks/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp +++ b/frameworks/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp @@ -34,6 +34,7 @@ #include "want_params.h" #include "want_receiver_stub.h" #include "want_sender_stub.h" +#include "ohos/aafwk/base/bool_wrapper.h" using namespace testing::ext; using namespace OHOS::AAFwk; diff --git a/interfaces/innerkits/ans/native/include/message_user.h b/interfaces/innerkits/ans/native/include/message_user.h index 3cb50e7cda8b36fd6b2121f7f3e8c0e7f4f16ca8..0ceb44f490471d3f6c3a0268206ac2d6c5330830 100644 --- a/interfaces/innerkits/ans/native/include/message_user.h +++ b/interfaces/innerkits/ans/native/include/message_user.h @@ -151,12 +151,12 @@ private: bool ReadFromParcel(Parcel &parcel); private: - std::string key_; - std::string name_; - std::shared_ptr pixelMap_; + std::string key_{}; + std::string name_{}; + std::shared_ptr pixelMap_{nullptr}; Uri uri_; - bool isMachine_; - bool isUserImportant_; + bool isMachine_{false}; + bool isUserImportant_{false}; // no object in parcel static constexpr int VALUE_NULL = -1; diff --git a/interfaces/innerkits/ans/native/include/notification.h b/interfaces/innerkits/ans/native/include/notification.h index ab91f6690c668fbba696b276813e7fdf203bf687..9a338eaea51762a53cdf5e694c9a8e2ef1d86359 100644 --- a/interfaces/innerkits/ans/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -42,6 +42,11 @@ public: */ Notification(const Notification &other); + /** + * @brief Default destructor. + */ + ~Notification(); + /** * @brief Obtains whether to enable the notification light when a notification is received on the device, provided * that this device has a notification light. @@ -146,14 +151,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 @@ -232,4 +237,4 @@ private: }; } // namespace Notification } // namespace OHOS -#endif \ No newline at end of file +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_H \ No newline at end of file diff --git a/interfaces/innerkits/ans/native/include/notification_action_button.h b/interfaces/innerkits/ans/native/include/notification_action_button.h index adda5ae958ce352bb29c066b94e04f7d94d7f00b..42f8af582eb30d87f0e372a0850d697104505617 100644 --- a/interfaces/innerkits/ans/native/include/notification_action_button.h +++ b/interfaces/innerkits/ans/native/include/notification_action_button.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * @@ -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_basic_content.h b/interfaces/innerkits/ans/native/include/notification_basic_content.h index c99a1cad9de1c41e5f6ffe448e28dd0b9b79aa98..f96de434bf797d8905fa7f7df4f74c0cd2a73b6f 100644 --- a/interfaces/innerkits/ans/native/include/notification_basic_content.h +++ b/interfaces/innerkits/ans/native/include/notification_basic_content.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * 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 0000000000000000000000000000000000000000..7c2fa9171aa53825cf990c0676bdd73ce76d83a3 --- /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 64bbddccd7e949e00cbae971192f9a881316528c..554699724dc7bb0459ba48323ee611b9439f1959 100644 --- a/interfaces/innerkits/ans/native/include/notification_constant.h +++ b/interfaces/innerkits/ans/native/include/notification_constant.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * @@ -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_content.h b/interfaces/innerkits/ans/native/include/notification_content.h index 01fc7fe8c001673bfb586d253083f4372f1b6e62..6a3733897f50d4be034d5a580ca44a5e92ed83ce 100644 --- a/interfaces/innerkits/ans/native/include/notification_content.h +++ b/interfaces/innerkits/ans/native/include/notification_content.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/interfaces/innerkits/ans/native/include/notification_conversational_content.h b/interfaces/innerkits/ans/native/include/notification_conversational_content.h index 894db41168f1ca8fe607797aca751c607996aca0..9e274ed77f1a6acea617825b68d42509850cd7dc 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_content.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_content.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/interfaces/innerkits/ans/native/include/notification_conversational_message.h b/interfaces/innerkits/ans/native/include/notification_conversational_message.h index e18b103f11fe134fb7be0c89768dc91c48101fe6..acd2c31ec0f2e11fe7462a9f44bb4ca1f60a912f 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_message.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_message.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/interfaces/innerkits/ans/native/include/notification_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index 236b4a41fd5e4a6d11cc05453b32aa3ac3c9223f..b6b5fbf65936495fce013a40afe962384a32b5bf 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -16,6 +16,7 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_HELPER_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_HELPER_H +#include "notification_bundle_option.h" #include "notification_request.h" #include "notification_slot.h" #include "notification_slot_group.h" @@ -41,6 +42,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 +67,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. * @@ -125,6 +141,15 @@ public: */ static ErrCode GetNotificationSlotGroups(std::vector> &groups); + /** + * Obtains number of slot. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param num Indicates number of slot. + * @return Returns get slot number by bundle result. + */ + static ErrCode GetNotificationSlotNumAsBundle(const NotificationBundleOption &bundleOption, int &num); + /** * Publishes a notification. * @note If a notification with the same ID has been published by the current application and has not been deleted, @@ -378,14 +403,35 @@ 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 bundleOption Indicates the bundle name and 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 NotificationBundleOption &bundleOption, 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 bundleOption Indicates the bundle name and uid of the application whose notifications are to be removed. + * @return Returns remove notification result. + */ + static ErrCode RemoveAllNotifications(const NotificationBundleOption &bundleOption); + /** * Removes all removable notifications of a specified bundle. * @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 bundleOption Indicates the bundle name and uid of the application whose notifications are to be removed. * @return Returns remove notifications result. */ - static ErrCode RemoveNotifications(const std::string &bundleName); + static ErrCode RemoveNotificationsByBundle(const NotificationBundleOption &bundleOption); /** * Removes all removable notifications in the system. @@ -397,12 +443,32 @@ public: /** * Returns all notification slots belonging to the specified bundle. * - * @param bundleName Indicates the application name. + * @param bundleOption Indicates the bundle name and uid of the application. * @param slots Indicates a list of notification slots. * @return Returns get notification slots for bundle result. */ static ErrCode GetNotificationSlotsForBundle( - const std::string &bundleName, std::vector> &slots); + const NotificationBundleOption &bundleOption, std::vector> &slots); + + /** + * Update all notification slots for the specified bundle. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param slots Indicates a list of new notification slots. + * @return Returns update notification slots for bundle result. + */ + static ErrCode UpdateNotificationSlots( + const NotificationBundleOption &bundleOption, const std::vector> &slots); + + /** + * Update all notification slot groups for the specified bundle. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param groups Indicates a list of new notification slot groups. + * @return Returns update notification slot groups for bundle result. + */ + static ErrCode UpdateNotificationSlotGroups( + const NotificationBundleOption &bundleOption, const std::vector> &groups); /** * Obtains all active notifications in the current system. The caller must have system permissions to @@ -430,11 +496,11 @@ public: * the current application, no permission is required for calling this method. If bundle specifies another * application, the caller must have system permissions. * - * @param bundle Indicates the bundle name of the application to check. + * @param bundleOption Indicates the bundle name and uid of the application. * @param allowed True if the application has permissions; returns false otherwise. * @return Returns is allowed notify result. */ - static ErrCode IsAllowedNotify(const std::string &bundle, bool &allowed); + static ErrCode IsAllowedNotify(const NotificationBundleOption &bundleOption, bool &allowed); /** * Sets whether to allow all applications to publish notifications on a specified device. The caller must have @@ -466,7 +532,7 @@ public: * Sets whether to allow a specified application to publish notifications on a specified device. The caller * must have system permissions to call this method. * - * @param bundle Indicates the bundle name of the application. + * @param bundleOption Indicates the bundle name and uid of the application. * @param deviceId Indicates the ID of the device running the application. At present, this parameter can only * be null or an empty string, indicating the current device. * @param enabled Specifies whether to allow the given application to publish notifications. The value @@ -475,7 +541,33 @@ public: * @return Returns set notifications enabled for specified bundle result. */ static ErrCode SetNotificationsEnabledForSpecifiedBundle( - const std::string &bundle, std::string &deviceId, bool enabled); + const NotificationBundleOption &bundleOption, std::string &deviceId, bool enabled); + + /** + * Sets whether to allow a specified application to show badge. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param enabled Specifies whether to allow the given application to show badge. + * @return Returns set result. + */ + static ErrCode SetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool enabled); + + /** + * Obtains the flag that whether to allow a specified application to show badge. + * + * @param bundleOption Indicates the bundle name and uid of the application. + * @param enabled Specifies whether to allow the given application to show badge. + * @return Returns get result. + */ + static ErrCode GetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool &enabled); + + /** + * Obtains the flag that whether to allow the current application to show badge. + * + * @param enabled Specifies whether to allow the given application to show badge. + * @return Returns get result. + */ + static ErrCode GetShowBadgeEnabled(bool &enabled); /** * Sets the type of the Do Not Disturb mode. The Do Not Disturb mode type specifies the type of notifications diff --git a/interfaces/innerkits/ans/native/include/notification_long_text_content.h b/interfaces/innerkits/ans/native/include/notification_long_text_content.h index c01757c786dd6ee951ad01113374cda118db9eaa..f0a7ffb1552e4949309dbd3e842cb20516450741 100644 --- a/interfaces/innerkits/ans/native/include/notification_long_text_content.h +++ b/interfaces/innerkits/ans/native/include/notification_long_text_content.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/interfaces/innerkits/ans/native/include/notification_media_content.h b/interfaces/innerkits/ans/native/include/notification_media_content.h index 00d29f7501c2a7b45e8216a6b1face8618b5c3b9..cfc7b3be27de4b8ed8fad3679f33421afcf8c9fd 100644 --- a/interfaces/innerkits/ans/native/include/notification_media_content.h +++ b/interfaces/innerkits/ans/native/include/notification_media_content.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/interfaces/innerkits/ans/native/include/notification_multiline_content.h b/interfaces/innerkits/ans/native/include/notification_multiline_content.h index db0f4db89960fa864f189791e64da5d12abcae84..1bbfe05ea420b78fbfe6826a53a9693f427f34e6 100644 --- a/interfaces/innerkits/ans/native/include/notification_multiline_content.h +++ b/interfaces/innerkits/ans/native/include/notification_multiline_content.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/interfaces/innerkits/ans/native/include/notification_normal_content.h b/interfaces/innerkits/ans/native/include/notification_normal_content.h index b9145ceb7c9bc52ca0c3ee68f5341b9af1f73b25..4bb177e95d9572f952e325f890edcd28dc2d043a 100644 --- a/interfaces/innerkits/ans/native/include/notification_normal_content.h +++ b/interfaces/innerkits/ans/native/include/notification_normal_content.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/interfaces/innerkits/ans/native/include/notification_picture_content.h b/interfaces/innerkits/ans/native/include/notification_picture_content.h index 45dda0608a93c942df368494ffbf68827843a648..1fdd92f7e5ec9576dfc7d56b04095f5ea90dc082 100644 --- a/interfaces/innerkits/ans/native/include/notification_picture_content.h +++ b/interfaces/innerkits/ans/native/include/notification_picture_content.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index c6e677199f7dc0b6844372c57f66f2ea68f4d7b6..0f52f5bf68cf1d885ee877df558cd1c12b1c8792 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * @@ -29,7 +29,6 @@ namespace OHOS { namespace Notification { -class ComponentProvider; class PixelMap; class NotificationRequest : public Parcelable { @@ -137,13 +136,13 @@ public: /** * Indicates the default notification background color, which means that no color is displayed. */ - static const int32_t COLOR_DEFAULT; + static const uint32_t COLOR_DEFAULT; private: /** * Indicates the color mask, used for calculation with the ARGB value set by setColor(int32_t). */ - static const int32_t COLOR_MASK; + static const uint32_t COLOR_MASK; /** * the maximum number of user input history is 5. @@ -442,15 +441,15 @@ public: * This method is valid only when background color has been enabled by calling setColorEnabled(bool). * @param color Indicates the background color to set. For details about the value range, see Color. */ - void SetColor(int32_t color); + void SetColor(uint32_t color); /** * Obtains the background color of this notification. * The return value, except for the default color COLOR_DEFAULT, - * is the bitwise OR operation result of 0xFF000000 and the ARGB value set by setColor(int32_t). + * is the bitwise OR operation result of 0xFF000000 and the ARGB value set by setColor(uint32_t). * @return the background color of this notification. */ - int32_t GetColor() const; + uint32_t GetColor() const; /** * Checks whether background color is enabled for this notification. @@ -508,47 +507,6 @@ public: */ void SetCountdownTimer(bool isCountDown); - /** - * Sets the custom view to be displayed when this notification is expanded. - * @param view Indicates the ComponentProvider object defining the custom view. - */ - void SetCustomBigView(const std::shared_ptr &view); - - /** - * Obtains the ComponentProvider object defining the custom view to be displayed when this notification is expanded - * The ComponentProvider object is set in setCustomBigView(ComponentProvider). - * @return the ComponentProvider object defining the custom view. - */ - const std::shared_ptr GetCustomBigView() const; - - /** - * Sets the custom view to be displayed when this notification is shown as a floating window at the top of the - * screen - * @param view Indicates the ComponentProvider object defining the custom view. - */ - void SetCustomFloatView(const std::shared_ptr &view); - - /** - * Obtains the ComponentProvider object defining the custom view to be displayed - * when this notification is shown as a floating window at the top of the screen. - * The ComponentProvider object is set in setCustomFloatView(ComponentProvider). - * @return the ComponentProvider object defining the custom view. - */ - const std::shared_ptr GetCustomFloatView() const; - - /** - * Sets the custom view of this notification. - * @param view Indicates the ComponentProvider object defining the custom view. - */ - void SetCustomView(const std::shared_ptr &view); - - /** - * Obtains the ComponentProvider object defining the custom view set in this notification. - * The ComponentProvider object is set in setCustomView(ComponentProvider). - * @return the ComponentProvider object defining the custom view. - */ - const std::shared_ptr GetCustomView() const; - /** * Sets the group alert type for this notification, * which determines how the group overview and other notifications in a group are published. @@ -877,13 +835,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. @@ -932,7 +890,7 @@ private: private: int32_t notificationId_{0}; - int32_t color_{NotificationRequest::COLOR_DEFAULT}; + uint32_t color_{NotificationRequest::COLOR_DEFAULT}; int32_t badgeNumber_{0}; int32_t progressValue_{0}; int32_t progressMax_{0}; @@ -941,7 +899,7 @@ private: int64_t autoDeletedTime_{0}; pid_t creatorPid_{0}; - uid_t creatorUid_{0}; + pid_t creatorUid_{0}; std::string settingsText_{}; std::string creatorBundleName_{}; @@ -981,9 +939,6 @@ private: std::shared_ptr littleIcon_{}; std::shared_ptr bigIcon_{}; std::shared_ptr notificationContent_{}; - std::shared_ptr customBigView_{}; - std::shared_ptr customFloatView_{}; - std::shared_ptr customView_{}; std::shared_ptr publicNotification_{}; std::vector> actionButtons_{}; diff --git a/interfaces/innerkits/ans/native/include/notification_slot.h b/interfaces/innerkits/ans/native/include/notification_slot.h index c5cce655349f78045340f6d311b316e34f560b02..5a82654defffab83ad155a8ed2acff14ad635951 100644 --- a/interfaces/innerkits/ans/native/include/notification_slot.h +++ b/interfaces/innerkits/ans/native/include/notification_slot.h @@ -346,20 +346,20 @@ private: void SetName(const std::string &name); private: - std::string id_; - std::string name_; - bool isLightEnabled_; - bool isVibrationEnabled_; - bool isShowBadge_ = true; - bool isBypassDnd_; - std::string description_; - int32_t lightColor_ = 0; - NotificationLevel level_ = LEVEL_DEFAULT; - NotificationConstant::SlotType type_; + std::string id_{}; + std::string name_{}; + bool isLightEnabled_ {false}; + bool isVibrationEnabled_ {false}; + bool isShowBadge_{true}; + bool isBypassDnd_{false}; + std::string description_{}; + int32_t lightColor_ {0}; + NotificationLevel level_{LEVEL_DEFAULT}; + NotificationConstant::SlotType type_{}; NotificationConstant::VisiblenessType lockScreenVisibleness_{NotificationConstant::VisiblenessType::NO_OVERRIDE}; - std::string groupId_; + std::string groupId_{}; Uri sound_; - std::vector vibrationValues_; + std::vector vibrationValues_{}; // no object in parcel static constexpr int VALUE_NULL = -1; diff --git a/interfaces/innerkits/ans/native/include/notification_slot_group.h b/interfaces/innerkits/ans/native/include/notification_slot_group.h index ba95b6af4acf8cd4fc4939c5bf2b1e16fece202c..f979cdd93a758859bbc14e71f56aa4cf04eced8d 100644 --- a/interfaces/innerkits/ans/native/include/notification_slot_group.h +++ b/interfaces/innerkits/ans/native/include/notification_slot_group.h @@ -24,10 +24,6 @@ namespace OHOS { namespace Notification { class NotificationSlotGroup : public Parcelable { public: - /** - * Default constructor used to create a NotificationSlotGroup instance. - */ - NotificationSlotGroup(); /** * A constructor used to create a NotificationSlotGroup instance with the group ID and name initialized. @@ -69,6 +65,14 @@ public: /** * Obtains a list of notification slots bound to this NotificationSlotGroup object. * @note NotificationSlot::SetSlotGroup(string) is used to bind a notification slot to a notification slot group. + * @param slots Indicates the slots which to set to the slotgroup. + * + */ + void SetSlots(const std::vector &slots); + + /** + * Sets a list of notification slots bound to this NotificationSlotGroup object. + * @note NotificationSlot::SetSlotGroup(string) is used to bind a notification slot to a notification slot group. * * @return Returns the list of notification slots bound to this NotificationSlotGroup. */ @@ -121,6 +125,12 @@ public: std::string TruncateString(const std::string &inPutString); private: + + /** + * Default constructor used to create a NotificationSlotGroup instance. + */ + NotificationSlotGroup(); + /** * Read NotificationSlotGroup object from a Parcel. * @@ -130,11 +140,11 @@ private: bool ReadFromParcel(Parcel &parcel); private: - std::string id_; - std::string name_; - std::string description_; - std::vector slots_; - bool isDisabled_; + std::string id_{}; + std::string name_{}; + std::string description_{}; + std::vector slots_{}; + bool isDisabled_{false}; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_subscriber.h b/interfaces/innerkits/ans/native/include/notification_subscriber.h index 24b1c4ac34f30611c6646a6db6ccb44cd15bf550..7cbac600d704b5def985abae02a67d2467a2e523 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscriber.h +++ b/interfaces/innerkits/ans/native/include/notification_subscriber.h @@ -33,10 +33,12 @@ public: /** * @brief Default constructor used to create a instance. */ - NotificationSubscriber() - { - impl_ = new SubscriberImpl(*this); - }; + NotificationSubscriber(); + + /** + * @brief Default destructor. + */ + virtual ~NotificationSubscriber(); /** * @brief Called back when a notification is canceled. @@ -162,4 +164,4 @@ private: } // namespace Notification } // namespace OHOS -#endif \ No newline at end of file +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SUBSCRIBER_H \ No newline at end of file diff --git a/interfaces/innerkits/ans/native/include/notification_user_input.h b/interfaces/innerkits/ans/native/include/notification_user_input.h index 97b34ed895cb4f81af9b6fd9b8eb9791dbbe9b81..41b548076c41778e4748d92fd371289f037d0fe4 100644 --- a/interfaces/innerkits/ans/native/include/notification_user_input.h +++ b/interfaces/innerkits/ans/native/include/notification_user_input.h @@ -1,6 +1,6 @@ /* - * Copyright (c); 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License");; + * 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 * diff --git a/interfaces/innerkits/wantagent/include/trigger_info.h b/interfaces/innerkits/wantagent/include/trigger_info.h index 9e6eff4e18a67ce540a11eae6487b8250c33e92b..ce60016a4f2758f687fa2dd2495ca816d59e8b78 100644 --- a/interfaces/innerkits/wantagent/include/trigger_info.h +++ b/interfaces/innerkits/wantagent/include/trigger_info.h @@ -29,6 +29,7 @@ class TriggerInfo final : public std::enable_shared_from_this { */ public: TriggerInfo(); + virtual ~TriggerInfo() = default; /** * A constructor used to create a {@code TriggerInfo} instance based on the input parameters. @@ -57,6 +58,14 @@ public: */ explicit TriggerInfo(const TriggerInfo ¶mInfo); + /** + * A copy assignment operator used to create a {@code TriggerInfo} instance by copying parameters from an existing + * one. + * + * @param paramInfo Indicates the existing {@code TriggerInfo} object. + */ + const TriggerInfo &operator=(const TriggerInfo ¶mInfo); + /** * Obtains the permission from the current {@code TriggerInfo} object. * @@ -103,6 +112,7 @@ public: */ public: Builder(); + virtual ~Builder() = default; /** * Sets the permission that the {@link WantAgent} recipient must have. diff --git a/interfaces/innerkits/wantagent/include/want_agent.h b/interfaces/innerkits/wantagent/include/want_agent.h index 6b8251f14d8f08836d0f036b037b0e6b016f557b..06d6cd36bbaa03c524ee2600ce1c87ccd9a8f418 100644 --- a/interfaces/innerkits/wantagent/include/want_agent.h +++ b/interfaces/innerkits/wantagent/include/want_agent.h @@ -35,6 +35,7 @@ private: */ public: WantAgent(){}; + virtual ~WantAgent() = default; explicit WantAgent(const std::shared_ptr &pendingWant); /** diff --git a/interfaces/innerkits/wantagent/include/want_agent_constant.h b/interfaces/innerkits/wantagent/include/want_agent_constant.h index 867be3a99c050cfdd5e92dc96950392cea5a270a..461b023c1fb8d2946e3cbff3116ed5df90150b28 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_constant.h +++ b/interfaces/innerkits/wantagent/include/want_agent_constant.h @@ -127,6 +127,7 @@ public: private: WantAgentConstant(){}; + virtual ~WantAgentConstant() = default; }; } // namespace OHOS::Notification::WantAgent #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_CONSTANT_H diff --git a/interfaces/innerkits/wantagent/include/want_agent_helper.h b/interfaces/innerkits/wantagent/include/want_agent_helper.h index e217e5bdb626bd58c7a27ecbda3c84edb841e780..cf775dde26013fa2d08189843925e5f490a2caa6 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_helper.h +++ b/interfaces/innerkits/wantagent/include/want_agent_helper.h @@ -44,7 +44,9 @@ static const int FLAG_IMMUTABLE = 1 << 26; class WantAgentHelper final : public std::enable_shared_from_this { private: WantAgentHelper(); + virtual ~WantAgentHelper() = default; +public: /** * Obtains an WantAgent object. * The WantAgent class does not have any constructor, and you can only use this method to create an @@ -55,7 +57,6 @@ private: * WantAgent object to create. * @return Returns the created WantAgent object. */ -public: static std::shared_ptr GetWantAgent( const std::shared_ptr &context, const WantAgentInfo ¶msInfo); @@ -71,6 +72,12 @@ public: */ static std::shared_ptr GetWantAgent(const WantAgentInfo ¶msInfo); + /** + * Obtains an WantAgent object operation type. + * + * @param agent Indicates the WantAgent to trigger. + * @return Returns the created WantAgent object. + */ static WantAgentConstant::OperationType GetType(const std::shared_ptr &agent); /** @@ -142,9 +149,21 @@ public: */ static std::shared_ptr GetWant(const std::shared_ptr &agent); + /** + * Register Cancel function Listener. + * + * @param cancelListener Register listener object. + * @param agent Indicates the WantAgent whose bundle name is to be obtained. + */ static void RegisterCancelListener( const std::shared_ptr &cancelListener, const std::shared_ptr &agent); + /** + * Unregister Cancel function Listener. + * + * @param cancelListener Register listener object. + * @param agent Indicates the WantAgent whose bundle name is to be obtained. + */ static void UnregisterCancelListener( const std::shared_ptr &cancelListener, const std::shared_ptr &agent); diff --git a/interfaces/innerkits/wantagent/include/want_agent_info.h b/interfaces/innerkits/wantagent/include/want_agent_info.h index 168443c266a415cbe36522885c57d16d0dc02c51..15c411dc90e75bab07b2a0f44de7e35a260fd684 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_info.h +++ b/interfaces/innerkits/wantagent/include/want_agent_info.h @@ -45,7 +45,7 @@ private: */ public: WantAgentInfo(); - ~WantAgentInfo() = default; + virtual ~WantAgentInfo() = default; /** * A constructor used to create an WantAgentInfo instance based on the input parameters. diff --git a/interfaces/kits/js/@ohos.notification.d.ts b/interfaces/kits/js/@ohos.notification.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8c7dc59d4b4e57538ae25207b359e66601f696f --- /dev/null +++ b/interfaces/kits/js/@ohos.notification.d.ts @@ -0,0 +1,406 @@ +/* + * 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 { NotificationSubscriber } from './notification/notificationSubscriber'; +import { NotificationSubscribeInfo } from './notification/notificationSubscribeInfo'; +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; + + /** + * Creates a notification slot. + * + * @param slot Indicates the notification slot to be created, which is set by {@link NotificationSlot}. + * This parameter must be specified. + * + * @SystemApi + * @since 7 + */ + function addSlot(slot: NotificationSlot, callback: AsyncCallback): void; + function addSlot(slot: NotificationSlot): Promise; + + /** + * Creates a notification slot. + * + * @param slot Indicates the notification slot to be created, which is set by {@link SlotType}. + * This parameter must be specified. + * + * @since 7 + */ + function addSlot(type: SlotType, callback: AsyncCallback): void; + function addSlot(type: SlotType): Promise; + + /** + * Creates a notification slot. + * + * @param slots Indicates the notification slots to be created, which is set by {@link NotificationSlot}. + * This parameter must be specified. + * + * @SystemApi + * @since 7 + */ + function addSlots(slots: Array, callback: AsyncCallback): void; + function addSlots(slots: Array): 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; + + /** + * Deletes all notification slots. + * + * @since 7 + */ + function removeAllSlots(callback: AsyncCallback): void; + function removeAllSlots(): 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_PICTURE, + NOTIFICATION_CONTENT_CONVERSATION, + NOTIFICATION_CONTENT_MULTILINE, + NOTIFICATION_CONTENT_MEDIA + } + + /** + * Indicates the level of the slot + * + * @since 7 + */ + export enum SlotLevel { + LEVEL_NONE = 0, + LEVEL_MIN = 1, + LEVEL_LOW = 2, + LEVEL_DEFAULT = 3, + LEVEL_HIGH = 4, + } + + /** + * subscribe + * + * @systemapi + * @since 7 + */ + function subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void; + function subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback): void; + function subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): Promise; + + /** + * unsubscribe + * + * @systemapi + * @since 7 + */ + function unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void; + function unsubscribe(subscriber: NotificationSubscriber): Promise; + + /** + * enableNotification + * + * @systemapi + * @since 7 + */ + function enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void; + function enableNotification(bundle: BundleOption, enable: boolean): Promise; + + /** + * canNotify + * + * @systemapi + * @since 7 + */ + function isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback): void; + function isNotificationEnabled(bundle: BundleOption): Promise; + + /** + * canNotify + * + * @since 7 + */ + function isNotificationEnabled(callback: AsyncCallback): void; + function isNotificationEnabled(): Promise; + + /** + * isBadgeDisplayed + * + * @systemapi + * @since 7 + */ + function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void; + function displayBadge(bundle: BundleOption, enable: boolean): Promise; + + /** + * canDisplayBadge + * + * @systemapi + * @since 7 + */ + function isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback): void; + function isBadgeDisplayed(bundle: BundleOption): Promise; + + /** + * isShowBadge + * + * @since 7 + */ + function isBadgeDisplayed(callback: AsyncCallback): void; + function isBadgeDisplayed(): Promise; + + /** + * setSlotAsBundle + * + * @systemapi + * @since 7 + */ + function setSlotAsBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback): void; + function setSlotAsBundle(bundle: BundleOption, slot: NotificationSlot): Promise; + + /** + * getSlotsAsBundle + * + * @systemapi + * @since 7 + */ + function getSlotsAsBundle(bundle: BundleOption, callback: AsyncCallback>): void; + function getSlotsAsBundle(bundle: BundleOption): Promise>; + + /** + * getSlotNumAsBundle + * + * @systemapi + * @since 7 + */ + function getSlotNumAsBundle(bundle: BundleOption, callback: AsyncCallback): void; + function getSlotNumAsBundle(bundle: BundleOption): Promise; + + /** + * remove + * + * @systemapi + * @since 7 + */ + function remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback): void; + function remove(bundle: BundleOption, notificationKey: NotificationKey): Promise; + + /** + * remove + * + * @systemapi + * @since 7 + */ + function remove(hashCode: string, callback: AsyncCallback): void; + function remove(hashCode: string): Promise; + + /** + * removeAll + * + * @systemapi + * @since 7 + */ + function removeAll(bundle: BundleOption, callback: AsyncCallback): void; + function removeAll(callback: AsyncCallback): void; + function removeAll(bundle?: BundleOption): 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>; + + /** + * BundleOption + * + * @since 7 + */ + export interface BundleOption { + bundle: string; + uid?: number; + } + + /** + * NotificationKey + * + * @since 7 + */ + export interface NotificationKey { + id: number; + lable?: string; + } + + /** + * DisturbMode + * + * @since 7 + */ + export enum DoNotDisturbMode { + ALLOW_UNKNOWN, + + /** + * Indicates that all notifications are allowed to interrupt the user in Do Not Disturb mode. + */ + ALLOW_ALL, + + /** + * Indicates that only notifications meeting the specified priority criteria are allowed to interrupt + * the user in Do Not Disturb mode. + */ + ALLOW_PRIORITY, + + /** + * Indicates that no notifications are allowed to interrupt the user in Do Not Disturb mode. + */ + ALLOW_NONE, + + /** + * Indicates that only notifications of the {@link NotificationRequest#CLASSIFICATION_ALARM} category + * are allowed to interrupt the user in Do Not Disturb mode. + */ + ALLOW_ALARMS + } +} + +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 0000000000000000000000000000000000000000..23f8c861f02c32abbb82242267425349ef4e51e5 --- /dev/null +++ b/interfaces/kits/js/@ohos.wantAgent.d.ts @@ -0,0 +1,154 @@ +/* + * 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. + * + * @systemApi + * @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 IntentAgent} 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 WantAgentFlags { + 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/notificationActionButton.ts b/interfaces/kits/js/notification/notificationActionButton.ts new file mode 100644 index 0000000000000000000000000000000000000000..21690e602d06fc309aecfa7f771d53fe21b1ff2b --- /dev/null +++ b/interfaces/kits/js/notification/notificationActionButton.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 { AsyncCallback } from './../basic'; +import { WantAgent } from '../@ohos.wantAgent'; +import image from '../@ohos.multimedia.image'; + +/** + * The action button of notification + * @name NotificationActionButton + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationActionButton { + title: string; + wantAgent: WantAgent; +} diff --git a/interfaces/kits/js/notification/notificationContent.d.ts b/interfaces/kits/js/notification/notificationContent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f89526b33a8a6bc4d5ac62f0621734d6457d5228 --- /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 0000000000000000000000000000000000000000..5fd0fc9e6ed2cc3470831eed09b979568b57af15 --- /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 { AsyncCallback } from './../basic'; +import notification from '../@ohos.notification'; +import image from '../@ohos.multimedia.image'; +import { WantAgent } from '../@ohos.wantAgent'; +import { NotificationContent } from './notificationContent'; +import { NotificationActionButton } from './notificationActionButton'; + +/** + * 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; + statusBarText?: string; + isFloatingIcon?: boolean; + label?: string; + badgeIconStyle?: number; + showDeliveryTime?: boolean; + actionButtons?: Array; + readonly creatorBundleName?: string; + readonly creatorUid?: number; + readonly creatorPid?: number; + + /** + * Obtains the classification of this notification. + * + * @systemapi + * @since 7 + */ + classification?: string; + + /** + * Obtains the unique hash code of a notification in the current application. + * + * @since 7 + */ + readonly hashCode?: string; +} diff --git a/interfaces/kits/js/notification/notificationSlot.d.ts b/interfaces/kits/js/notification/notificationSlot.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e91e8c0eb652a894c612cbdecc87f7718fe25387 --- /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?: notification.SlotLevel; + + /** + * Obtains the description of a notification slot. + * + * @since 7 + */ + desc?: string; + + /** + * Obtains the application icon badge status of a notification slot. + * + * @since 7 + */ + badgeFlag?: 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 0000000000000000000000000000000000000000..73fbae19b4444d31a10a3ca357bbf5e229fa081b --- /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 0000000000000000000000000000000000000000..f632189dea7ef101119f40ed4e654d980142113a --- /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/notification/notificationSubscribeInfo.ts b/interfaces/kits/js/notification/notificationSubscribeInfo.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d9afb6498918fd71f3550d7b0dc30ea893f936a --- /dev/null +++ b/interfaces/kits/js/notification/notificationSubscribeInfo.ts @@ -0,0 +1,28 @@ +/* + * 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. + */ + +/** + * Sets filter criteria of publishers for subscribing to desired notifications. + * + * @name NotificationSubscribeInfo + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationSubscribeInfo { + bundleNames?: Array; + userId?: number; +} \ No newline at end of file diff --git a/interfaces/kits/js/notification/notificationSubscriber.d.ts b/interfaces/kits/js/notification/notificationSubscriber.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..309c15bb3f1c980f841494a54c49b311d8809d0f --- /dev/null +++ b/interfaces/kits/js/notification/notificationSubscriber.d.ts @@ -0,0 +1,58 @@ +/* + * 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 { NotificationRequest } from './notificationRequest'; +import { NotificationSortingMap } from './notificationSortingMap'; +import notification from '../@ohos.notification'; + +/** + * Provides methods that will be called back when the subscriber receives a new notification or + * a notification is canceled. + * + * @name NotificationSubscriber + * @sysCap ans + * @devices phone, tablet + * @permission N/A + * @systemApi + * @since 7 + */ +export interface NotificationSubscriber { + onConsumed?:(data: SubscribeCallbackData) => void; + onCanceled?:(data: SubscribeCallbackData) => void; + onUpdate?:(data: NotificationSortingMap) => void; + onConnected?:() => void; + onDisConnect?:() => void; + onDied?:() => void; + onDisturbModeChanged?:(mode: notification.DoNotDisturbMode) => void; +} + +/** + * Provides methods that will be called back when the subscriber receives a new notification or + * a notification is canceled. + * + * @name SubscribeCallbackData + * @sysCap ans + * @devices phone, tablet + * @permission N/A + * @systemApi + * @since 7 + */ +export interface SubscribeCallbackData { + readonly request: NotificationRequest; + readonly sortingMap?: NotificationSortingMap; + readonly reason?: number; + readonly sound?: string; + readonly vibrationValues?: 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 0000000000000000000000000000000000000000..f12ac8ebe158e4e26412f8cd0abfa6e489ff0219 --- /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 0000000000000000000000000000000000000000..675ba97d1e736b65b7cf89a5ff8db04edce04c7e --- /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/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn old mode 100644 new mode 100755 index 2c1ca3a90ebcbe3b20c1b87e3560694189b07a01..d7d886bebb471e003d23ebde37b64d8d6dc9148c --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -48,7 +48,9 @@ ohos_shared_library("notification") { "src/cancel.cpp", "src/common.cpp", "src/constant.cpp", - "src/create_subscriber.cpp", + "src/display_badge.cpp", + "src/disturb_mode.cpp", + "src/enable_notification.cpp", "src/get_active.cpp", "src/init.cpp", "src/publish.cpp", diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index 9b427c4d44ec13e053cbd7aa555e1ff4352f9918..92a08e74b15d9c1caebd8576d3a117c880cd786b 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, @@ -78,22 +87,31 @@ enum DisturbMode { ALLOW_UNKNOWN, ALLOW_ALL, ALLOW_PRIORITY, ALLOW_NONE, ALLOW_A enum InputEditType { EDIT_AUTO, EDIT_DISABLED, EDIT_ENABLED }; -struct NotificationSubscriberInfo { +struct NotificationSubscribeInfo { std::vector bundleNames; // std::vector deviceIds; int userId = 0; - bool hasSubscriberInfo = false; + bool hasSubscribeInfo = false; +}; + +struct BundleOption { + std::string bundle{}; + int uid{}; +}; + +struct NotificationKey { + int id{}; + std::string label{}; }; struct CallbackPromiseInfo { napi_ref callback = nullptr; - napi_deferred deferred; + napi_deferred deferred = nullptr; bool isCallback = false; int errorCode = 0; }; 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( @@ -155,7 +176,7 @@ public: const napi_env &env, const std::shared_ptr &actionButton, napi_value &result); static napi_value GetNotificationSubscriberInfo( - const napi_env &env, const napi_value &value, NotificationSubscriberInfo &result); + const napi_env &env, const napi_value &value, NotificationSubscribeInfo &result); static napi_value GetNotificationRequest( const napi_env &env, const napi_value &value, NotificationRequest &request); @@ -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); @@ -186,6 +215,7 @@ private: static const int ARGS_TWO = 2; static const int PARAM0 = 0; static const int PARAM1 = 1; + static std::set> wantAgent_; }; } // namespace NotificationNapi diff --git a/interfaces/kits/napi/ans/include/constant.h b/interfaces/kits/napi/ans/include/constant.h index 516b4422f9a1362155c9e0b8afe50ec69cc9493b..249864af98f992e3c9c266e015bff04dde9183b3 100644 --- a/interfaces/kits/napi/ans/include/constant.h +++ b/interfaces/kits/napi/ans/include/constant.h @@ -24,9 +24,10 @@ 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); +napi_value DoNotDisturbMode(napi_env env, napi_value exports); napi_value InputEditTypeInit(napi_env env, napi_value exports); napi_value ContentTypeInit(napi_env env, napi_value exports); napi_value ConstantInit(napi_env env, napi_value exports); diff --git a/interfaces/kits/napi/ans/include/create_subscriber.h b/interfaces/kits/napi/ans/include/create_subscriber.h deleted file mode 100644 index a5f0055c48d5d36a868f23739610e4658da81243..0000000000000000000000000000000000000000 --- a/interfaces/kits/napi/ans/include/create_subscriber.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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_NAPI_INCLUDE_CREATE_SUBSCRIBER_H -#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_CREATE_SUBSCRIBER_H - -#include -#include - -#include "common.h" - -namespace OHOS { -namespace NotificationNapi { -using namespace OHOS::Notification; - -class SubscriberInstance; -struct AsyncCallbackInfoOn { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = 0; - SubscriberInstance *objectInfo; - std::string type; -}; - -class SubscriberInstance : public NotificationSubscriber { -public: - SubscriberInstance(); - - virtual ~SubscriberInstance(); - - virtual void OnCanceled(const std::shared_ptr &request) override; - - virtual void OnCanceled(const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason) override; - - virtual void OnConsumed(const std::shared_ptr &request) override; - - virtual void OnConsumed(const std::shared_ptr &request, - const std::shared_ptr &sortingMap) override; - - virtual void OnUpdate(const std::shared_ptr &sortingMap) override; - - virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override; - - virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override; - - virtual void OnDied() override; - - virtual void OnDisturbModeChanged(int disturbMode) override; - - void SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref); - -private: - void SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref); - - void SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref); - - void SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref); - - void SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref); - - void SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref); - - void SetDieCallbackInfo(const napi_env &env, const napi_ref &ref); - - void SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref); - -private: - struct CallbackInfo { - napi_env env; - napi_ref ref; - }; - - CallbackInfo canceCallbackInfo_; - CallbackInfo consumeCallbackInfo_; - CallbackInfo updateCallbackInfo_; - CallbackInfo subscribeCallbackInfo_; - CallbackInfo unsubscribeCallbackInfo_; - CallbackInfo dieCallbackInfo_; - CallbackInfo disturbModeCallbackInfo_; -}; - -napi_value NotificationSubscriberInit(napi_env env, napi_value exports); - -napi_value On(napi_env env, napi_callback_info info); - -napi_value Off(napi_env env, napi_callback_info info); - -napi_value CreateSubscriber(napi_env env, napi_callback_info info); - -bool CreateSubscriberInstanceRecord(SubscriberInstance **subscriber); - -bool AddAsyncCallbackInfo(SubscriberInstance *subscriber, AsyncCallbackInfoOn *asynccallbackinfo); - -bool DelAsyncCallbackInfo(SubscriberInstance *subscriber, const std::string &type = ""); - -bool HasNotificationSubscriber(SubscriberInstance *subscriber); - -static std::mutex mutex_; -static napi_value g_NotificationSubscriber; -static std::map> g_SubscriberInstances; - -} // namespace NotificationNapi -} // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_CREATE_SUBSCRIBER_H \ No newline at end of file diff --git a/services/ans/test/unittest/mock/mock_bundle_manager.cpp b/interfaces/kits/napi/ans/include/display_badge.h similarity index 50% rename from services/ans/test/unittest/mock/mock_bundle_manager.cpp rename to interfaces/kits/napi/ans/include/display_badge.h index d026341ec21ed697a96b995aa8f4bcb40ff9f804..945543193b1a9beb9cd79442466f9f2f60546992 100644 --- a/services/ans/test/unittest/mock/mock_bundle_manager.cpp +++ b/interfaces/kits/napi/ans/include/display_badge.h @@ -12,34 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_DISPLAY_BADGE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_DISPLAY_BADGE_H -#include "mock_bundle_manager.h" -#include "ability_info.h" -#include "application_info.h" +#include "common.h" namespace OHOS { -namespace AppExecFwk { -void MockBundleMgrService::MockSetIsSystemApp(bool isSystemApp) -{ - isSystemAppMock_ = true; - isSystemApp_ = isSystemApp; -} +namespace NotificationNapi { +using namespace OHOS::Notification; -bool MockBundleMgrService::CheckIsSystemAppByUid(const int uid) -{ - if (isSystemAppMock_) { - return isSystemApp_; - } - return (uid < 1000) ? false : true; -} +napi_value DisplayBadge(napi_env env, napi_callback_info info); +napi_value IsBadgeDisplayed(napi_env env, napi_callback_info info); -int MockBundleMgrService::CheckPermission(const std::string &bundleName, const std::string &permission) -{ - if (!bundleName.compare("bundleName")) { - return 0; - } else { - return -1; - } -} -} // namespace AppExecFwk +} // namespace NotificationNapi } // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_DISPLAY_BADGE_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/disturb_mode.h b/interfaces/kits/napi/ans/include/disturb_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..9a199f9a7345d1f8389096589412d82f39ae8105 --- /dev/null +++ b/interfaces/kits/napi/ans/include/disturb_mode.h @@ -0,0 +1,28 @@ +/* + * 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_NAPI_INCLUDE_DISTURB_MODE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_DISTURB_MODE_H + +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +napi_value SetDoNotDisturbMode(napi_env env, napi_callback_info info); + +} // namespace NotificationNapi +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_DISTURB_MODE_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/enable_notification.h b/interfaces/kits/napi/ans/include/enable_notification.h new file mode 100644 index 0000000000000000000000000000000000000000..e7ae306486c5be506303458a24f219c07b754f23 --- /dev/null +++ b/interfaces/kits/napi/ans/include/enable_notification.h @@ -0,0 +1,29 @@ +/* + * 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_NAPI_INCLUDE_ENABLE_NOTIFICATION_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_ENABLE_NOTIFICATION_H + +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +napi_value EnableNotification(napi_env env, napi_callback_info info); +napi_value IsNotificationEnabled(napi_env env, napi_callback_info info); + +} // namespace NotificationNapi +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_ENABLE_NOTIFICATION_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/slot.h b/interfaces/kits/napi/ans/include/slot.h index 1f851d501b920daf942aba25d453ce55fdb5c300..789bc5376b66842ea0bb5693fec868b9d783162d 100644 --- a/interfaces/kits/napi/ans/include/slot.h +++ b/interfaces/kits/napi/ans/include/slot.h @@ -23,9 +23,13 @@ using namespace OHOS::Notification; napi_value AddSlot(napi_env env, napi_callback_info info); napi_value AddSlots(napi_env env, napi_callback_info info); +napi_value SetSlotAsBundle(napi_env env, napi_callback_info info); napi_value GetSlot(napi_env env, napi_callback_info info); +napi_value GetSlotNumAsBundle(napi_env env, napi_callback_info info); napi_value GetSlots(napi_env env, napi_callback_info info); +napi_value GetSlotsAsBundle(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/include/subscribe.h b/interfaces/kits/napi/ans/include/subscribe.h index 80b0faffee90fc2ce2d4d1fa8b29f3b6a45abb7b..5046928a0aec27bf2f03e92eac04b0e508a5608c 100644 --- a/interfaces/kits/napi/ans/include/subscribe.h +++ b/interfaces/kits/napi/ans/include/subscribe.h @@ -15,15 +15,84 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SUBSCRIBE_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SUBSCRIBE_H -#include "create_subscriber.h" #include "common.h" namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; +class SubscriberInstance : public NotificationSubscriber { +public: + SubscriberInstance(); + + virtual ~SubscriberInstance(); + + virtual void OnCanceled(const std::shared_ptr &request) override; + + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override; + + virtual void OnConsumed(const std::shared_ptr &request) override; + + virtual void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override; + + virtual void OnUpdate(const std::shared_ptr &sortingMap) override; + + virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override; + + virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override; + + virtual void OnDied() override; + + virtual void OnDisturbModeChanged(int disturbMode) override; + + void SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref); + +private: + void SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetDieCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref); + +private: + struct CallbackInfo { + napi_env env = nullptr; + napi_ref ref = nullptr; + }; + + CallbackInfo canceCallbackInfo_; + CallbackInfo consumeCallbackInfo_; + CallbackInfo updateCallbackInfo_; + CallbackInfo subscribeCallbackInfo_; + CallbackInfo unsubscribeCallbackInfo_; + CallbackInfo dieCallbackInfo_; + CallbackInfo disturbModeCallbackInfo_; +}; + +struct SubscriberInstancesInfo { + napi_ref ref = nullptr; + SubscriberInstance *subscriber = nullptr; +}; + +static std::mutex mutex_; +static std::vector subscriberInstances_; + +bool HasNotificationSubscriber(const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo); +bool AddSubscriberInstancesInfo(const napi_env &env, const SubscriberInstancesInfo &subscriberInfo); +bool DelSubscriberInstancesInfo(const napi_env &env, SubscriberInstance *subscriber); + napi_value Subscribe(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SUBSCRIBE_H +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SUBSCRIBE_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/unsubscribe.h b/interfaces/kits/napi/ans/include/unsubscribe.h index ac6c6d8c47f3d2026829c8c6ec4cd13d48381568..595de743b7f07909e92fd0bbbe89227524f2f3af 100644 --- a/interfaces/kits/napi/ans/include/unsubscribe.h +++ b/interfaces/kits/napi/ans/include/unsubscribe.h @@ -17,7 +17,6 @@ #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_UNSUBSCRIBE_H #include "common.h" -#include "create_subscriber.h" namespace OHOS { namespace NotificationNapi { diff --git a/interfaces/kits/napi/ans/src/cancel.cpp b/interfaces/kits/napi/ans/src/cancel.cpp index 24fb596751343da61e6a91e47214b4a5204a523c..5264e984fa929a82ca024c7ee836410d3b5f048c 100644 --- a/interfaces/kits/napi/ans/src/cancel.cpp +++ b/interfaces/kits/napi/ans/src/cancel.cpp @@ -21,70 +21,73 @@ namespace NotificationNapi { const int CANCEL_MAX_PARA = 3; const int CANCEL_ALL_MAX_PARA = 1; -struct AsyncCallbackInfoCancel { - napi_env env; - napi_async_work asyncWork; +struct ParametersInfoCancel { + int id = 0; + std::string label = ""; napi_ref callback = nullptr; - napi_deferred deferred; - std::string label; - int id; - bool hasLabel = false; - bool isCallback = false; - int errorCode = 0; }; -struct paraInfoCancel { +struct AsyncCallbackInfoCancel { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; int id = 0; std::string label; - bool hasLabel = false; + CallbackPromiseInfo info; }; -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] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; + napi_valuetype valuetype = napi_undefined; // 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] = {nullptr}; + 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; + napi_valuetype valuetype = napi_undefined; // argv[0]:callback NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); @@ -93,46 +96,24 @@ 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"); - - 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; + ANS_LOGI("enter"); - 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}; - - napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + 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 = nullptr; + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "cancel", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -142,24 +123,18 @@ 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, asynccallbackinfo->info, Common::NapiGetNull(env)); - Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -172,7 +147,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,25 +156,22 @@ 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 = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); - napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); - - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "cancelAll", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -208,18 +180,17 @@ 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)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -232,7 +203,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 174867b4e3788011795f378021483b702382481f..09531dac60e207e0122387e0fc912d0a3b02ca27 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -18,11 +18,13 @@ #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" namespace OHOS { namespace NotificationNapi { +std::set> Common::wantAgent_; static napi_value GetIdByPublish(const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetSlotType(const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetNotificationIsOngoing(const napi_env &env, const napi_value &value, NotificationRequest &request); @@ -59,14 +61,14 @@ static napi_value GetNotificationIsCountDown( const napi_env &env, const napi_value &value, NotificationRequest &request); // static napi_value GetNotificationVisibleness( // const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationProgressBar( - const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationProgressBar( +// const napi_env &env, const napi_value &value, NotificationRequest &request); 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); @@ -99,14 +101,14 @@ Common::~Common() napi_value Common::NapiGetboolean(napi_env env, const bool &isValue) { - napi_value result = 0; + napi_value result = nullptr; napi_get_boolean(env, isValue, &result); return result; } napi_value Common::NapiGetNull(napi_env env) { - napi_value result = 0; + napi_value result = nullptr; napi_get_null(env, &result); return result; } @@ -121,9 +123,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); @@ -137,13 +155,13 @@ void Common::SetCallback( const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result) { ANS_LOGI("enter"); - napi_value undefined; + napi_value undefined = nullptr; napi_get_undefined(env, &undefined); - napi_value callback; - napi_value resultout; + napi_value callback = nullptr; + napi_value resultout = nullptr; napi_get_reference_value(env, callbackIn, &callback); - napi_value results[ARGS_TWO] = {0}; + napi_value results[ARGS_TWO] = {nullptr}; results[PARAM0] = GetCallbackErrorValue(env, errorCode); results[PARAM1] = result; NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &results[PARAM0], &resultout)); @@ -162,7 +180,7 @@ napi_value Common::JSParaError(const napi_env &env, const napi_ref &callback) if (callback) { return Common::NapiGetNull(env); } else { - napi_value promise = 0; + napi_value promise = nullptr; napi_deferred deferred = nullptr; napi_create_promise(env, &deferred, &promise); SetPromise(env, deferred, Common::NapiGetNull(env)); @@ -173,13 +191,13 @@ 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"); return NapiGetboolean(env, false); } - napi_value value; + napi_value value = nullptr; NotificationRequest request = notification->GetNotificationRequest(); if (!SetNotificationRequest(env, &request, result)) { return NapiGetboolean(env, false); @@ -217,7 +235,7 @@ napi_value Common::SetNotificationRequest( { ANS_LOGI("SetNotificationRequest start"); - napi_value value; + napi_value value = nullptr; if (request == nullptr) { ANS_LOGE("request is nullptr"); @@ -227,7 +245,7 @@ napi_value Common::SetNotificationRequest( // content: NotificationContent std::shared_ptr content = request->GetContent(); if (content) { - napi_value contentResult; + napi_value contentResult = nullptr; napi_create_object(env, &contentResult); if (!SetNotificationContent(env, content, contentResult)) { ANS_LOGE("SetNotificationContent call failed"); @@ -244,7 +262,7 @@ napi_value Common::SetNotificationRequest( napi_set_named_property(env, result, "id", value); // slotType?: SlotType - enum SlotType outType; + enum SlotType outType = SlotType::UNKNOWN_TYPE; if (!SlotTypeCToJS(request->GetSlotType(), outType)) { return NapiGetboolean(env, false); } @@ -278,7 +296,7 @@ napi_value Common::SetNotificationRequest( // wantAgent?: WantAgent std::shared_ptr agent = request->GetWantAgent(); if (agent) { - napi_value wantAgent; + napi_value wantAgent = nullptr; wantAgent = CreateWantAgentByJS(env, agent); napi_set_named_property(env, result, "wantAgent", wantAgent); } else { @@ -288,7 +306,7 @@ napi_value Common::SetNotificationRequest( // extraInfo ?: {[key:string] : any} std::shared_ptr additionalData = request->GetAdditionalData(); if (additionalData) { - napi_value extraInfo; + napi_value extraInfo = nullptr; extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); napi_set_named_property(env, result, "extraInfo", extraInfo); } @@ -317,7 +335,7 @@ napi_value Common::SetNotificationRequest( // removalWantAgent ?: WantAgent std::shared_ptr removalAgent = request->GetRemovalWantAgent(); if (removalAgent) { - napi_value wantAgent; + napi_value wantAgent = nullptr; wantAgent = CreateWantAgentByJS(env, removalAgent); napi_set_named_property(env, result, "removalWantAgent", wantAgent); } else { @@ -327,7 +345,7 @@ napi_value Common::SetNotificationRequest( // maxScreenWantAgent ? WantAgent std::shared_ptr maxScreenAgent = request->GetMaxScreenWantAgent(); if (maxScreenAgent) { - napi_value wantAgent; + napi_value wantAgent = nullptr; wantAgent = CreateWantAgentByJS(env, maxScreenAgent); napi_set_named_property(env, result, "maxScreenWantAgent", wantAgent); } else { @@ -339,7 +357,7 @@ napi_value Common::SetNotificationRequest( napi_set_named_property(env, result, "classification", value); // color ?: number - napi_create_int32(env, request->GetColor(), &value); + napi_create_uint32(env, request->GetColor(), &value); napi_set_named_property(env, result, "color", value); // colorEnabled ?: boolean @@ -363,17 +381,17 @@ napi_value Common::SetNotificationRequest( // napi_create_int32(env, visibleness, &value); // napi_set_named_property(env, result, "visibleness", value); - // progressValue ?: number - napi_create_int32(env, request->GetProgressValue(), &value); - napi_set_named_property(env, result, "progressValue", value); + // // progressValue ?: number + // napi_create_int32(env, request->GetProgressValue(), &value); + // napi_set_named_property(env, result, "progressValue", value); - // progressMaxValue ?: number - napi_create_int32(env, request->GetProgressMax(), &value); - napi_set_named_property(env, result, "progressMaxValue", value); + // // progressMaxValue ?: number + // napi_create_int32(env, request->GetProgressMax(), &value); + // napi_set_named_property(env, result, "progressMaxValue", value); - // isIndeterminate ?: boolean - napi_get_boolean(env, request->IsProgressIndeterminate(), &value); - napi_set_named_property(env, result, "isIndeterminate", value); + // // isIndeterminate ?: boolean + // napi_get_boolean(env, request->IsProgressIndeterminate(), &value); + // napi_set_named_property(env, result, "isIndeterminate", value); // statusBarText ?: string napi_create_string_utf8(env, request->GetStatusBarText().c_str(), NAPI_AUTO_LENGTH, &value); @@ -387,9 +405,9 @@ napi_value Common::SetNotificationRequest( // napi_get_boolean(env, request->IsOnlyLocal(), &value); // napi_set_named_property(env, result, "onlyLocal", value); - // sortingKey ?: string - napi_create_string_utf8(env, request->GetSortingKey().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "sortingKey", value); + // // sortingKey ?: string + // napi_create_string_utf8(env, request->GetSortingKey().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "sortingKey", value); // // messageUsers ?: Array // napi_value arr; @@ -425,12 +443,12 @@ napi_value Common::SetNotificationRequest( napi_set_named_property(env, result, "showDeliveryTime", value); // actionButtons?: Array - napi_value arr; + napi_value arr = nullptr; int count = 0; napi_create_array(env, &arr); for (auto vec : request->GetActionButtons()) { if (vec) { - napi_value actionButtonResult; + napi_value actionButtonResult = nullptr; napi_create_object(env, &actionButtonResult); if (SetNotificationActionButton(env, vec, actionButtonResult)) { napi_set_element(env, arr, count, actionButtonResult); @@ -472,21 +490,21 @@ napi_value Common::SetNotificationSortingMap( } size_t count = 0; - napi_value arrSortedHashCode; + napi_value arrSortedHashCode = nullptr; napi_create_array(env, &arrSortedHashCode); - napi_value sortingsResult; + napi_value sortingsResult = nullptr; napi_create_object(env, &sortingsResult); for (auto key : sortingMap->GetKey()) { NotificationSorting sorting; if (sortingMap->GetNotificationSorting(key, sorting)) { // sortedHashCode: Array - napi_value keyValue; + napi_value keyValue = nullptr; ANS_LOGI("sortingMap key = %{public}s", key.c_str()); napi_create_string_utf8(env, key.c_str(), NAPI_AUTO_LENGTH, &keyValue); napi_set_element(env, arrSortedHashCode, count, keyValue); // sortings:{[key : string] : NotificationSorting} - napi_value sortingResult; + napi_value sortingResult = nullptr; napi_create_object(env, &sortingResult); if (!SetNotificationSorting(env, sorting, sortingResult)) { ANS_LOGE("SetNotificationSorting call failed"); @@ -509,8 +527,8 @@ napi_value Common::SetNotificationSorting(const napi_env &env, const Notificatio ANS_LOGI("SetNotificationSorting start"); // slot: NotificationSlot - napi_value slotResult; - napi_value value = 0; + napi_value slotResult = nullptr; + napi_value value = nullptr; napi_create_object(env, &slotResult); if (!SetNotificationSlot(env, sorting.GetSlot(), slotResult)) { ANS_LOGE("SetNotificationSlot call failed"); @@ -555,12 +573,11 @@ 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"); - - napi_value value = 0; + ANS_LOGI("enter"); + napi_value value = nullptr; // type: SlotType; - enum SlotType outType; + enum SlotType outType = SlotType::UNKNOWN_TYPE; if (!SlotTypeCToJS(slot.GetType(), outType)) { return NapiGetboolean(env, false); } @@ -568,24 +585,28 @@ 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 napi_create_string_utf8(env, slot.GetDescription().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "desc", value); - // showBadgeFlag?: boolean + // badgeFlag?: boolean napi_get_boolean(env, slot.IsShowBadge(), &value); - napi_set_named_property(env, result, "showBadgeFlag", value); + napi_set_named_property(env, result, "badgeFlag", value); // bypassDnd?: boolean napi_get_boolean(env, slot.IsEnableBypassDnd(), &value); 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 @@ -605,7 +626,7 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl napi_set_named_property(env, result, "lightColor", value); // vibrationValues?: Array - napi_value arr; + napi_value arr = nullptr; napi_create_array(env, &arr); size_t count = 0; for (auto vec : slot.GetVibrationStyle()) { @@ -627,10 +648,10 @@ napi_value Common::SetNotificationContent( return NapiGetboolean(env, false); } - napi_value value; + napi_value value = nullptr; // contentType: ContentType; NotificationContent::Type type = content->GetContentType(); - ContentType outType; + ContentType outType = ContentType::NOTIFICATION_CONTENT_BASIC_TEXT; if (!ContentTypeCToJS(type, outType)) { return NapiGetboolean(env, false); } @@ -645,7 +666,7 @@ napi_value Common::SetNotificationContent( } if (outType == ContentType::NOTIFICATION_CONTENT_BASIC_TEXT) { // normal?: NotificationBasicContent - napi_value basicContentResult; + napi_value basicContentResult = nullptr; napi_create_object(env, &basicContentResult); if (SetNotificationBasicContent(env, basicContent.get(), basicContentResult)) { napi_set_named_property(env, result, "normal", basicContentResult); @@ -657,7 +678,7 @@ napi_value Common::SetNotificationContent( // longText?: NotificationLongTextContent OHOS::Notification::NotificationLongTextContent *longTextContent = static_cast(basicContent.get()); - napi_value longTextContentResult; + napi_value longTextContentResult = nullptr; napi_create_object(env, &longTextContentResult); if (SetNotificationLongTextContent(env, longTextContent, longTextContentResult)) { napi_set_named_property(env, result, "longText", longTextContentResult); @@ -669,7 +690,7 @@ napi_value Common::SetNotificationContent( // picture?: NotificationPictureContent OHOS::Notification::NotificationPictureContent *pictureContent = static_cast(basicContent.get()); - napi_value pictureContentResult; + napi_value pictureContentResult = nullptr; napi_create_object(env, &pictureContentResult); if (SetNotificationPictureContent(env, pictureContent, pictureContentResult)) { napi_set_named_property(env, result, "picture", pictureContentResult); @@ -680,7 +701,7 @@ napi_value Common::SetNotificationContent( // conversational?: NotificationConversationalContent OHOS::Notification::NotificationConversationalContent *conversationalContent = static_cast(basicContent.get()); - napi_value conversationalContentResult; + napi_value conversationalContentResult = nullptr; napi_create_object(env, &conversationalContentResult); if (SetNotificationConversationalContent(env, conversationalContent, conversationalContentResult)) { napi_set_named_property(env, result, "conversational", conversationalContentResult); @@ -691,7 +712,7 @@ napi_value Common::SetNotificationContent( // multiLine?: NotificationMultiLineContent OHOS::Notification::NotificationMultiLineContent *multiLineContent = static_cast(basicContent.get()); - napi_value multiLineContentResult; + napi_value multiLineContentResult = nullptr; napi_create_object(env, &multiLineContentResult); if (SetNotificationMultiLineContent(env, multiLineContent, multiLineContentResult)) { napi_set_named_property(env, result, "multiLine", multiLineContentResult); @@ -714,7 +735,7 @@ napi_value Common::SetNotificationBasicContent( return NapiGetboolean(env, false); } - napi_value value; + napi_value value = nullptr; // title: string; napi_create_string_utf8(env, basicContent->GetTitle().c_str(), NAPI_AUTO_LENGTH, &value); @@ -745,7 +766,7 @@ napi_value Common::SetNotificationLongTextContent( return NapiGetboolean(env, false); } - napi_value value; + napi_value value = nullptr; // longText: string napi_create_string_utf8(env, longTextContent->GetLongText().c_str(), NAPI_AUTO_LENGTH, &value); @@ -776,7 +797,7 @@ napi_value Common::SetNotificationPictureContent( return NapiGetboolean(env, false); } - napi_value value; + napi_value value = nullptr; // pictureId: number //c++ no do @@ -807,7 +828,7 @@ napi_value Common::SetNotificationConversationalContent(const napi_env &env, return NapiGetboolean(env, false); } - napi_value value; + napi_value value = nullptr; // conversationTitle: string napi_create_string_utf8(env, conversationalContent->GetConversationTitle().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "conversationTitle", value); @@ -817,7 +838,7 @@ napi_value Common::SetNotificationConversationalContent(const napi_env &env, napi_set_named_property(env, result, "conversationGroup", value); // messages: Array - napi_value arr; + napi_value arr = nullptr; int count = 0; napi_create_array(env, &arr); std::vector> messages = @@ -826,7 +847,7 @@ napi_value Common::SetNotificationConversationalContent(const napi_env &env, if (!vec) { continue; } - napi_value conversationalMessageResult; + napi_value conversationalMessageResult = nullptr; napi_create_object(env, &conversationalMessageResult); if (SetConversationalMessage(env, vec, conversationalMessageResult)) { napi_set_element(env, arr, count, conversationalMessageResult); @@ -836,7 +857,7 @@ napi_value Common::SetNotificationConversationalContent(const napi_env &env, napi_set_named_property(env, result, "messages", arr); // user: MessageUser - napi_value messageUserResult; + napi_value messageUserResult = nullptr; napi_create_object(env, &messageUserResult); if (!SetMessageUser(env, conversationalContent->GetMessageUser(), messageUserResult)) { messageUserResult = NapiGetNull(env); @@ -860,7 +881,7 @@ napi_value Common::SetNotificationMultiLineContent( return NapiGetboolean(env, false); } - napi_value value; + napi_value value = nullptr; // briefText: string napi_create_string_utf8(env, multiLineContent->GetBriefText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "briefText", value); @@ -870,7 +891,7 @@ napi_value Common::SetNotificationMultiLineContent( napi_set_named_property(env, result, "longTitle", value); // lines: Array - napi_value arr; + napi_value arr = nullptr; int count = 0; napi_create_array(env, &arr); for (auto vec : multiLineContent->GetAllLines()) { @@ -887,7 +908,7 @@ napi_value Common::SetMessageUser(const napi_env &env, const MessageUser &messag { ANS_LOGI("SetMessageUser start"); - napi_value value; + napi_value value = nullptr; // name: string napi_create_string_utf8(env, messageUser.GetName().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "name", value); @@ -922,7 +943,7 @@ napi_value Common::SetConversationalMessage(const napi_env &env, return NapiGetboolean(env, false); } - napi_value value; + napi_value value = nullptr; // text: string napi_create_string_utf8(env, conversationalMessage->GetText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "text", value); @@ -940,7 +961,7 @@ napi_value Common::SetConversationalMessage(const napi_env &env, napi_set_named_property(env, result, "uri", value); // sender: MessageUser; - napi_value messageUserResult; + napi_value messageUserResult = nullptr; napi_create_object(env, &messageUserResult); if (SetMessageUser(env, conversationalMessage->GetSender(), messageUserResult)) { messageUserResult = NapiGetNull(env); @@ -959,7 +980,7 @@ napi_value Common::SetNotificationActionButton( return NapiGetboolean(env, false); } - napi_value value; + napi_value value = nullptr; // title: string napi_create_string_utf8(env, actionButton->GetTitle().c_str(), NAPI_AUTO_LENGTH, &value); @@ -972,7 +993,7 @@ napi_value Common::SetNotificationActionButton( napi_set_named_property(env, result, "wantAgent", NapiGetNull(env)); return NapiGetboolean(env, true); } - napi_value wantAgent; + napi_value wantAgent = nullptr; wantAgent = CreateWantAgentByJS(env, agent); napi_set_named_property(env, result, "wantAgent", wantAgent); @@ -982,61 +1003,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, NotificationSubscribeInfo &subscriberInfo) { uint32_t length = 0; - size_t strLen; + size_t strLen = 0; bool hasProperty = false; - napi_valuetype valuetype; + bool isArray = false; + napi_valuetype valuetype = napi_undefined; + // 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 = nullptr; + 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 = nullptr; + 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.hasSubscribeInfo = 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 = nullptr; + // 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 = nullptr; + // 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.hasSubscribeInfo = 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 = nullptr; + 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.hasSubscribeInfo = true; } return NapiGetNull(env); @@ -1082,7 +1107,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; } @@ -1161,22 +1186,10 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value // return nullptr; // } - // progressValue?: number - // progressMaxValue?: number - // isIndeterminate?: boolean - if (GetNotificationProgressBar(env, value, request) == nullptr) { - return nullptr; - } - - // progressMaxValue?: number - // if (GetNotificationProgressMaxValueByPublish(env, value, notificationRequestData.progressMaxValue, request) == - // nullptr) { - // return nullptr; - // } - - // isIndeterminate?: boolean - // if (GetNotificationIsIndeterminateByPublish(env, value, notificationRequestData.isIndeterminate, request) == - // nullptr) { + // // progressValue?: number + // // progressMaxValue?: number + // // isIndeterminate?: boolean + // if (GetNotificationProgressBar(env, value, request) == nullptr) { // return nullptr; // } @@ -1190,10 +1203,10 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value // return nullptr; // } - // sortingKey?: string - if (GetNotificationSortingKey(env, value, request) == nullptr) { - return nullptr; - } + // // sortingKey?: string + // if (GetNotificationSortingKey(env, value, request) == nullptr) { + // return nullptr; + // } // label?: string if (GetNotificationLabel(env, value, request) == nullptr) { @@ -1227,13 +1240,12 @@ napi_value GetIdByPublish(const napi_env &env, const napi_value &value, Notifica { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - int32_t notificationId; + int32_t notificationId = 0; 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)); @@ -1253,20 +1265,19 @@ napi_value GetSlotType(const napi_env &env, const napi_value &value, Notificatio { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - int32_t slotType; + int32_t slotType = 0; 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)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, result, &slotType); - enum NotificationConstant::SlotType outType; + enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { return nullptr; } @@ -1283,61 +1294,58 @@ napi_value Common::GetNotificationContent(const napi_env &env, const napi_value { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - int32_t type; + int32_t type = 0; 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 = NotificationContent::Type::NONE; + 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"); @@ -1348,10 +1356,10 @@ napi_value GetNotificationIsOngoing(const napi_env &env, const napi_value &value { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - bool isOngoing; + bool isOngoing = false; NAPI_CALL(env, napi_has_named_property(env, value, "isOngoing", &hasProperty)); if (hasProperty) { @@ -1369,10 +1377,10 @@ napi_value GetNotificationIsUnremovable(const napi_env &env, const napi_value &v { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - bool isUnremovable; + bool isUnremovable = false; NAPI_CALL(env, napi_has_named_property(env, value, "isUnremovable", &hasProperty)); if (hasProperty) { @@ -1390,10 +1398,10 @@ napi_value GetNotificationDeliveryTime(const napi_env &env, const napi_value &va { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - int64_t deliveryTime; + int64_t deliveryTime = 0; NAPI_CALL(env, napi_has_named_property(env, value, "deliveryTime", &hasProperty)); if (hasProperty) { @@ -1411,10 +1419,10 @@ napi_value GetNotificationtapDismissed(const napi_env &env, const napi_value &va { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - bool tapDismissed; + bool tapDismissed = false; NAPI_CALL(env, napi_has_named_property(env, value, "tapDismissed", &hasProperty)); if (hasProperty) { @@ -1434,8 +1442,8 @@ napi_value Common::GetNotificationWantAgent(const napi_env &env, const napi_valu bool hasProperty = false; WantAgent::WantAgent *wantAgent = nullptr; - napi_value result; - napi_valuetype valuetype; + napi_value result = nullptr; + napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_has_named_property(env, value, "wantAgent", &hasProperty)); if (hasProperty) { @@ -1444,6 +1452,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); @@ -1457,8 +1466,8 @@ napi_value GetNotificationExtraInfo(const napi_env &env, const napi_value &value { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; NAPI_CALL(env, napi_has_named_property(env, value, "extraInfo", &hasProperty)); @@ -1484,8 +1493,8 @@ napi_value GetNotificationRemovalWantAgent(const napi_env &env, const napi_value bool hasProperty = false; WantAgent::WantAgent *wantAgent = nullptr; - napi_value result; - napi_valuetype valuetype; + napi_value result = nullptr; + napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_has_named_property(env, value, "removalWantAgent", &hasProperty)); if (hasProperty) { @@ -1494,6 +1503,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); @@ -1509,8 +1519,8 @@ napi_value GetNotificationMaxScreenWantAgent(const napi_env &env, const napi_val bool hasProperty = false; WantAgent::WantAgent *wantAgent = nullptr; - napi_value result; - napi_valuetype valuetype; + napi_value result = nullptr; + napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_has_named_property(env, value, "maxScreenWantAgent", &hasProperty)); if (hasProperty) { @@ -1519,6 +1529,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); @@ -1532,10 +1543,10 @@ napi_value GetNotificationAutoDeletedTime(const napi_env &env, const napi_value { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - int64_t autoDeletedTime; + int64_t autoDeletedTime = 0; NAPI_CALL(env, napi_has_named_property(env, value, "autoDeletedTime", &hasProperty)); if (hasProperty) { @@ -1554,8 +1565,8 @@ napi_value GetNotificationAutoDeletedTime(const napi_env &env, const napi_value // { // ANS_LOGI("enter"); -// napi_valuetype valuetype; -// napi_value result; +// napi_valuetype valuetype = napi_undefined; +// napi_value result = nullptr; // bool hasProperty = false; // char str[STR_MAX_SIZE] = {0}; // size_t strLen = 0; @@ -1578,8 +1589,8 @@ napi_value GetNotificationAutoDeletedTime(const napi_env &env, const napi_value // { // ANS_LOGI("enter"); -// napi_valuetype valuetype; -// napi_value result; +// napi_valuetype valuetype = napi_undefined; +// napi_value result = nullptr; // bool hasProperty = false; // char str[STR_MAX_SIZE] = {0}; // size_t strLen = 0; @@ -1602,10 +1613,10 @@ napi_value GetNotificationAutoDeletedTime(const napi_env &env, const napi_value // { // ANS_LOGI("enter"); -// napi_valuetype valuetype; -// napi_value result; +// napi_valuetype valuetype = napi_undefined; +// napi_value result = nullptr; // bool hasProperty = false; -// int32_t groupAlertType; +// int32_t groupAlertType = 0; // NAPI_CALL(env, napi_has_named_property(env, value, "groupAlertType", &hasProperty)); // if (hasProperty) { @@ -1624,10 +1635,10 @@ napi_value GetNotificationAutoDeletedTime(const napi_env &env, const napi_value // { // ANS_LOGI("enter"); -// napi_valuetype valuetype; -// napi_value result; +// napi_valuetype valuetype = napi_undefined; +// napi_value result = nullptr; // bool hasProperty = false; -// bool groupOverview; +// bool groupOverview = false; // NAPI_CALL(env, napi_has_named_property(env, value, "groupOverview", &hasProperty)); // if (hasProperty) { @@ -1641,13 +1652,12 @@ 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"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; @@ -1668,10 +1678,10 @@ napi_value GetNotificationColor(const napi_env &env, const napi_value &value, No { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - int32_t color; + int32_t color = 0; NAPI_CALL(env, napi_has_named_property(env, value, "color", &hasProperty)); if (hasProperty) { @@ -1679,6 +1689,7 @@ napi_value GetNotificationColor(const napi_env &env, const napi_value &value, No 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, &color); + NAPI_ASSERT(env, color >= 0, "Wrong argument type. Natural number expected."); request.SetColor(color); } @@ -1689,10 +1700,10 @@ napi_value GetNotificationColorEnabled(const napi_env &env, const napi_value &va { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - bool colorEnabled; + bool colorEnabled = false; NAPI_CALL(env, napi_has_named_property(env, value, "colorEnabled", &hasProperty)); if (hasProperty) { @@ -1710,10 +1721,10 @@ napi_value GetNotificationIsAlertOnce(const napi_env &env, const napi_value &val { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - bool isAlertOnce; + bool isAlertOnce = false; NAPI_CALL(env, napi_has_named_property(env, value, "isAlertOnce", &hasProperty)); if (hasProperty) { @@ -1731,10 +1742,10 @@ napi_value GetNotificationIsStopwatch(const napi_env &env, const napi_value &val { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - bool isStopwatch; + bool isStopwatch = false; NAPI_CALL(env, napi_has_named_property(env, value, "isStopwatch", &hasProperty)); if (hasProperty) { @@ -1752,10 +1763,10 @@ napi_value GetNotificationIsCountDown(const napi_env &env, const napi_value &val { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - bool isCountDown; + bool isCountDown = false; NAPI_CALL(env, napi_has_named_property(env, value, "isCountDown", &hasProperty)); if (hasProperty) { @@ -1774,10 +1785,10 @@ napi_value GetNotificationIsCountDown(const napi_env &env, const napi_value &val // { // ANS_LOGI("enter"); -// napi_valuetype valuetype; -// napi_value result; +// napi_valuetype valuetype = napi_undefined; +// napi_value result = nullptr; // bool hasProperty = false; -// int32_t visibleness; +// int32_t visibleness = 0; // NAPI_CALL(env, napi_has_named_property(env, value, "visibleness", &hasProperty)); // if (hasProperty) { @@ -1790,90 +1801,44 @@ 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; - 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); - } - - return Common::NapiGetNull(env); -} -// napi_value GetNotificationProgressMaxValueByPublish( -// const napi_env &env, const napi_value &value, int32_t &progressMaxValue, NotificationRequest &request) +// napi_value GetNotificationProgressBar(const napi_env &env, const napi_value &value, NotificationRequest &request) // { // ANS_LOGI("enter"); -// napi_valuetype valuetype; -// napi_value result; +// napi_valuetype valuetype = napi_undefined; +// napi_value result = nullptr; // bool hasProperty = false; +// int32_t progressValue = 0; +// int32_t progressMaxValue = 0; +// bool isIndeterminate = false; + +// 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); +// } // 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_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number 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_valuetype valuetype; -// napi_value result; -// bool hasProperty = false; - // 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_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); // } @@ -1881,8 +1846,8 @@ napi_value GetNotificationStatusBarText(const napi_env &env, const napi_value &v { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; @@ -1896,7 +1861,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); } @@ -1905,10 +1869,10 @@ napi_value GetNotificationStatusBarText(const napi_env &env, const napi_value &v // { // ANS_LOGI("enter"); -// napi_valuetype valuetype; -// napi_value result; +// napi_valuetype valuetype = napi_undefined; +// napi_value result = nullptr; // bool hasProperty = false; -// bool onlyLocal; +// bool onlyLocal = false; // NAPI_CALL(env, napi_has_named_property(env, value, "onlyLocal", &hasProperty)); // if (hasProperty) { @@ -1922,35 +1886,34 @@ 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) -{ - ANS_LOGI("enter"); +// napi_value GetNotificationSortingKey(const napi_env &env, const napi_value &value, NotificationRequest &request) +// { +// ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; - bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; - size_t strLen = 0; +// napi_valuetype valuetype = napi_undefined; +// napi_value result = nullptr; +// bool hasProperty = false; +// char str[STR_MAX_SIZE] = {0}; +// size_t strLen = 0; - NAPI_CALL(env, napi_has_named_property(env, value, "sortingKey", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, value, "sortingKey", &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)); - request.SetSortingKey(str); - } +// NAPI_CALL(env, napi_has_named_property(env, value, "sortingKey", &hasProperty)); +// if (hasProperty) { +// napi_get_named_property(env, value, "sortingKey", &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)); +// request.SetSortingKey(str); +// } - return Common::NapiGetNull(env); -} +// return Common::NapiGetNull(env); +// } napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; @@ -1964,7 +1927,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); } @@ -1972,10 +1934,10 @@ napi_value GetNotificationBadgeIconStyle(const napi_env &env, const napi_value & { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - int32_t badgeIconStyle; + int32_t badgeIconStyle = 0; NAPI_CALL(env, napi_has_named_property(env, value, "badgeIconStyle", &hasProperty)); if (hasProperty) { @@ -1994,8 +1956,8 @@ napi_value GetNotificationBadgeIconStyle(const napi_env &env, const napi_value & // { // ANS_LOGI("enter"); -// napi_valuetype valuetype; -// napi_value result; +// napi_valuetype valuetype = napi_undefined; +// napi_value result = nullptr; // bool hasProperty = false; // char str[STR_MAX_SIZE] = {0}; // size_t strLen = 0; @@ -2017,16 +1979,16 @@ napi_value GetNotificationShowDeliveryTime(const napi_env &env, const napi_value { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value result; + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; bool hasProperty = false; - bool showDeliveryTime; + bool showDeliveryTime = false; NAPI_CALL(env, napi_has_named_property(env, value, "showDeliveryTime", &hasProperty)); 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); } @@ -2040,55 +2002,69 @@ napi_value GetNotificationNotificationActionButtons( ANS_LOGI("enter"); bool isArray = false; - napi_valuetype valuetype; - napi_value actionButtons; + napi_valuetype valuetype = napi_undefined; + napi_value actionButtons = nullptr; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; uint32_t length = 0; bool hasProperty = false; - napi_value titelActionButton, wantAgentActionButton; + napi_value titelActionButton = nullptr; + napi_value wantAgentActionButton = nullptr; std::string title; 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 = nullptr; + 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); @@ -2098,18 +2074,21 @@ napi_value GetNotificationContentType(const napi_env &env, const napi_value &res { ANS_LOGI("enter"); - napi_value contentResult; - napi_valuetype valuetype; + napi_value contentResult = nullptr; + napi_valuetype valuetype = napi_undefined; 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); } @@ -2117,55 +2096,66 @@ napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &re { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value contentResult, basicContentResult; + napi_valuetype valuetype = napi_undefined; + napi_value contentResult = nullptr; + napi_value basicContentResult = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; NAPI_CALL(env, napi_has_named_property(env, result, "normal", &hasProperty)); - if (hasProperty) { - 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."); + NAPI_ASSERT(env, hasProperty, "Property normal expected."); + 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_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "title", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + // title: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "title", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "text", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + // text: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "text", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - normalContent->SetAdditionalText(str); - ANS_LOGI("normal::additionalText = %{public}s", str); - } - request.SetContent(std::make_shared(normalContent)); + // additionalText?: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + normalContent->SetAdditionalText(str); + ANS_LOGI("normal::additionalText = %{public}s", str); } + request.SetContent(std::make_shared(normalContent)); + return Common::NapiGetNull(env); } @@ -2173,327 +2163,395 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value contentResult, longContentResult, basicContentResult; + napi_valuetype valuetype = napi_undefined; + napi_value contentResult = nullptr; + napi_value longContentResult = nullptr; + napi_value basicContentResult = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; NAPI_CALL(env, napi_has_named_property(env, result, "longText", &hasProperty)); - if (hasProperty) { - 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."); - - NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "title", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + NAPI_ASSERT(env, hasProperty, "Property longText expected."); - NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "text", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + 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."); - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - longContent->SetAdditionalText(str); - ANS_LOGI("longText::additionalText = %{public}s", str); - } + std::shared_ptr longContent = + std::make_shared(); + if (longContent == nullptr) { + ANS_LOGE("longContent is null"); + return nullptr; + } - 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)); - longContent->SetLongText(str); - ANS_LOGI("longText::longText = %{public}s", str); - } + // title: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "title", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "briefText", &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)); - longContent->SetBriefText(str); - ANS_LOGI("longText::briefText = %{public}s", str); - } + // text: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "text", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "expandedTitle", &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)); - longContent->SetExpandedTitle(str); - ANS_LOGI("longText::expandedTitle = %{public}s", str); - } - request.SetContent(std::make_shared(longContent)); + // additionalText?: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + longContent->SetAdditionalText(str); + ANS_LOGI("longText::additionalText = %{public}s", str); } - return Common::NapiGetNull(env); -} + // 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, 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); + 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)); + 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); + 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)); + 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"); - napi_valuetype valuetype; - napi_value contentResult; - napi_value pictureContentResult; - napi_value basicContentResult; + napi_valuetype valuetype = napi_undefined; + napi_value contentResult = nullptr; + napi_value pictureContentResult = nullptr; + napi_value basicContentResult = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; NAPI_CALL(env, napi_has_named_property(env, result, "picture", &hasProperty)); - if (hasProperty) { - 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."); + NAPI_ASSERT(env, hasProperty, "Property picture expected."); + 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."); - NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "title", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + std::shared_ptr pictureContent = + std::make_shared(); + if (pictureContent == nullptr) { + ANS_LOGE("pictureContent is null"); + return nullptr; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "text", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + // title: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "title", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - pictureContent->SetAdditionalText(str); - ANS_LOGI("pictureText::additionalText = %{public}s", str); - } + // text: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "text", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - 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); - } + // additionalText?: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + pictureContent->SetAdditionalText(str); + ANS_LOGI("pictureText::additionalText = %{public}s", str); + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "briefText", &pictureContentResult); - NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + // briefText: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "briefText", &pictureContentResult); + NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "expandedTitle", &pictureContentResult); - NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + // expandedTitle: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "expandedTitle", &pictureContentResult); + NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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 + // bigPicture: image.PixelMap do - request.SetContent(std::make_shared(pictureContent)); - } + request.SetContent(std::make_shared(pictureContent)); 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; + napi_valuetype valuetype = napi_undefined; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; 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_value nameResult = nullptr; + 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_value uriResult = nullptr; + 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_value importantResult = nullptr; + 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_value machineResult = nullptr; + 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_value keyResult = nullptr; + 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"); - napi_valuetype valuetype; + napi_valuetype valuetype = napi_undefined; 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_value textResult = nullptr; + 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) { - napi_value timestampResult; + napi_value timestampResult = nullptr; napi_get_named_property(env, conversationalMessage, "timestamp", ×tampResult); NAPI_CALL(env, napi_typeof(env, timestampResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int64(env, timestampResult, ×tamp); ANS_LOGI("conversationalMessage::timestamp = %{public}" PRId64, timestamp); + } else { + ANS_LOGE("Property timestamp expected."); } + // mimeType: string NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "mimeType", &hasProperty)); if (hasProperty) { - napi_value mimeTypeResult; + napi_value mimeTypeResult = nullptr; napi_get_named_property(env, conversationalMessage, "mimeType", &mimeTypeResult); NAPI_CALL(env, napi_typeof(env, mimeTypeResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); 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) { - napi_value uriResult; + napi_value uriResult = nullptr; napi_get_named_property(env, conversationalMessage, "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 = 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) { - napi_value senderResult; + napi_value senderResult = nullptr; 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); } @@ -2502,198 +2560,247 @@ napi_value GetNotificationConversationalContent( { ANS_LOGI("enter"); - napi_valuetype valuetype; - napi_value contentResult; - napi_value conversationalContentResult; - napi_value basicContentResult; + napi_valuetype valuetype = napi_undefined; + napi_value contentResult = nullptr; + napi_value conversationalContentResult = nullptr; + napi_value basicContentResult = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; MessageUser user; NAPI_CALL(env, napi_has_named_property(env, result, "conversational", &hasProperty)); - if (hasProperty) { + NAPI_ASSERT(env, hasProperty, "Property conversational expected."); + 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."); - napi_get_named_property(env, result, "conversational", &contentResult); - NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + // user: MessageUser + NAPI_CALL(env, napi_has_named_property(env, contentResult, "user", &hasProperty)); + if (hasProperty) { + napi_value userResult = nullptr; + 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."); - - // user: MessageUser - NAPI_CALL(env, napi_has_named_property(env, contentResult, "user", &hasProperty)); - if (hasProperty) { - napi_value userResult; - 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)) { - return nullptr; - } - } - - std::shared_ptr conversationalContent = - std::make_shared(user); - if (conversationalContent == nullptr) { - ANS_LOGE("conversationalContent is null"); + if (!GetMessageUser(env, userResult, user)) { return nullptr; } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "title", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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 user expected."); + return nullptr; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "text", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + std::shared_ptr conversationalContent = + std::make_shared(user); + if (conversationalContent == nullptr) { + ANS_LOGE("conversationalContent is null"); + return nullptr; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - conversationalContent->SetAdditionalText(str); - ANS_LOGI("conversationalText::additionalText = %{public}s", str); - } + // title: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "title", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationTitle", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "conversationTitle", &conversationalContentResult); - NAPI_CALL(env, napi_typeof(env, conversationalContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL( - env, napi_get_value_string_utf8(env, conversationalContentResult, str, STR_MAX_SIZE - 1, &strLen)); - conversationalContent->SetConversationTitle(str); - ANS_LOGI("conversationalText::conversationTitle = %{public}s", str); - } + // text: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "text", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationGroup", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "conversationGroup", &conversationalContentResult); - NAPI_CALL(env, napi_typeof(env, conversationalContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); - bool conversationGroup = false; - napi_get_value_bool(env, conversationalContentResult, &conversationGroup); - conversationalContent->SetConversationGroup(conversationGroup); - ANS_LOGI("conversationalText::conversationGroup = %{public}d", conversationGroup); - } + // additionalText?: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + conversationalContent->SetAdditionalText(str); + ANS_LOGI("conversationalText::additionalText = %{public}s", str); + } - 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); - } - } else { + // conversationTitle: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationTitle", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "conversationTitle", &conversationalContentResult); + NAPI_CALL(env, napi_typeof(env, conversationalContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(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); + NAPI_CALL(env, napi_typeof(env, conversationalContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + bool conversationGroup = false; + 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); + 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 = nullptr; + 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); } - request.SetContent(std::make_shared(conversationalContent)); + } 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"); - napi_valuetype valuetype; - napi_value contentResult, multiLineContentResult, basicContentResult; + napi_valuetype valuetype = napi_undefined; + napi_value contentResult = nullptr; + napi_value multiLineContentResult = nullptr; + napi_value basicContentResult = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; 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."); + NAPI_ASSERT(env, hasProperty, "Property multiLine expected."); + 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."); - NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "title", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + std::shared_ptr multiLineContent = + std::make_shared(); + if (multiLineContent == nullptr) { + ANS_LOGE("multiLineContent is null"); + return nullptr; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "text", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + // title: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "title", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - multiLineContent->SetAdditionalText(str); - ANS_LOGI("multiLine::additionalText = %{public}s", str); - } + // text: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "text", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "briefText", &multiLineContentResult); - NAPI_CALL(env, napi_typeof(env, multiLineContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + // additionalText?: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + multiLineContent->SetAdditionalText(str); + ANS_LOGI("multiLine::additionalText = %{public}s", str); + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "longTitle", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "longTitle", &multiLineContentResult); - NAPI_CALL(env, napi_typeof(env, multiLineContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - 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); - } + // briefText: string; + NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "briefText", &multiLineContentResult); + NAPI_CALL(env, napi_typeof(env, multiLineContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - NAPI_CALL(env, napi_has_named_property(env, contentResult, "lines", &hasProperty)); - if (hasProperty) { - if (GetNotificationMultiLineContentLines(env, contentResult, multiLineContent) == nullptr) { - 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); + NAPI_CALL(env, napi_typeof(env, multiLineContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + 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; + } - request.SetContent(std::make_shared(multiLineContent)); + // 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)); + return Common::NapiGetNull(env); } @@ -2703,71 +2810,77 @@ napi_value GetNotificationMultiLineContentLines(const napi_env &env, const napi_ ANS_LOGI("enter"); bool isArray = false; - napi_valuetype valuetype; - napi_value multilines; + napi_valuetype valuetype = napi_undefined; + napi_value multilines = nullptr; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; uint32_t length = 0; 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 = nullptr; + 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; - napi_valuetype valuetype; + napi_valuetype valuetype = napi_undefined; bool hasProperty = false; size_t strLen = 0; uint32_t length = 0; // 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; + enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; if (!SlotTypeJSToC(SlotType(slotType), outType)) { return nullptr; } 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,23 +2889,23 @@ napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &sl slot.SetDescription(desc); } - // showBadgeFlag?: boolean - NAPI_CALL(env, napi_has_named_property(env, result, "showBadgeFlag", &hasProperty)); + // badgeFlag?: boolean + NAPI_CALL(env, napi_has_named_property(env, value, "badgeFlag", &hasProperty)); if (hasProperty) { - bool showBadgeFlag = false; - napi_get_named_property(env, result, "showBadgeFlag", &nobj); + bool badgeFlag = false; + napi_get_named_property(env, value, "badgeFlag", &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); - ANS_LOGI("showBadgeFlag is: %{public}d", showBadgeFlag); - slot.EnableBadge(showBadgeFlag); + napi_get_value_bool(env, nobj, &badgeFlag); + ANS_LOGI("badgeFlag is: %{public}d", badgeFlag); + slot.EnableBadge(badgeFlag); } // 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); @@ -2801,10 +2914,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); @@ -2813,10 +2926,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); @@ -2825,11 +2938,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)); @@ -2839,10 +2952,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); @@ -2851,10 +2964,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); @@ -2863,29 +2976,89 @@ 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}" PRId64, 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 = nullptr; + 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}" PRId64, 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_undefined; + napi_value result = nullptr; + + 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; + NAPI_CALL(env, napi_has_named_property(env, value, "uid", &hasProperty)); + if (hasProperty) { + 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_undefined; + napi_value result = nullptr; + + // 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); } @@ -2898,20 +3071,20 @@ bool Common::ContentTypeJSToC(const enum ContentType &inType, enum NotificationC case ContentType::NOTIFICATION_CONTENT_LONG_TEXT: outType = NotificationContent::Type::LONG_TEXT; break; - case ContentType::NOTIFICATION_CONTENT_PICTURE: - outType = NotificationContent::Type::PICTURE; - break; - case ContentType::NOTIFICATION_CONTENT_CONVERSATION: - outType = NotificationContent::Type::CONVERSATION; - break; + // case ContentType::NOTIFICATION_CONTENT_PICTURE: + // outType = NotificationContent::Type::PICTURE; + // break; + // case ContentType::NOTIFICATION_CONTENT_CONVERSATION: + // outType = NotificationContent::Type::CONVERSATION; + // break; case ContentType::NOTIFICATION_CONTENT_MULTILINE: outType = NotificationContent::Type::MULTILINE; break; - case ContentType::NOTIFICATION_CONTENT_MEDIA: - outType = NotificationContent::Type::MEDIA; - break; + // case ContentType::NOTIFICATION_CONTENT_MEDIA: + // 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; @@ -2926,20 +3099,20 @@ bool Common::ContentTypeCToJS(const enum NotificationContent::Type &inType, enum case NotificationContent::Type::LONG_TEXT: outType = ContentType::NOTIFICATION_CONTENT_LONG_TEXT; break; - case NotificationContent::Type::PICTURE: - outType = ContentType::NOTIFICATION_CONTENT_PICTURE; - break; - case NotificationContent::Type::CONVERSATION: - outType = ContentType::NOTIFICATION_CONTENT_CONVERSATION; - break; + // case NotificationContent::Type::PICTURE: + // outType = ContentType::NOTIFICATION_CONTENT_PICTURE; + // break; + // case NotificationContent::Type::CONVERSATION: + // outType = ContentType::NOTIFICATION_CONTENT_CONVERSATION; + // break; case NotificationContent::Type::MULTILINE: outType = ContentType::NOTIFICATION_CONTENT_MULTILINE; break; - case NotificationContent::Type::MEDIA: - outType = ContentType::NOTIFICATION_CONTENT_MEDIA; - break; + // case NotificationContent::Type::MEDIA: + // 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; @@ -2962,7 +3135,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; @@ -2987,7 +3160,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; @@ -3024,7 +3248,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; @@ -3049,7 +3273,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; @@ -3061,6 +3285,8 @@ napi_value Common::CreateWantAgentByJS(const napi_env &env, const std::shared_pt ANS_LOGI("agent is nullptr"); return nullptr; } + + wantAgent_.insert(agent); napi_value wantAgent = nullptr; napi_value wantAgentClass = nullptr; napi_define_class(env, @@ -3076,7 +3302,24 @@ napi_value Common::CreateWantAgentByJS(const napi_env &env, const std::shared_pt nullptr, &wantAgentClass); napi_new_instance(env, wantAgentClass, 0, nullptr, &wantAgent); - napi_wrap(env, wantAgent, (void *)agent.get(), [](napi_env env, void *data, void *hint) {}, nullptr, nullptr); + napi_wrap(env, + wantAgent, + (void *)agent.get(), + [](napi_env env, void *data, void *hint) { + WantAgent::WantAgent *objectInfo = (WantAgent::WantAgent *)data; + ANS_LOGI("CreateWantAgentByJS this = %{public}p", objectInfo); + + if (objectInfo) { + for (auto it = wantAgent_.begin(); it != wantAgent_.end(); ++it) { + if ((*it).get() == objectInfo) { + wantAgent_.erase(it); + break; + } + } + } + }, + nullptr, + nullptr); return wantAgent; } diff --git a/interfaces/kits/napi/ans/src/constant.cpp b/interfaces/kits/napi/ans/src/constant.cpp index 7744cfa77e0a9667bf8a08a9e3db28361352b8cc..3b16f77347adcb60d7624b96efbb6182fe5f233c 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__); @@ -123,7 +144,7 @@ napi_value InputsSourceInit(napi_env env, napi_value exports) return exports; } -napi_value DisturbModeInit(napi_env env, napi_value exports) +napi_value DoNotDisturbMode(napi_env env, napi_value exports) { ANS_LOGI("%{public}s, called", __func__); @@ -137,7 +158,7 @@ napi_value DisturbModeInit(napi_env env, napi_value exports) SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_ALARMS, "ALLOW_ALARMS"); napi_property_descriptor exportFuncs[] = { - DECLARE_NAPI_PROPERTY("DisturbMode", obj), + DECLARE_NAPI_PROPERTY("DoNotDisturbMode", obj), }; napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); @@ -191,9 +212,10 @@ 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); + DoNotDisturbMode(env, exports); InputEditTypeInit(env, exports); ContentTypeInit(env, exports); return exports; diff --git a/interfaces/kits/napi/ans/src/create_subscriber.cpp b/interfaces/kits/napi/ans/src/create_subscriber.cpp deleted file mode 100644 index 28360ea0abc1453a089559dfa91f445199b7d1ea..0000000000000000000000000000000000000000 --- a/interfaces/kits/napi/ans/src/create_subscriber.cpp +++ /dev/null @@ -1,892 +0,0 @@ -/* - * 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 "create_subscriber.h" - -namespace OHOS { -namespace NotificationNapi { -const int ON_MAX_PARA = 2; -const int OFF_MAX_PARA = 1; -const int NO_DELETE_REASON = -1; -const std::string CONSUME = "consume"; -const std::string CANCEL = "cancel"; -const std::string UPDATE = "update"; -const std::string SUBSCRIBE = "subscribe"; -const std::string UNSUBSCRIBE = "unsubscribe"; -const std::string DIE = "die"; -const std::string DISTURB_MODE_CHANGE = "disturbModeChange"; - -struct AsyncCallbackInfoOff { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = 0; - SubscriberInstance *objectInfo; - std::string type; -}; - -struct NotificationReceiveDataWorker { - napi_env env; - napi_ref ref = 0; - std::shared_ptr request = nullptr; - std::shared_ptr sortingMap = nullptr; - int deleteReason = 0; - int result = 0; - int disturbMode = 0; -}; - -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"); - if (request == nullptr) { - ANS_LOGE("request is null"); - return Common::NapiGetboolean(env, false); - } - - if (sortingMap == nullptr) { - ANS_LOGE("sortingMap is null"); - return Common::NapiGetboolean(env, false); - } - - // request: NotificationRequest - napi_value requestResult; - napi_create_object(env, &requestResult); - if (!Common::SetNotification(env, request.get(), requestResult)) { - ANS_LOGE("SetNotification call failed"); - return Common::NapiGetboolean(env, false); - } - napi_set_named_property(env, result, "request", requestResult); - - // sortingMap?: NotificationSortingMap - napi_value sortingMapResult; - napi_create_object(env, &sortingMapResult); - if (!Common::SetNotificationSortingMap(env, sortingMap, sortingMapResult)) { - ANS_LOGE("SetNotificationSortingMap call failed"); - return Common::NapiGetboolean(env, false); - } - napi_set_named_property(env, result, "sortingMap", sortingMapResult); - - // reason?: number - if (deleteReason != NO_DELETE_REASON) { - napi_value value = 0; - int outReason = 0; - if (!Common::ReasonCToJS(deleteReason, outReason)) { - return Common::NapiGetboolean(env, false); - } - napi_create_int32(env, outReason, &value); - napi_set_named_property(env, result, "reason", value); - } - - return Common::NapiGetboolean(env, true); -} - -SubscriberInstance::SubscriberInstance() -{} - -SubscriberInstance::~SubscriberInstance() -{} - -void SubscriberInstance::OnCanceled(const std::shared_ptr &request) -{} - -void SubscriberInstance::OnCanceled(const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason) -{ - ANS_LOGI("OnCanceled start"); - - if (canceCallbackInfo_.ref == nullptr) { - ANS_LOGI("cancel callback unset"); - return; - } - - if (request == nullptr) { - ANS_LOGE("request is null"); - return; - } - - if (sortingMap == nullptr) { - ANS_LOGE("sortingMap is null"); - return; - } - ANS_LOGI("OnCanceled NotificationId = %{public}d", request->GetNotificationRequest().GetNotificationId()); - ANS_LOGI("OnCanceled sortingMap size = %{public}zu", sortingMap->GetKey().size()); - ANS_LOGI("OnCanceled deleteReason = %{public}d", deleteReason); - - uv_loop_s *loop = nullptr; -#if NAPI_VERSION >= 2 - napi_get_uv_event_loop(canceCallbackInfo_.env, &loop); -#endif // NAPI_VERSION >= 2 - - NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); - dataWorker->request = request; - dataWorker->sortingMap = sortingMap; - dataWorker->deleteReason = deleteReason; - dataWorker->env = canceCallbackInfo_.env; - dataWorker->ref = canceCallbackInfo_.ref; - - uv_work_t *work = new uv_work_t; - work->data = (void *)dataWorker; - - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnCanceled uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - napi_value result; - napi_create_object(dataWorkerData->env, &result); - int error = 0; - if (!SetSubscribeCallbackData(dataWorkerData->env, - dataWorkerData->request, - dataWorkerData->sortingMap, - dataWorkerData->deleteReason, - result)) { - result = Common::NapiGetNull(dataWorkerData->env); - error = ERROR; - } else { - error = NO_ERROR; - } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); -} - -void SubscriberInstance::OnConsumed(const std::shared_ptr &request) -{} - -void SubscriberInstance::OnConsumed(const std::shared_ptr &request, - const std::shared_ptr &sortingMap) -{ - ANS_LOGI("OnConsumed start"); - - if (consumeCallbackInfo_.ref == nullptr) { - ANS_LOGI("consume callback unset"); - return; - } - - if (request == nullptr) { - ANS_LOGE("request is null"); - return; - } - - if (sortingMap == nullptr) { - ANS_LOGE("sortingMap is null"); - return; - } - ANS_LOGI("OnConsumed NotificationId = %{public}d", request->GetNotificationRequest().GetNotificationId()); - ANS_LOGI("OnConsumed sortingMap size = %{public}zu", sortingMap->GetKey().size()); - - uv_loop_s *loop = nullptr; -#if NAPI_VERSION >= 2 - napi_get_uv_event_loop(consumeCallbackInfo_.env, &loop); -#endif // NAPI_VERSION >= 2 - - NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); - dataWorker->request = request; - dataWorker->sortingMap = sortingMap; - dataWorker->env = consumeCallbackInfo_.env; - dataWorker->ref = consumeCallbackInfo_.ref; - - uv_work_t *work = new (std::nothrow) uv_work_t; - work->data = (void *)dataWorker; - - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnConsumed uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - napi_value result; - napi_create_object(dataWorkerData->env, &result); - int error = 0; - if (!SetSubscribeCallbackData(dataWorkerData->env, - dataWorkerData->request, - dataWorkerData->sortingMap, - NO_DELETE_REASON, - result)) { - result = Common::NapiGetNull(dataWorkerData->env); - error = ERROR; - } else { - error = NO_ERROR; - } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); -} - -void SubscriberInstance::OnUpdate(const std::shared_ptr &sortingMap) -{ - ANS_LOGI("OnUpdate start"); - - if (updateCallbackInfo_.ref == nullptr) { - ANS_LOGI("update callback unset"); - return; - } - - if (sortingMap == nullptr) { - ANS_LOGE("sortingMap is null"); - return; - } - ANS_LOGI("OnUpdate sortingMap size = %{public}zu", sortingMap->GetKey().size()); - - uv_loop_s *loop = nullptr; -#if NAPI_VERSION >= 2 - napi_get_uv_event_loop(updateCallbackInfo_.env, &loop); -#endif // NAPI_VERSION >= 2 - - NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); - dataWorker->sortingMap = sortingMap; - dataWorker->env = updateCallbackInfo_.env; - dataWorker->ref = updateCallbackInfo_.ref; - - uv_work_t *work = new (std::nothrow) uv_work_t; - work->data = (void *)dataWorker; - - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnUpdate uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - napi_value result; - napi_create_object(dataWorkerData->env, &result); - int error = 0; - if (!Common::SetNotificationSortingMap(dataWorkerData->env, dataWorkerData->sortingMap, result)) { - result = Common::NapiGetNull(dataWorkerData->env); - error = ERROR; - } else { - error = NO_ERROR; - } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); -} - -void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult result) -{ - ANS_LOGI("OnSubscribeResult start"); - - if (subscribeCallbackInfo_.ref == nullptr) { - ANS_LOGI("subscribe callback unset"); - return; - } - ANS_LOGI("OnSubscribeResult result = %{public}d", result); - - uv_loop_s *loop = nullptr; -#if NAPI_VERSION >= 2 - napi_get_uv_event_loop(subscribeCallbackInfo_.env, &loop); -#endif // NAPI_VERSION >= 2 - - NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); - dataWorker->result = (int)result; - dataWorker->env = subscribeCallbackInfo_.env; - dataWorker->ref = subscribeCallbackInfo_.ref; - - uv_work_t *work = new (std::nothrow) uv_work_t; - work->data = (void *)dataWorker; - - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnSubscribeResult uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - // result: number - napi_value result; - napi_create_int32(dataWorkerData->env, dataWorkerData->result, &result); - - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); -} - -void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) -{ - ANS_LOGI("OnUnsubscribeResult start"); - - if (unsubscribeCallbackInfo_.ref == nullptr) { - ANS_LOGI("unsubscribe callback unset"); - return; - } - ANS_LOGI("OnUnsubscribeResult result = %{public}d", result); - - uv_loop_s *loop = nullptr; -#if NAPI_VERSION >= 2 - napi_get_uv_event_loop(unsubscribeCallbackInfo_.env, &loop); -#endif // NAPI_VERSION >= 2 - - NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); - dataWorker->result = (int)result; - dataWorker->env = unsubscribeCallbackInfo_.env; - dataWorker->ref = unsubscribeCallbackInfo_.ref; - - uv_work_t *work = new (std::nothrow) uv_work_t; - work->data = (void *)dataWorker; - - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnUnsubscribeResult uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - // result: number - napi_value result; - napi_create_int32(dataWorkerData->env, dataWorkerData->result, &result); - - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); -} - -void SubscriberInstance::OnDied() -{ - ANS_LOGI("OnDied start"); - - if (dieCallbackInfo_.ref == nullptr) { - ANS_LOGE("die callback unset"); - return; - } - - uv_loop_s *loop = nullptr; -#if NAPI_VERSION >= 2 - napi_get_uv_event_loop(dieCallbackInfo_.env, &loop); -#endif // NAPI_VERSION >= 2 - - NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); - dataWorker->env = dieCallbackInfo_.env; - dataWorker->ref = dieCallbackInfo_.ref; - - uv_work_t *work = new (std::nothrow) uv_work_t; - work->data = (void *)dataWorker; - - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnDied uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - - Common::SetCallback( - dataWorkerData->env, dataWorkerData->ref, NO_ERROR, Common::NapiGetNull(dataWorkerData->env)); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); -} - -void SubscriberInstance::OnDisturbModeChanged(int disturbMode) -{ - ANS_LOGI("OnDisturbModeChanged start"); - - if (disturbModeCallbackInfo_.ref == nullptr) { - ANS_LOGI("disturbModeChange callback unset"); - return; - } - ANS_LOGI("OnDisturbModeChanged disturbMode = %{public}d", disturbMode); - - uv_loop_s *loop = nullptr; -#if NAPI_VERSION >= 2 - napi_get_uv_event_loop(disturbModeCallbackInfo_.env, &loop); -#endif // NAPI_VERSION >= 2 - - NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); - dataWorker->disturbMode = disturbMode; - dataWorker->env = disturbModeCallbackInfo_.env; - dataWorker->ref = disturbModeCallbackInfo_.ref; - - uv_work_t *work = new (std::nothrow) uv_work_t; - work->data = (void *)dataWorker; - - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnDisturbModeChanged uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - // disturbMode: number - napi_value result; - napi_create_int32(dataWorkerData->env, dataWorkerData->disturbMode, &result); - - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); -} - -void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref) -{ - canceCallbackInfo_.env = env; - canceCallbackInfo_.ref = ref; -} - -void SubscriberInstance::SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref) -{ - consumeCallbackInfo_.env = env; - consumeCallbackInfo_.ref = ref; -} - -void SubscriberInstance::SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref) -{ - updateCallbackInfo_.env = env; - updateCallbackInfo_.ref = ref; -} - -void SubscriberInstance::SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref) -{ - subscribeCallbackInfo_.env = env; - subscribeCallbackInfo_.ref = ref; -} - -void SubscriberInstance::SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref) -{ - unsubscribeCallbackInfo_.env = env; - unsubscribeCallbackInfo_.ref = ref; -} - -void SubscriberInstance::SetDieCallbackInfo(const napi_env &env, const napi_ref &ref) -{ - dieCallbackInfo_.env = env; - dieCallbackInfo_.ref = ref; -} - -void SubscriberInstance::SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref) -{ - disturbModeCallbackInfo_.env = env; - disturbModeCallbackInfo_.ref = ref; -} - -void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref) -{ - if (type == CONSUME) { - SetConsumeCallbackInfo(env, ref); - } else if (type == CANCEL) { - SetCancelCallbackInfo(env, ref); - } else if (type == UPDATE) { - SetUpdateCallbackInfo(env, ref); - } else if (type == SUBSCRIBE) { - SetSubscribeCallbackInfo(env, ref); - } else if (type == UNSUBSCRIBE) { - SetUnsubscribeCallbackInfo(env, ref); - } else if (type == DIE) { - SetDieCallbackInfo(env, ref); - } else if (type == DISTURB_MODE_CHANGE) { - SetDisturbModeCallbackInfo(env, ref); - } else { - ANS_LOGW("type is error"); - } -} - -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"); - napi_valuetype valuetype; - size_t strLen = 0; - char str[STR_MAX_SIZE] = {0}; - - NAPI_ASSERT(env, argc >= ON_MAX_PARA, "Wrong number of arguments"); - - // argv[0]:type - 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)); - type = str; - if (!(type == CONSUME || type == CANCEL || type == UPDATE || type == SUBSCRIBE || type == UNSUBSCRIBE || - type == DIE || type == DISTURB_MODE_CHANGE)) { - ANS_LOGI("type parameter is error"); - return nullptr; - } - - // argv[1]:callback - 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); - - return Common::NapiGetNull(env); -} - -napi_value On(napi_env env, napi_callback_info info) -{ - ANS_LOGI("On start"); - - size_t argc = ON_MAX_PARA; - napi_value argv[ON_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - std::string type; - napi_ref callback = 0; - if (ParseParametersByOn(env, argc, argv, type, callback) == nullptr) { - return Common::NapiGetNull(env); - } - - SubscriberInstance *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - ANS_LOGI("On objectInfo = %{public}p", objectInfo); - - AsyncCallbackInfoOn *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoOn{ - .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .type = type, .callback = callback}; - - if (!AddAsyncCallbackInfo(objectInfo, asynccallbackinfo)) { - return Common::NapiGetNull(env); - } - - napi_value resourceName; - napi_create_string_latin1(env, "on", NAPI_AUTO_LENGTH, &resourceName); - // Asynchronous function call - napi_create_async_work(env, - nullptr, - resourceName, - [](napi_env env, void *data) { - ANS_LOGI("On napi_create_async_work start"); - AsyncCallbackInfoOn *asynccallbackinfo = (AsyncCallbackInfoOn *)data; - ANS_LOGI("On asynccallbackinfo->type = %{public}s", asynccallbackinfo->type.c_str()); - asynccallbackinfo->objectInfo->SetCallbackInfo(env, asynccallbackinfo->type, asynccallbackinfo->callback); - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("On napi_create_async_work end"); - AsyncCallbackInfoOn *asynccallbackinfo = (AsyncCallbackInfoOn *)data; - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - }, - (void *)asynccallbackinfo, - &asynccallbackinfo->asyncWork); - - NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - - return Common::NapiGetNull(env); -} - -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"); - napi_valuetype valuetype; - size_t strLen = 0; - char str[STR_MAX_SIZE] = {0}; - - NAPI_ASSERT(env, argc >= OFF_MAX_PARA, "Wrong number of arguments"); - - // argv[0]:type - 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)); - type = str; - if (!(type == CONSUME || type == CANCEL || type == UPDATE || type == SUBSCRIBE || type == UNSUBSCRIBE || - type == DIE || type == DISTURB_MODE_CHANGE)) { - ANS_LOGE("type parameter is error"); - return nullptr; - } - - return Common::NapiGetNull(env); -} - -napi_value Off(napi_env env, napi_callback_info info) -{ - ANS_LOGI("Off start"); - - size_t argc = OFF_MAX_PARA; - napi_value argv[OFF_MAX_PARA]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - std::string type; - if (ParseParametersByOff(env, argc, argv, type) == nullptr) { - return Common::NapiGetNull(env); - } - - SubscriberInstance *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - ANS_LOGI("Off objectInfo = %{public}p", objectInfo); - - AsyncCallbackInfoOff *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoOff{ - .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .type = type, .callback = nullptr}; - - napi_value resourceName; - napi_create_string_latin1(env, "off", NAPI_AUTO_LENGTH, &resourceName); - // Asynchronous function call - napi_create_async_work(env, - nullptr, - resourceName, - [](napi_env env, void *data) { - ANS_LOGI("Off napi_create_async_work start"); - AsyncCallbackInfoOff *asynccallbackinfo = (AsyncCallbackInfoOff *)data; - ANS_LOGI("Off asynccallbackinfo->type = %{public}s", asynccallbackinfo->type.c_str()); - asynccallbackinfo->objectInfo->SetCallbackInfo(env, asynccallbackinfo->type, asynccallbackinfo->callback); - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("Off napi_create_async_work end"); - AsyncCallbackInfoOff *asynccallbackinfo = (AsyncCallbackInfoOff *)data; - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - - DelAsyncCallbackInfo(asynccallbackinfo->objectInfo, asynccallbackinfo->type); - - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } - }, - (void *)asynccallbackinfo, - &asynccallbackinfo->asyncWork); - - NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - - return Common::NapiGetNull(env); -} - -napi_value CreateSubscriber(napi_env env, napi_callback_info info) -{ - ANS_LOGI("CreateSubscriber start"); - - size_t argc = 0; - napi_value argv[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - - napi_value result = 0; - napi_new_instance(env, g_NotificationSubscriber, 0, nullptr, &result); - - return result; -} - -napi_value SubscriberConstructor(napi_env env, napi_callback_info info) -{ - ANS_LOGI("SubscriberConstructor start"); - - size_t argc = 0; - napi_value argv[1]; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); - - SubscriberInstance *objectInfo = nullptr; - if (!CreateSubscriberInstanceRecord(&objectInfo)) { - return Common::NapiGetNull(env); - } - ANS_LOGI("SubscriberConstructor objectInfo = %{public}p", objectInfo); - - napi_wrap(env, - thisVar, - objectInfo, - [](napi_env env, void *data, void *hint) { - SubscriberInstance *objectInfo = (SubscriberInstance *)data; - ANS_LOGI("SubscriberConstructor this = %{public}p, destruct", objectInfo); - - DelAsyncCallbackInfo(objectInfo); - - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } - }, - nullptr, - nullptr); - - ANS_LOGI("SubscriberConstructor end"); - return thisVar; -} - -bool CreateSubscriberInstanceRecord(SubscriberInstance **subscriber) -{ - ANS_LOGI("CreateSubscriberInstanceRecord start"); - - *subscriber = new (std::nothrow) SubscriberInstance(); - - if (*subscriber == nullptr) { - ANS_LOGE("subscriber is null"); - return false; - } - - std::vector info; - g_SubscriberInstances[*subscriber] = info; - - return true; -} - -bool AddAsyncCallbackInfo(SubscriberInstance *subscriber, AsyncCallbackInfoOn *asynccallbackinfo) -{ - ANS_LOGI("AddAsyncCallbackInfo start"); - - if (subscriber == nullptr) { - ANS_LOGE("subscriber is null"); - return false; - } - - if (asynccallbackinfo == nullptr) { - ANS_LOGE("asynccallbackinfo is null"); - return false; - } - - std::lock_guard lock(mutex_); - auto infoItem = g_SubscriberInstances.find(subscriber); - if (infoItem != g_SubscriberInstances.end()) { - ANS_LOGI("AddAsyncCallbackInfo AsyncCallbackInfoOn size = %{public}zu", infoItem->second.size()); - for (auto asyncCallbackInfoOn : infoItem->second) { - ANS_LOGI("AddAsyncCallbackInfo AsyncCallbackInfoOn ptr = %{public}p", asyncCallbackInfoOn); - ANS_LOGI("AsyncCallbackInfoOn->type = %{public}s", asyncCallbackInfoOn->type.c_str()); - if (asyncCallbackInfoOn->type == asynccallbackinfo->type) { - asyncCallbackInfoOn = asynccallbackinfo; - return true; - } - } - g_SubscriberInstances[subscriber].emplace_back(asynccallbackinfo); - } else { - ANS_LOGE("the current subscriber does not exist"); - return false; - } - - return true; -} - -bool DelAsyncCallbackInfo(SubscriberInstance *subscriber, const std::string &type) -{ - ANS_LOGI("DelSubscriberInstance start"); - - if (subscriber == nullptr) { - ANS_LOGE("subscriber is null"); - return false; - } - - std::lock_guard lock(mutex_); - - auto infoItem = g_SubscriberInstances.find(subscriber); - if (infoItem != g_SubscriberInstances.end()) { - ANS_LOGI("DelSubscriberInstance AsyncCallbackInfoOn size = %{public}zu", infoItem->second.size()); - if (type.empty()) { - for (auto asyncCallbackInfoOn : infoItem->second) { - ANS_LOGI("DelSubscriberInstance AsyncCallbackInfoOn ptr = %{public}p", asyncCallbackInfoOn); - delete asyncCallbackInfoOn; - asyncCallbackInfoOn = nullptr; - } - g_SubscriberInstances.erase(subscriber); - } else { - for (auto it = infoItem->second.begin(); it != infoItem->second.end(); ++it) { - ANS_LOGI("DelSubscriberInstance AsyncCallbackInfoOn ptr = %{public}p", *it); - ANS_LOGI("DelSubscriberInstance type = %{public}s", (*it)->type.c_str()); - if ((*it)->type == type) { - delete *it; - *it = nullptr; - infoItem->second.erase(it); - break; - } - } - if (infoItem->second.size() == 0) { - g_SubscriberInstances.erase(subscriber); - } - } - } else { - return false; - } - - return true; - - ANS_LOGI("DelSubscriberInstance end"); -} - -bool HasNotificationSubscriber(SubscriberInstance *subscriber) -{ - ANS_LOGI("HasNotificationSubscriber start"); - - if (subscriber == nullptr) { - ANS_LOGE("subscriber is null"); - return false; - } - - std::lock_guard lock(mutex_); - - auto infoItem = g_SubscriberInstances.find(subscriber); - if (infoItem != g_SubscriberInstances.end()) { - return true; - } else { - ANS_LOGE("HasNotificationSubscriber The curren subscriber does not exist"); - return false; - } -} - -napi_value NotificationSubscriberInit(napi_env env, napi_value exports) -{ - ANS_LOGI("NotificationSubscriberInit start"); - - napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("on", On), - DECLARE_NAPI_FUNCTION("off", Off), - }; - - NAPI_CALL(env, - napi_define_class(env, - "notificationSubscriber", - NAPI_AUTO_LENGTH, - SubscriberConstructor, - nullptr, - sizeof(properties) / sizeof(*properties), - properties, - &g_NotificationSubscriber)); - - return exports; -} -} // namespace NotificationNapi -} // namespace OHOS diff --git a/interfaces/kits/napi/ans/src/display_badge.cpp b/interfaces/kits/napi/ans/src/display_badge.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52d895636173efe32c84da0985feba28695d4b29 --- /dev/null +++ b/interfaces/kits/napi/ans/src/display_badge.cpp @@ -0,0 +1,265 @@ +/* + * 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 "enable_notification.h" + +namespace OHOS { +namespace NotificationNapi { +const int ENABLE_BADGE_DISPLAYED_MAX_PARA = 3; +const int ENABLE_BADGE_DISPLAYED_MIN_PARA = 2; +const int IS_DISPLAY_BADGE_MAX_PARA = 2; + +struct EnableBadgeParams { + BundleOption option; + bool enable = false; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoEnableBadge { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + EnableBadgeParams params; + CallbackPromiseInfo info; +}; + +struct IsDisplayBadgeParams { + BundleOption option; + napi_ref callback = nullptr; + bool hasBundleOption = false; +}; + +struct AsyncCallbackInfoIsDisplayBadge { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + IsDisplayBadgeParams params; + CallbackPromiseInfo info; + bool enabled = false; +}; + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, EnableBadgeParams ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = ENABLE_BADGE_DISPLAYED_MAX_PARA; + napi_value argv[ENABLE_BADGE_DISPLAYED_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= ENABLE_BADGE_DISPLAYED_MIN_PARA, "Wrong number of arguments"); + + // argv[0]: bundle + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); + auto retValue = Common::GetBundleOption(env, argv[0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + + // argv[1]: enable + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, argv[1], ¶ms.enable); + + // argv[2]:callback + if (argc >= ENABLE_BADGE_DISPLAYED_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 ParseParameters(const napi_env &env, const napi_callback_info &info, IsDisplayBadgeParams ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = IS_DISPLAY_BADGE_MAX_PARA; + napi_value argv[IS_DISPLAY_BADGE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + if (argc == 0) { + return Common::NapiGetNull(env); + } + + // argv[0]: bundle / callback + napi_valuetype valuetype = napi_undefined; + 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_object) { + auto retValue = Common::GetBundleOption(env, argv[0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + params.hasBundleOption = true; + } else { + napi_create_reference(env, argv[0], 1, ¶ms.callback); + } + + // argv[1]:callback + if (argc >= IS_DISPLAY_BADGE_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 DisplayBadge(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + EnableBadgeParams params{}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); + } + + AsyncCallbackInfoEnableBadge *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoEnableBadge{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "DisplayBadge", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("DisplayBadge napi_create_async_work start"); + AsyncCallbackInfoEnableBadge *asynccallbackinfo = (AsyncCallbackInfoEnableBadge *)data; + NotificationBundleOption bundleOption; + bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); + bundleOption.SetUid(asynccallbackinfo->params.option.uid); + ANS_LOGI("asynccallbackinfo->params.option.bundle = %{public}s", + asynccallbackinfo->params.option.bundle.c_str()); + ANS_LOGI("asynccallbackinfo->params.option.uid = %{public}d", asynccallbackinfo->params.option.uid); + ANS_LOGI("asynccallbackinfo->params.enable = %{public}d", asynccallbackinfo->params.enable); + asynccallbackinfo->info.errorCode = + NotificationHelper::SetShowBadgeEnabledForBundle(bundleOption, asynccallbackinfo->params.enable); + ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("DisplayBadge napi_create_async_work end"); + AsyncCallbackInfoEnableBadge *asynccallbackinfo = (AsyncCallbackInfoEnableBadge *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + 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 IsBadgeDisplayed(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + IsDisplayBadgeParams params{}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); + } + + AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoIsDisplayBadge{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "IsBadgeDisplayed", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("IsBadgeDisplayed napi_create_async_work start"); + AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = (AsyncCallbackInfoIsDisplayBadge *)data; + + NotificationBundleOption bundleOption; + bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); + bundleOption.SetUid(asynccallbackinfo->params.option.uid); + if (asynccallbackinfo->params.hasBundleOption) { + ANS_LOGI("asynccallbackinfo->params.option.bundle = %{public}s", + asynccallbackinfo->params.option.bundle.c_str()); + ANS_LOGI("asynccallbackinfo->params.option.uid = %{public}d", asynccallbackinfo->params.option.uid); + ANS_LOGI("asynccallbackinfo->enabled = %{public}d", asynccallbackinfo->enabled); + asynccallbackinfo->info.errorCode = + NotificationHelper::GetShowBadgeEnabledForBundle(bundleOption, asynccallbackinfo->enabled); + } else { + ANS_LOGI("asynccallbackinfo->enabled = %{public}d", asynccallbackinfo->enabled); + asynccallbackinfo->info.errorCode = NotificationHelper::GetShowBadgeEnabled(asynccallbackinfo->enabled); + } + ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("IsBadgeDisplayed napi_create_async_work end"); + AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = (AsyncCallbackInfoIsDisplayBadge *)data; + + napi_value result = nullptr; + napi_get_boolean(env, asynccallbackinfo->enabled, &result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (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; + } +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/disturb_mode.cpp b/interfaces/kits/napi/ans/src/disturb_mode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..34040e313a80d2d5f6f898b63b143ffff6dd03ed --- /dev/null +++ b/interfaces/kits/napi/ans/src/disturb_mode.cpp @@ -0,0 +1,126 @@ +/* + * 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 "disturb_mode.h" + +namespace OHOS { +namespace NotificationNapi { +const int DISTURB_MODE_MAX_PARA = 2; +const int DISTURB_MODE_MIN_PARA = 1; + +struct DisturbModeParams { + NotificationConstant::DisturbMode mode = NotificationConstant::DisturbMode::ALLOW_UNKNOWN; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoDisturbMode { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + DisturbModeParams params; + CallbackPromiseInfo info; +}; + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, DisturbModeParams ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = DISTURB_MODE_MAX_PARA; + napi_value argv[DISTURB_MODE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= DISTURB_MODE_MIN_PARA, "Wrong number of arguments"); + + // argv[0]: mode + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + int mode = 0; + napi_get_value_int32(env, argv[0], &mode); + ANS_LOGI("mode is: %{public}d", mode); + + if (!Common::DisturbModeJSToC(DisturbMode(mode), params.mode)) { + return nullptr; + } + + // argv[1]:callback + if (argc >= DISTURB_MODE_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 SetDoNotDisturbMode(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + DisturbModeParams params{}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); + } + + AsyncCallbackInfoDisturbMode *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoDisturbMode{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "setDoNotDisturbMode", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("SetDoNotDisturbMode napi_create_async_work start"); + AsyncCallbackInfoDisturbMode *asynccallbackinfo = (AsyncCallbackInfoDisturbMode *)data; + ANS_LOGI("asynccallbackinfo->params.mode = %{public}d", asynccallbackinfo->params.mode); + asynccallbackinfo->info.errorCode = NotificationHelper::SetDisturbMode(asynccallbackinfo->params.mode); + ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("SetDoNotDisturbMode napi_create_async_work end"); + AsyncCallbackInfoDisturbMode *asynccallbackinfo = (AsyncCallbackInfoDisturbMode *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (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; + } +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/enable_notification.cpp b/interfaces/kits/napi/ans/src/enable_notification.cpp new file mode 100644 index 0000000000000000000000000000000000000000..014c6c3e680ee529740c8de450a738bea7d7bcca --- /dev/null +++ b/interfaces/kits/napi/ans/src/enable_notification.cpp @@ -0,0 +1,262 @@ +/* + * 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 "enable_notification.h" + +namespace OHOS { +namespace NotificationNapi { +const int ENABLE_NOTIFICATION_MAX_PARA = 3; +const int ENABLE_NOTIFICATION_MIN_PARA = 2; +const int IS_NOTIFICATION_ENABLE_MAX_PARA = 2; + +struct EnableParams { + BundleOption option; + bool enable = false; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoEnable { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + EnableParams params; + CallbackPromiseInfo info; +}; + +struct IsEnableParams { + BundleOption option; + napi_ref callback = nullptr; + bool hasBundleOption = false; +}; + +struct AsyncCallbackInfoIsEnable { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + IsEnableParams params; + CallbackPromiseInfo info; + bool allowed = false; +}; + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, EnableParams ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = ENABLE_NOTIFICATION_MAX_PARA; + napi_value argv[ENABLE_NOTIFICATION_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= ENABLE_NOTIFICATION_MIN_PARA, "Wrong number of arguments"); + + // argv[0]: bundle + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); + auto retValue = Common::GetBundleOption(env, argv[0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + + // argv[1]: enable + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, argv[1], ¶ms.enable); + + // argv[2]:callback + if (argc >= ENABLE_NOTIFICATION_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 ParseParameters(const napi_env &env, const napi_callback_info &info, IsEnableParams ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = IS_NOTIFICATION_ENABLE_MAX_PARA; + napi_value argv[IS_NOTIFICATION_ENABLE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + if (argc == 0) { + return Common::NapiGetNull(env); + } + + // argv[0]: bundle / callback + napi_valuetype valuetype = napi_undefined; + 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_object) { + auto retValue = Common::GetBundleOption(env, argv[0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + params.hasBundleOption = true; + } else { + napi_create_reference(env, argv[0], 1, ¶ms.callback); + } + + // argv[1]:callback + if (argc >= IS_NOTIFICATION_ENABLE_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 EnableNotification(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + EnableParams params{}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); + } + + AsyncCallbackInfoEnable *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoEnable{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "enableNotification", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("EnableNotification napi_create_async_work start"); + AsyncCallbackInfoEnable *asynccallbackinfo = (AsyncCallbackInfoEnable *)data; + NotificationBundleOption bundleOption; + bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); + bundleOption.SetUid(asynccallbackinfo->params.option.uid); + std::string deviceId; + asynccallbackinfo->info.errorCode = NotificationHelper::SetNotificationsEnabledForSpecifiedBundle( + bundleOption, deviceId, asynccallbackinfo->params.enable); + ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("EnableNotification napi_create_async_work end"); + AsyncCallbackInfoEnable *asynccallbackinfo = (AsyncCallbackInfoEnable *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (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 IsNotificationEnabled(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + IsEnableParams params{}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); + } + + AsyncCallbackInfoIsEnable *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoIsEnable{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "isNotificationEnabled", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("IsNotificationEnabled napi_create_async_work start"); + AsyncCallbackInfoIsEnable *asynccallbackinfo = (AsyncCallbackInfoIsEnable *)data; + + if (asynccallbackinfo->params.hasBundleOption) { + NotificationBundleOption bundleOption; + bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); + bundleOption.SetUid(asynccallbackinfo->params.option.uid); + ANS_LOGI("asynccallbackinfo->params.option.bundle = %{public}s", + asynccallbackinfo->params.option.bundle.c_str()); + ANS_LOGI("asynccallbackinfo->params.option.uid = %{public}d", asynccallbackinfo->params.option.uid); + ANS_LOGI("asynccallbackinfo->allowed = %{public}d", asynccallbackinfo->allowed); + asynccallbackinfo->info.errorCode = + NotificationHelper::IsAllowedNotify(bundleOption, asynccallbackinfo->allowed); + } else { + ANS_LOGI("asynccallbackinfo->allowed = %{public}d", asynccallbackinfo->allowed); + asynccallbackinfo->info.errorCode = NotificationHelper::IsAllowedNotify(asynccallbackinfo->allowed); + } + ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("IsNotificationEnabled napi_create_async_work end"); + AsyncCallbackInfoIsEnable *asynccallbackinfo = (AsyncCallbackInfoIsEnable *)data; + + napi_value result = nullptr; + napi_get_boolean(env, asynccallbackinfo->allowed, &result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (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; + } +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/get_active.cpp b/interfaces/kits/napi/ans/src/get_active.cpp index 0ae881ec3e8d6c32cd1a05cf7947e8a4bd20fc06..cf9bab8a6ebd251be752610c79facd0ea80215b7 100644 --- a/interfaces/kits/napi/ans/src/get_active.cpp +++ b/interfaces/kits/napi/ans/src/get_active.cpp @@ -21,23 +21,23 @@ const int ALL_ACTIVE_MAX_PARA = 1; 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_env env = nullptr; + napi_async_work asyncWork = nullptr; 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] = {nullptr}; + 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; + napi_valuetype valuetype = napi_undefined; // argv[0]:callback NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); @@ -47,100 +47,81 @@ 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] = {nullptr}; + 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; + napi_valuetype valuetype = napi_undefined; // 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); -} - -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}zu", hashcode.size()); AsyncCallbackInfoActive *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr, .strValue = hashcode}; - - napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + new (std::nothrow) AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "getAllActiveNotifications", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { 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 = nullptr; + 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 = nullptr; + 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 +129,11 @@ 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); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -166,7 +146,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,60 +155,59 @@ 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 = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); - napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); - - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "getActiveNotifications", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { 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 = nullptr; + 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 = nullptr; + 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 +215,11 @@ 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); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -254,61 +232,59 @@ 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 = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); - napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); - - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "getActiveNotificationNums", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { 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); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -321,11 +297,11 @@ 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; } } } // namespace NotificationNapi -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index 14eb5ce8cc6177d83162903e9b496941d49537c1..64869c224dbcae3c520eb63a41d11a557a8abb70 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -16,7 +16,9 @@ #include "init.h" #include "cancel.h" #include "constant.h" -#include "create_subscriber.h" +#include "display_badge.h" +#include "disturb_mode.h" +#include "enable_notification.h" #include "get_active.h" #include "publish.h" #include "remove.h" @@ -35,18 +37,30 @@ napi_value NotificationInit(napi_env env, napi_value exports) ANS_LOGI("notificationInit start"); napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("createSubscriber", CreateSubscriber), 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("setSlotAsBundle", SetSlotAsBundle), DECLARE_NAPI_FUNCTION("getSlot", GetSlot), + DECLARE_NAPI_FUNCTION("getSlotNumAsBundle", GetSlotNumAsBundle), DECLARE_NAPI_FUNCTION("getSlots", GetSlots), + DECLARE_NAPI_FUNCTION("getSlotsAsBundle", GetSlotsAsBundle), DECLARE_NAPI_FUNCTION("removeSlot", RemoveSlot), + DECLARE_NAPI_FUNCTION("removeAllSlots", RemoveAllSlots), + DECLARE_NAPI_FUNCTION("enableNotification", EnableNotification), + DECLARE_NAPI_FUNCTION("isNotificationEnabled", IsNotificationEnabled), + DECLARE_NAPI_FUNCTION("displayBadge", DisplayBadge), + DECLARE_NAPI_FUNCTION("isBadgeDisplayed", IsBadgeDisplayed), + DECLARE_NAPI_FUNCTION("setDoNotDisturbMode", SetDoNotDisturbMode), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); @@ -62,7 +76,6 @@ static napi_value Init(napi_env env, napi_value exports) /* * Propertise define */ - NotificationSubscriberInit(env, exports); NotificationInit(env, exports); ConstantInit(env, exports); return exports; diff --git a/interfaces/kits/napi/ans/src/publish.cpp b/interfaces/kits/napi/ans/src/publish.cpp index eda71be1aaffead0640ac7386ce3f0c2fa5f93f0..8dd5e880c3ce4188a59a97f4db6e765bd6d027d2 100644 --- a/interfaces/kits/napi/ans/src/publish.cpp +++ b/interfaces/kits/napi/ans/src/publish.cpp @@ -23,134 +23,80 @@ namespace NotificationNapi { 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; + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + 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_undefined; + 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] = {nullptr}; + 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_undefined; + 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 = nullptr; 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_value resourceName = nullptr; napi_create_string_latin1(env, "publish", NAPI_AUTO_LENGTH, &resourceName); napi_create_async_work(env, @@ -159,20 +105,23 @@ 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 = " + "%{public}d", + 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)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -186,7 +135,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 a3f01f9241aca8905301247b39e13f04319552c4..a2c4f62ba92f3465912e37ff4c700c74be5ea08f 100644 --- a/interfaces/kits/napi/ans/src/remove.cpp +++ b/interfaces/kits/napi/ans/src/remove.cpp @@ -14,96 +14,155 @@ */ #include "remove.h" +#include +#include "common.h" +#include "notification_bundle_option.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; -struct AsyncCallbackInfoRemove { - napi_env env; - napi_async_work asyncWork; +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; - napi_deferred deferred; - std::string strValue; - bool isCallback = false; - int errorCode = 0; }; -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) +struct AsyncCallbackInfoRemove { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + RemoveParams params{}; + CallbackPromiseInfo info; +}; + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, RemoveParams ¶ms) { + ANS_LOGI("enter"); + + size_t argc = REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA; + napi_value argv[REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= REMOVE_MIN_PARA, "Wrong number of arguments"); - 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_valuetype valuetype = napi_undefined; 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 = 0; + 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] = {nullptr}; + 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_undefined; + 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"); + ANS_LOGI("enter"); - 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 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}; - - napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + new (std::nothrow) AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "remove", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -112,80 +171,27 @@ 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)); + 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(); - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; + NotificationBundleOption bundleOption(infos.option.bundle, infos.option.uid); + asynccallbackinfo->info.errorCode = + NotificationHelper::RemoveNotification(bundleOption, 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)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -198,33 +204,31 @@ 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}; - - napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + new (std::nothrow) AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "removeAll", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -233,18 +237,25 @@ 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(); + + NotificationBundleOption bundleOption(infos.option.bundle, infos.option.uid); + asynccallbackinfo->info.errorCode = NotificationHelper::RemoveAllNotifications(bundleOption); + } 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)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -257,7 +268,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 c3967c3b4627b02fa237c8837ede6e9e1403885f..19350c71683a8ddd6f0a1997c0d5382bbae73a68 100644 --- a/interfaces/kits/napi/ans/src/slot.cpp +++ b/interfaces/kits/napi/ans/src/slot.cpp @@ -19,162 +19,260 @@ namespace OHOS { namespace NotificationNapi { const int ADD_SLOT_MAX_PARA = 2; const int ADD_SLOTS_MAX_PARA = 2; +const int SET_SLOT_AS_BUNDLE_MAX_PARA = 3; const int GET_SLOT_MAX_PARA = 2; +const int GET_SLOT_NUM_AS_BUNDLE_MAX_PARA = 2; const int GET_SLOTS_MAX_PARA = 1; +const int GET_SLOTS_AS_BUNDLE_MAX_PARA = 2; const int REMOVE_SLOT_MAX_PARA = 2; +const int REMOVE_ALL_MAX_PARA = 1; -struct AsyncCallbackInfoAddSlot { - napi_env env; - napi_async_work asyncWork; +struct ParametersInfoAddSlot { + NotificationSlot slot; + enum NotificationConstant::SlotType inType = NotificationConstant::SlotType::OTHER; + bool isAddSlotByType = false; napi_ref callback = nullptr; - napi_deferred deferred; +}; + +struct AsyncCallbackInfoAddSlot { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; NotificationSlot slot; - bool isCallback = false; - int errorCode = 0; + enum NotificationConstant::SlotType inType = NotificationConstant::SlotType::OTHER; + bool isAddSlotByType = false; + CallbackPromiseInfo info; }; -struct AsyncCallbackInfoAddSlots { - napi_env env; - napi_async_work asyncWork; +struct ParametersInfoAddSlots { + std::vector slots; napi_ref callback = nullptr; - napi_deferred deferred; +}; + +struct AsyncCallbackInfoAddSlots { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; std::vector slots; - bool isCallback = false; - int errorCode = 0; + CallbackPromiseInfo info; +}; + +struct ParametersInfoSetSlotAsBundle { + BundleOption option; + std::vector> slots; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoSetSlotAsBundle { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + ParametersInfoSetSlotAsBundle params; + CallbackPromiseInfo info; +}; + +struct ParametersInfoGetSlot { + enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; + napi_ref callback = nullptr; }; struct AsyncCallbackInfoGetSlot { - napi_env env; - napi_async_work asyncWork; + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; + napi_value result = nullptr; + CallbackPromiseInfo info; +}; + +struct ParametersInfoGetSlotNumAsBundle { + BundleOption option; napi_ref callback = nullptr; - napi_deferred deferred; - enum NotificationConstant::SlotType outType; - bool isCallback = false; +}; + +struct AsyncCallbackInfoGetSlotNumAsBundle { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; napi_value result = nullptr; - int errorCode = 0; + ParametersInfoGetSlotNumAsBundle params; + CallbackPromiseInfo info; }; struct AsyncCallbackInfoGetSlots { - napi_env env; - napi_async_work asyncWork; + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_value result = nullptr; + CallbackPromiseInfo info; +}; + +struct ParametersInfoGetSlotsAsBundle { + BundleOption option; napi_ref callback = nullptr; - napi_deferred deferred; - bool isCallback = false; +}; + +struct AsyncCallbackInfoGetSlotsAsBundle { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; napi_value result = nullptr; - int errorCode = 0; + ParametersInfoGetSlotsAsBundle params; + CallbackPromiseInfo info; }; -struct AsyncCallbackInfoRemoveSlot { - napi_env env; - napi_async_work asyncWork; +struct ParametersInfoRemoveSlot { + enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; napi_ref callback = nullptr; - napi_deferred deferred; - enum NotificationConstant::SlotType outType; - bool isCallback = false; - int errorCode = 0; }; -napi_value ParseParametersByAddSlot(const napi_env &env, const napi_value (&argv)[ADD_SLOT_MAX_PARA], - const size_t &argc, NotificationSlot &slot, napi_ref &callback) +struct AsyncCallbackInfoRemoveSlot { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; + CallbackPromiseInfo info; +}; + +struct AsyncCallbackInfoRemoveAllSlots { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + CallbackPromiseInfo info; +}; + +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] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; + + napi_valuetype valuetype = napi_undefined; // 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] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; + + napi_valuetype valuetype = napi_undefined; // 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 = nullptr; + 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) +napi_value ParseParametersSetSlotAsBundle( + const napi_env &env, const napi_callback_info &info, ParametersInfoSetSlotAsBundle ¶ms) { - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + ANS_LOGI("enter"); - 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; + size_t argc = SET_SLOT_AS_BUNDLE_MAX_PARA; + napi_value argv[SET_SLOT_AS_BUNDLE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= SET_SLOT_AS_BUNDLE_MAX_PARA - 1, "Wrong number of arguments"); + + // argv[0]: bundle + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); + auto retValue = Common::GetBundleOption(env, argv[0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; } + + // argv[1]: slot + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); + NotificationSlot slot; + if (!Common::GetNotificationSlot(env, argv[1], slot)) { + return nullptr; + } + std::vector slots; + slots.emplace_back(slot); + + for (auto vec : slots) { + sptr slotPtr = new (std::nothrow) NotificationSlot(vec); + if (slotPtr == nullptr) { + ANS_LOGE("Failed to create NotificationSlot ptr"); + return nullptr; + } + params.slots.emplace_back(slotPtr); + } + + // argv[2]:callback + if (argc >= SET_SLOT_AS_BUNDLE_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 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] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; + + napi_valuetype valuetype = napi_undefined; // 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,32 +280,52 @@ 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 ParseParametersGetSlotNumAsBundle( + const napi_env &env, const napi_callback_info &info, ParametersInfoGetSlotNumAsBundle ¶ms) { - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + ANS_LOGI("enter"); - 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; + size_t argc = GET_SLOT_NUM_AS_BUNDLE_MAX_PARA; + napi_value argv[GET_SLOT_NUM_AS_BUNDLE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= GET_SLOT_NUM_AS_BUNDLE_MAX_PARA - 1, "Wrong number of arguments"); + + // argv[0]: bundle + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); + auto retValue = Common::GetBundleOption(env, argv[0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; } + + // argv[1]:callback + if (argc >= GET_SLOT_NUM_AS_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); + } + + return Common::NapiGetNull(env); } -napi_value ParseParametersByGetSlots( - const napi_env &env, const napi_value (&argv)[GET_SLOTS_MAX_PARA], const size_t &argc, napi_ref &callback) +napi_value ParseParametersByGetSlots(const napi_env &env, const napi_callback_info &info, napi_ref &callback) { + ANS_LOGI("enter"); + size_t argc = GET_SLOTS_MAX_PARA; + napi_value argv[GET_SLOTS_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + // argv[0]:callback - napi_valuetype valuetype; + napi_valuetype valuetype = napi_undefined; if (argc >= GET_SLOTS_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); @@ -216,35 +334,54 @@ napi_value ParseParametersByGetSlots( return Common::NapiGetNull(env); } -void PaddingAsyncCallbackInfoIsByGetSlots( - const napi_env &env, AsyncCallbackInfoGetSlots *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +napi_value ParseParametersGetSlotsAsBundle( + const napi_env &env, const napi_callback_info &info, ParametersInfoGetSlotsAsBundle ¶ms) { - ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + ANS_LOGI("enter"); - 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; + size_t argc = GET_SLOTS_AS_BUNDLE_MAX_PARA; + napi_value argv[GET_SLOTS_AS_BUNDLE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= GET_SLOTS_AS_BUNDLE_MAX_PARA - 1, "Wrong number of arguments"); + + // argv[0]: bundle + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); + auto retValue = Common::GetBundleOption(env, argv[0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; } + + // argv[1]:callback + if (argc >= GET_SLOTS_AS_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); + } + + return Common::NapiGetNull(env); } -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] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; + + napi_valuetype valuetype = napi_undefined; // 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,50 +389,50 @@ 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] = {nullptr}; + 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 = napi_undefined; + // 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"); + 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_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}; - - napi_value promise = 0; - PaddingAsyncCallbackInfoIsByAddSlot(env, asynccallbackinfo, callback, promise); + 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 = nullptr; + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "addSlot", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -304,18 +441,21 @@ 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)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -328,35 +468,31 @@ 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"); - - 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; + ANS_LOGI("enter"); - 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}; - - napi_value promise = 0; - PaddingAsyncCallbackInfoIsByAddSlots(env, asynccallbackinfo, callback, promise); + new (std::nothrow) AsyncCallbackInfoAddSlots{.env = env, .asyncWork = nullptr, .slots = paras.slots}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "addSlots", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -365,18 +501,17 @@ 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)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -389,35 +524,92 @@ 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) + +napi_value SetSlotAsBundle(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)); + ParametersInfoSetSlotAsBundle params{}; + if (ParseParametersSetSlotAsBundle(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); + } - napi_ref callback = nullptr; + AsyncCallbackInfoSetSlotAsBundle *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoSetSlotAsBundle{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); - enum NotificationConstant::SlotType outType; - if (ParseParametersByGetSlot(env, argv, argc, outType, callback) == nullptr) { - return Common::JSParaError(env, callback); + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "setSlotAsBundle", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("SetSlotAsBundle napi_create_async_work start"); + AsyncCallbackInfoSetSlotAsBundle *asynccallbackinfo = (AsyncCallbackInfoSetSlotAsBundle *)data; + + NotificationBundleOption bundleOption; + bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); + bundleOption.SetUid(asynccallbackinfo->params.option.uid); + asynccallbackinfo->info.errorCode = + NotificationHelper::UpdateNotificationSlots(bundleOption, asynccallbackinfo->params.slots); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("SetSlotAsBundle napi_create_async_work end"); + AsyncCallbackInfoSetSlotAsBundle *asynccallbackinfo = (AsyncCallbackInfoSetSlotAsBundle *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (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; } +} - AsyncCallbackInfoGetSlot *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoGetSlot{.env = env, .asyncWork = nullptr, .outType = outType}; +napi_value GetSlot(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); - napi_value promise = 0; - PaddingAsyncCallbackInfoIsByGetSlot(env, asynccallbackinfo, callback, promise); + ParametersInfoGetSlot paras; + if (ParseParametersByGetSlot(env, info, paras) == nullptr) { + return Common::JSParaError(env, paras.callback); + } - napi_value resourceName; + AsyncCallbackInfoGetSlot *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetSlot{.env = env, .asyncWork = nullptr, .outType = paras.outType}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; napi_create_string_latin1(env, "getSlot", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -428,14 +620,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 +640,73 @@ 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); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (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 GetSlotNumAsBundle(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + ParametersInfoGetSlotNumAsBundle params{}; + if (ParseParametersGetSlotNumAsBundle(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); + } + + AsyncCallbackInfoGetSlotNumAsBundle *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetSlotNumAsBundle{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "getSlotNumAsBundle", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("GetSlotNumAsBundle napi_create_async_work start"); + AsyncCallbackInfoGetSlotNumAsBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotNumAsBundle *)data; + + NotificationBundleOption bundleOption; + bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); + bundleOption.SetUid(asynccallbackinfo->params.option.uid); + int num = 0; + asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlotNumAsBundle(bundleOption, num); + napi_create_int32(env, num, &asynccallbackinfo->result); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("GetSlotNumAsBundle napi_create_async_work end"); + AsyncCallbackInfoGetSlotNumAsBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotNumAsBundle *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -461,7 +719,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,25 +728,22 @@ 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 = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); - napi_value promise = 0; - PaddingAsyncCallbackInfoIsByGetSlots(env, asynccallbackinfo, callback, promise); - - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "getSlots", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -499,28 +754,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 = nullptr; + 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}zu", count); - if (count == 0) { - asynccallbackinfo->errorCode = ERROR; - asynccallbackinfo->result = Common::NapiGetNull(env); + napi_value nSlot = nullptr; + 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}zu", count); + asynccallbackinfo->result = arr; + if ((count == 0) && (slots.size() > 0)) { + asynccallbackinfo->info.errorCode = ERROR; asynccallbackinfo->result = Common::NapiGetNull(env); } }, @@ -528,12 +787,11 @@ 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); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -546,35 +804,120 @@ 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) + +napi_value GetSlotsAsBundle(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)); + ParametersInfoGetSlotsAsBundle params{}; + if (ParseParametersGetSlotsAsBundle(env, info, params) == nullptr) { + return Common::JSParaError(env, params.callback); + } - napi_ref callback = nullptr; + AsyncCallbackInfoGetSlotsAsBundle *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetSlotsAsBundle{.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); - enum NotificationConstant::SlotType outType; - if (ParseParametersByRemoveSlot(env, argv, argc, outType, callback) == nullptr) { - return Common::JSParaError(env, callback); + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "getSlotsAsBundle", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("GetSlotsAsBundle napi_create_async_work start"); + AsyncCallbackInfoGetSlotsAsBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotsAsBundle *)data; + + NotificationBundleOption bundleOption; + bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); + bundleOption.SetUid(asynccallbackinfo->params.option.uid); + + std::vector> slots; + asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlotsForBundle(bundleOption, slots); + if (asynccallbackinfo->info.errorCode != ERR_OK) { + asynccallbackinfo->result = Common::NapiGetNull(env); + return; + } + + napi_value arr = nullptr; + napi_create_array(env, &arr); + size_t count = 0; + for (auto vec : slots) { + if (!vec) { + ANS_LOGW("Invalid NotificationSlot object ptr"); + continue; + } + napi_value nSlot = nullptr; + napi_create_object(env, &nSlot); + if (!Common::SetNotificationSlot(env, *vec, nSlot)) { + continue; + } + napi_set_element(env, arr, count, nSlot); + count++; + } + ANS_LOGI("getSlots count = %{public}zu", count); + asynccallbackinfo->result = arr; + if ((count == 0) && (slots.size() > 0)) { + asynccallbackinfo->info.errorCode = ERROR; + asynccallbackinfo->result = Common::NapiGetNull(env); + } + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("GetSlotsAsBundle napi_create_async_work end"); + AsyncCallbackInfoGetSlotsAsBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotsAsBundle *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + 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; } +} - AsyncCallbackInfoRemoveSlot *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoRemoveSlot{.env = env, .asyncWork = nullptr, .outType = outType}; +napi_value RemoveSlot(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); - napi_value promise = 0; - PaddingAsyncCallbackInfoIsByRemoveSlot(env, asynccallbackinfo, callback, promise); + ParametersInfoRemoveSlot paras; + if (ParseParametersByRemoveSlot(env, info, paras) == nullptr) { + return Common::JSParaError(env, paras.callback); + } - napi_value resourceName; + AsyncCallbackInfoRemoveSlot *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoRemoveSlot{.env = env, .asyncWork = nullptr, .outType = paras.outType}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; napi_create_string_latin1(env, "removeSlot", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -583,18 +926,73 @@ 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)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (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 = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + 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)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -607,7 +1005,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; @@ -615,4 +1013,4 @@ napi_value RemoveSlot(napi_env env, napi_callback_info info) } } // namespace NotificationNapi -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index af36a9452a65bd7b7269e9303ec5cb3ab2dbf8ea..f4787d927a8fd6811c3cd9b172c8a6c883f4e1b4 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -13,112 +13,919 @@ * limitations under the License. */ +#include +#include #include "subscribe.h" namespace OHOS { namespace NotificationNapi { - const int SUBSRIBE_MAX_PARA = 3; +const int NO_DELETE_REASON = -1; +const std::string CONSUME = "onConsumed"; +const std::string CANCEL = "onCanceled"; +const std::string UPDATE = "onUpdate"; +const std::string CONNECTED = "onConnected"; +const std::string DIS_CONNECTED = "onDisConnect"; +const std::string DIE = "onDied"; +const std::string DISTURB_MODE_CHANGE = "onDisturbModeChanged"; + +struct NotificationReceiveDataWorker { + napi_env env = nullptr; + napi_ref ref = nullptr; + std::shared_ptr request; + std::shared_ptr sortingMap; + int deleteReason = 0; + int result = 0; + int disturbMode = 0; + SubscriberInstance *subscriber = nullptr; +}; + +napi_value SetSubscribeCallbackData(const napi_env &env, + const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason, napi_value &result) +{ + ANS_LOGI("enter"); + if (request == nullptr) { + ANS_LOGE("request is null"); + return Common::NapiGetboolean(env, false); + } + + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return Common::NapiGetboolean(env, false); + } + + // request: NotificationRequest + napi_value requestResult = nullptr; + napi_create_object(env, &requestResult); + if (!Common::SetNotification(env, request.get(), requestResult)) { + ANS_LOGE("SetNotification call failed"); + return Common::NapiGetboolean(env, false); + } + napi_set_named_property(env, result, "request", requestResult); + + // sortingMap?: NotificationSortingMap + napi_value sortingMapResult = nullptr; + napi_create_object(env, &sortingMapResult); + if (!Common::SetNotificationSortingMap(env, sortingMap, sortingMapResult)) { + ANS_LOGE("SetNotificationSortingMap call failed"); + return Common::NapiGetboolean(env, false); + } + napi_set_named_property(env, result, "sortingMap", sortingMapResult); + + // reason?: number + if (deleteReason != NO_DELETE_REASON) { + napi_value value = nullptr; + int outReason = 0; + if (!Common::ReasonCToJS(deleteReason, outReason)) { + return Common::NapiGetboolean(env, false); + } + napi_create_int32(env, outReason, &value); + napi_set_named_property(env, result, "reason", value); + } + + // sound?: string + napi_value soundResult = nullptr; + std::string sound; + if (request->EnableSound()) { + sound = request->GetSound().ToString(); + } + napi_create_string_utf8(env, sound.c_str(), NAPI_AUTO_LENGTH, &soundResult); + napi_set_named_property(env, result, "sound", soundResult); + + // vibrationValues?: Array + napi_value arr = nullptr; + napi_create_array(env, &arr); + size_t count = 0; + if (request->EnableVibrate()) { + for (auto vec : request->GetVibrationStyle()) { + napi_value nVibrationValue = nullptr; + napi_create_int64(env, vec, &nVibrationValue); + napi_set_element(env, arr, count, nVibrationValue); + count++; + } + } + napi_set_named_property(env, result, "vibrationValues", arr); + + return Common::NapiGetboolean(env, true); +} + +SubscriberInstance::SubscriberInstance() +{} + +SubscriberInstance::~SubscriberInstance() +{ + if (canceCallbackInfo_.ref != nullptr) { + napi_delete_reference(canceCallbackInfo_.env, canceCallbackInfo_.ref); + } + if (consumeCallbackInfo_.ref != nullptr) { + napi_delete_reference(consumeCallbackInfo_.env, consumeCallbackInfo_.ref); + } + if (updateCallbackInfo_.ref != nullptr) { + napi_delete_reference(updateCallbackInfo_.env, updateCallbackInfo_.ref); + } + if (subscribeCallbackInfo_.ref != nullptr) { + napi_delete_reference(subscribeCallbackInfo_.env, subscribeCallbackInfo_.ref); + } + if (unsubscribeCallbackInfo_.ref != nullptr) { + napi_delete_reference(unsubscribeCallbackInfo_.env, unsubscribeCallbackInfo_.ref); + } + if (dieCallbackInfo_.ref != nullptr) { + napi_delete_reference(dieCallbackInfo_.env, dieCallbackInfo_.ref); + } + if (disturbModeCallbackInfo_.ref != nullptr) { + napi_delete_reference(disturbModeCallbackInfo_.env, disturbModeCallbackInfo_.ref); + } +} + +void SubscriberInstance::OnCanceled(const std::shared_ptr &request) +{} + +void SubscriberInstance::OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) +{ + ANS_LOGI("enter"); + + if (canceCallbackInfo_.ref == nullptr) { + ANS_LOGI("cancel callback unset"); + return; + } + + if (request == nullptr) { + ANS_LOGE("request is null"); + return; + } + + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return; + } + ANS_LOGI("OnCanceled NotificationId = %{public}d", request->GetNotificationRequest().GetNotificationId()); + ANS_LOGI("OnCanceled sortingMap size = %{public}zu", sortingMap->GetKey().size()); + ANS_LOGI("OnCanceled deleteReason = %{public}d", deleteReason); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(canceCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); + if (dataWorker == nullptr) { + ANS_LOGE("new dataWorker failed"); + return; + } + + dataWorker->request = request; + dataWorker->sortingMap = sortingMap; + dataWorker->deleteReason = deleteReason; + dataWorker->env = canceCallbackInfo_.env; + dataWorker->ref = canceCallbackInfo_.ref; + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + ANS_LOGE("new work failed"); + return; + } + + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnCanceled uv_work_t start"); + + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + napi_value result = nullptr; + napi_create_object(dataWorkerData->env, &result); + int error = 0; + if (!SetSubscribeCallbackData(dataWorkerData->env, + dataWorkerData->request, + dataWorkerData->sortingMap, + dataWorkerData->deleteReason, + result)) { + result = Common::NapiGetNull(dataWorkerData->env); + error = ERROR; + } else { + error = NO_ERROR; + } + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnConsumed(const std::shared_ptr &request) +{} + +void SubscriberInstance::OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) +{ + ANS_LOGI("enter"); + + if (consumeCallbackInfo_.ref == nullptr) { + ANS_LOGI("consume callback unset"); + return; + } + + if (request == nullptr) { + ANS_LOGE("request is null"); + return; + } + + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return; + } + ANS_LOGI("OnConsumed NotificationId = %{public}d", request->GetNotificationRequest().GetNotificationId()); + ANS_LOGI("OnConsumed sortingMap size = %{public}zu", sortingMap->GetKey().size()); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(consumeCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); + if (dataWorker == nullptr) { + ANS_LOGE("new dataWorker failed"); + return; + } + + dataWorker->request = request; + dataWorker->sortingMap = sortingMap; + dataWorker->env = consumeCallbackInfo_.env; + dataWorker->ref = consumeCallbackInfo_.ref; + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + ANS_LOGE("new work failed"); + return; + } + + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnConsumed uv_work_t start"); + + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + napi_value result = nullptr; + napi_create_object(dataWorkerData->env, &result); + int error = 0; + if (!SetSubscribeCallbackData(dataWorkerData->env, + dataWorkerData->request, + dataWorkerData->sortingMap, + NO_DELETE_REASON, + result)) { + result = Common::NapiGetNull(dataWorkerData->env); + error = ERROR; + } else { + error = NO_ERROR; + } + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnUpdate(const std::shared_ptr &sortingMap) +{ + ANS_LOGI("enter"); + + if (updateCallbackInfo_.ref == nullptr) { + ANS_LOGI("update callback unset"); + return; + } + + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return; + } + ANS_LOGI("OnUpdate sortingMap size = %{public}zu", sortingMap->GetKey().size()); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(updateCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); + if (dataWorker == nullptr) { + ANS_LOGE("new dataWorker failed"); + return; + } + + dataWorker->sortingMap = sortingMap; + dataWorker->env = updateCallbackInfo_.env; + dataWorker->ref = updateCallbackInfo_.ref; + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + ANS_LOGE("new work failed"); + return; + } + + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnUpdate uv_work_t start"); + + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + napi_value result = nullptr; + napi_create_object(dataWorkerData->env, &result); + int error = 0; + if (!Common::SetNotificationSortingMap(dataWorkerData->env, dataWorkerData->sortingMap, result)) { + result = Common::NapiGetNull(dataWorkerData->env); + error = ERROR; + } else { + error = NO_ERROR; + } + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult result) +{ + ANS_LOGI("enter"); + + if (subscribeCallbackInfo_.ref == nullptr) { + ANS_LOGI("subscribe callback unset"); + return; + } + ANS_LOGI("OnSubscribeResult result = %{public}d", result); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(subscribeCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); + if (dataWorker == nullptr) { + ANS_LOGE("new dataWorker failed"); + return; + } + + dataWorker->result = (int)result; + dataWorker->env = subscribeCallbackInfo_.env; + dataWorker->ref = subscribeCallbackInfo_.ref; + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + ANS_LOGE("new work failed"); + return; + } + + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnSubscribeResult uv_work_t start"); + + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + // result: number + napi_value result = nullptr; + napi_create_int32(dataWorkerData->env, dataWorkerData->result, &result); + + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) +{ + ANS_LOGI("enter"); + + if (unsubscribeCallbackInfo_.ref == nullptr) { + ANS_LOGI("unsubscribe callback unset"); + return; + } + ANS_LOGI("OnUnsubscribeResult result = %{public}d", result); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(unsubscribeCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); + if (dataWorker == nullptr) { + ANS_LOGE("new dataWorker failed"); + return; + } + + dataWorker->result = (int)result; + dataWorker->env = unsubscribeCallbackInfo_.env; + dataWorker->ref = unsubscribeCallbackInfo_.ref; + dataWorker->subscriber = this; + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + ANS_LOGE("new work failed"); + return; + } + + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnUnsubscribeResult uv_work_t start"); + + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + // result: number + napi_value result = nullptr; + napi_create_int32(dataWorkerData->env, dataWorkerData->result, &result); + + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); + + DelSubscriberInstancesInfo(dataWorkerData->env, dataWorkerData->subscriber); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnDied() +{ + ANS_LOGI("enter"); + + if (dieCallbackInfo_.ref == nullptr) { + ANS_LOGE("die callback unset"); + return; + } + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(dieCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); + if (dataWorker == nullptr) { + ANS_LOGE("new dataWorker failed"); + return; + } + + dataWorker->env = dieCallbackInfo_.env; + dataWorker->ref = dieCallbackInfo_.ref; + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + ANS_LOGE("new work failed"); + return; + } + + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnDied uv_work_t start"); + + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + + Common::SetCallback( + dataWorkerData->env, dataWorkerData->ref, NO_ERROR, Common::NapiGetNull(dataWorkerData->env)); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnDisturbModeChanged(int disturbMode) +{ + ANS_LOGI("enter"); + + if (disturbModeCallbackInfo_.ref == nullptr) { + ANS_LOGI("disturbModeChange callback unset"); + return; + } + ANS_LOGI("OnDisturbModeChanged disturbMode = %{public}d", disturbMode); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(disturbModeCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); + if (dataWorker == nullptr) { + ANS_LOGE("new dataWorker failed"); + return; + } + + dataWorker->disturbMode = disturbMode; + dataWorker->env = disturbModeCallbackInfo_.env; + dataWorker->ref = disturbModeCallbackInfo_.ref; + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + ANS_LOGE("new work failed"); + return; + } + + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnDisturbModeChanged uv_work_t start"); + + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + // disturbMode: number + napi_value result = nullptr; + napi_create_int32(dataWorkerData->env, dataWorkerData->disturbMode, &result); + + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + canceCallbackInfo_.env = env; + canceCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + consumeCallbackInfo_.env = env; + consumeCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + updateCallbackInfo_.env = env; + updateCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + subscribeCallbackInfo_.env = env; + subscribeCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + unsubscribeCallbackInfo_.env = env; + unsubscribeCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetDieCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + dieCallbackInfo_.env = env; + dieCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + disturbModeCallbackInfo_.env = env; + disturbModeCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref) +{ + if (type == CONSUME) { + SetConsumeCallbackInfo(env, ref); + } else if (type == CANCEL) { + SetCancelCallbackInfo(env, ref); + } else if (type == UPDATE) { + SetUpdateCallbackInfo(env, ref); + } else if (type == CONNECTED) { + SetSubscribeCallbackInfo(env, ref); + } else if (type == DIS_CONNECTED) { + SetUnsubscribeCallbackInfo(env, ref); + } else if (type == DIE) { + SetDieCallbackInfo(env, ref); + } else if (type == DISTURB_MODE_CHANGE) { + SetDisturbModeCallbackInfo(env, ref); + } else { + ANS_LOGW("type is error"); + } +} struct AsyncCallbackInfoSubscribe { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = 0; - napi_deferred deferred; + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; SubscriberInstance *objectInfo = nullptr; - NotificationSubscriberInfo subscriberInfo; - bool isCallback = false; - int errorCode = 0; + NotificationSubscribeInfo subscriberInfo; + CallbackPromiseInfo info; }; -napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[SUBSRIBE_MAX_PARA], const size_t &argc, - NotificationSubscriberInfo &subscriberInfo, SubscriberInstance *&objectInfo, napi_ref &callback) +bool HasNotificationSubscriber(const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo) { + std::lock_guard lock(mutex_); + for (auto vec : subscriberInstances_) { + napi_value callback = nullptr; + napi_get_reference_value(env, vec.ref, &callback); + bool isEquals = false; + napi_strict_equals(env, value, callback, &isEquals); + if (isEquals) { + subscriberInfo = vec; + return true; + } + } + return false; +} - 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_value GetNotificationSubscriber( + const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo) +{ + ANS_LOGI("enter"); + bool hasProperty = false; + napi_valuetype valuetype = napi_undefined; + napi_ref result = nullptr; - napi_unwrap(env, argv[0], (void **)&objectInfo); - if (!objectInfo) { - ANS_LOGE("ParseParameters subscriberInstance is null"); + subscriberInfo.subscriber = new (std::nothrow) SubscriberInstance(); + if (subscriberInfo.subscriber == nullptr) { + ANS_LOGE("subscriber is null"); return nullptr; } - ANS_LOGI("ParseParameters subscriberInstance = %{public}p start", objectInfo); + napi_create_reference(env, value, 1, &subscriberInfo.ref); - if (!HasNotificationSubscriber(objectInfo)) { - return nullptr; + // onConsumed?:(data: SubscribeCallbackData) => void; + NAPI_CALL(env, napi_has_named_property(env, value, "onConsumed", &hasProperty)); + if (hasProperty) { + napi_value nOnConsumed = nullptr; + napi_get_named_property(env, value, "onConsumed", &nOnConsumed); + NAPI_CALL(env, napi_typeof(env, nOnConsumed, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, nOnConsumed, 1, &result); + subscriberInfo.subscriber->SetCallbackInfo(env, CONSUME, result); + } + // onCanceled?:(data: SubscribeCallbackData) => void; + NAPI_CALL(env, napi_has_named_property(env, value, "onCanceled", &hasProperty)); + if (hasProperty) { + napi_value nOnCanceled = nullptr; + napi_get_named_property(env, value, "onCanceled", &nOnCanceled); + NAPI_CALL(env, napi_typeof(env, nOnCanceled, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, nOnCanceled, 1, &result); + subscriberInfo.subscriber->SetCallbackInfo(env, CANCEL, result); + } + // onUpdate?:(data: NotificationSortingMap) => void; + NAPI_CALL(env, napi_has_named_property(env, value, "onUpdate", &hasProperty)); + if (hasProperty) { + napi_value nOnUpdate = nullptr; + napi_get_named_property(env, value, "onUpdate", &nOnUpdate); + NAPI_CALL(env, napi_typeof(env, nOnUpdate, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, nOnUpdate, 1, &result); + subscriberInfo.subscriber->SetCallbackInfo(env, UPDATE, result); + } + // onConnected?:() => void; + NAPI_CALL(env, napi_has_named_property(env, value, "onConnected", &hasProperty)); + if (hasProperty) { + napi_value nOnConnected = nullptr; + napi_get_named_property(env, value, "onConnected", &nOnConnected); + NAPI_CALL(env, napi_typeof(env, nOnConnected, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, nOnConnected, 1, &result); + subscriberInfo.subscriber->SetCallbackInfo(env, CONNECTED, result); + } + // onDisConnect?:() => void; + NAPI_CALL(env, napi_has_named_property(env, value, "onDisConnect", &hasProperty)); + if (hasProperty) { + napi_value nOnDisConnect = nullptr; + napi_get_named_property(env, value, "onDisConnect", &nOnDisConnect); + NAPI_CALL(env, napi_typeof(env, nOnDisConnect, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, nOnDisConnect, 1, &result); + subscriberInfo.subscriber->SetCallbackInfo(env, DIS_CONNECTED, result); + } + // onDied?:() => void; + NAPI_CALL(env, napi_has_named_property(env, value, "onDied", &hasProperty)); + if (hasProperty) { + napi_value nOnDied = nullptr; + napi_get_named_property(env, value, "onDied", &nOnDied); + NAPI_CALL(env, napi_typeof(env, nOnDied, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, nOnDied, 1, &result); + subscriberInfo.subscriber->SetCallbackInfo(env, DIE, result); } - ANS_LOGI("================ParseParameters 1111111111111111111111================="); - // argv[1]:callback/NotificationSubscriberInfo - if (argc >= 2) { + // onDisturbModeChanged?:(mode: notification.DoNotDisturbMode) => void; + NAPI_CALL(env, napi_has_named_property(env, value, "onDisturbModeChanged", &hasProperty)); + if (hasProperty) { + napi_value nOnDisturbModeChanged = nullptr; + napi_get_named_property(env, value, "onDisturbModeChanged", &nOnDisturbModeChanged); + NAPI_CALL(env, napi_typeof(env, nOnDisturbModeChanged, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, nOnDisturbModeChanged, 1, &result); + subscriberInfo.subscriber->SetCallbackInfo(env, DISTURB_MODE_CHANGE, result); + } + + return Common::NapiGetNull(env); +} + +bool AddSubscriberInstancesInfo(const napi_env &env, const SubscriberInstancesInfo &subscriberInfo) +{ + ANS_LOGI("enter"); + if (subscriberInfo.ref == nullptr) { + ANS_LOGE("subscriberInfo.ref is null"); + return false; + } + if (subscriberInfo.subscriber == nullptr) { + ANS_LOGE("subscriberInfo.subscriber is null"); + return false; + } + std::lock_guard lock(mutex_); + subscriberInstances_.emplace_back(subscriberInfo); + + return true; +} + +bool DelSubscriberInstancesInfo(const napi_env &env, SubscriberInstance *subscriber) +{ + ANS_LOGI("enter"); + if (subscriber == nullptr) { + ANS_LOGE("subscriber is null"); + return false; + } + + std::lock_guard lock(mutex_); + for (auto it = subscriberInstances_.begin(); it != subscriberInstances_.end(); ++it) { + if ((*it).subscriber == subscriber) { + if ((*it).ref != nullptr) { + napi_delete_reference(env, (*it).ref); + } + delete (*it).subscriber; + (*it).subscriber = nullptr; + subscriberInstances_.erase(it); + return true; + } + } + return false; +} +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, + NotificationSubscribeInfo &subscriberInfo, SubscriberInstance *&subscriber, napi_ref &callback) +{ + ANS_LOGI("enter"); + + size_t argc = SUBSRIBE_MAX_PARA; + napi_value argv[SUBSRIBE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + + napi_valuetype valuetype = napi_undefined; + + // argv[0]:subscriber + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. NotificationSubscriber object expected."); + + SubscriberInstancesInfo subscriberInstancesInfo; + if (!HasNotificationSubscriber(env, argv[0], subscriberInstancesInfo)) { + if (GetNotificationSubscriber(env, argv[0], subscriberInstancesInfo) == nullptr) { + ANS_LOGE("NotificationSubscriber parse failed"); + return nullptr; + } + if (!AddSubscriberInstancesInfo(env, subscriberInstancesInfo)) { + ANS_LOGE("AddSubscriberInstancesInfo add failed"); + return nullptr; + } + } + subscriber = subscriberInstancesInfo.subscriber; + + // argv[1]:callback or NotificationSubscribeInfo + if (argc >= SUBSRIBE_MAX_PARA - 1) { 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) { + NotificationSubscribeInfo subscriberInfo; + 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 = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); - napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); - - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "subscribeNotification", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -127,14 +934,14 @@ napi_value Subscribe(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("Subscribe napi_create_async_work start"); AsyncCallbackInfoSubscribe *asynccallbackinfo = (AsyncCallbackInfoSubscribe *)data; - if (asynccallbackinfo->subscriberInfo.hasSubscriberInfo) { - ANS_LOGI("Subscribe There are NotificationSubscribeInfo"); - NotificationSubscribeInfo subscribeInfo; + if (asynccallbackinfo->subscriberInfo.hasSubscribeInfo) { + ANS_LOGI("Subscribe with NotificationSubscribeInfo"); + OHOS::Notification::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 +949,11 @@ 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)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -160,7 +966,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 babc54fbfcae8f8f4ae6f8d95102869d644874ed..659c9e59dd459c776990fbf5e5b5dcddbc2489d9 100644 --- a/interfaces/kits/napi/ans/src/unsubscribe.cpp +++ b/interfaces/kits/napi/ans/src/unsubscribe.cpp @@ -14,94 +14,73 @@ */ #include "unsubscribe.h" -#include "create_subscriber.h" +#include "subscribe.h" namespace OHOS { namespace NotificationNapi { const int UNSUBSCRIBE_MAX_PARA = 2; struct AsyncCallbackInfoUnsubscribe { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = 0; - napi_deferred deferred; + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; 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] = {nullptr}; + 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; + napi_valuetype valuetype = napi_undefined; // 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_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. Subscribe object expected."); - napi_unwrap(env, argv[0], (void **)&objectInfo); - if (!objectInfo) { - ANS_LOGE("ParseParameters objectInfo is null"); - return nullptr; - } - - ANS_LOGI("ParseParameters objectInfo = %{public}p start", objectInfo); - - if (!HasNotificationSubscriber(objectInfo)) { + SubscriberInstancesInfo subscriberInstancesInfo; + if (!HasNotificationSubscriber(env, argv[0], subscriberInstancesInfo)) { return nullptr; } + paras.objectInfo = subscriberInstancesInfo.subscriber; + ANS_LOGI("ObjectInfo = %{public}p start", paras.objectInfo); // argv[1]:callback 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}; - - napi_value promise = 0; - PaddingAsyncCallbackInfoIs(env, argc, asynccallbackinfo, callback, promise); + AsyncCallbackInfoUnsubscribe{.env = env, .asyncWork = nullptr, .objectInfo = paras.objectInfo}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, paras.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); - napi_value resourceName; + napi_value resourceName = nullptr; napi_create_string_latin1(env, "Unsubscribe", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call @@ -112,21 +91,18 @@ 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); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { @@ -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 411937c4cf6955c08c9201e7d591730932fea113..0f347104567df4e611070f034de13430afd674d2 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.cpp +++ b/interfaces/kits/napi/wantagent/napi_want_agent.cpp @@ -55,9 +55,14 @@ void TriggerCompleteCallBack::OnSendFinished( return; } uv_loop_s *loop = nullptr; -#if NAPI_VERSION >= 2 +#if NAPI_VERSION >= NUMBER_OF_PARAMETERS_TWO napi_get_uv_event_loop(triggerCompleteInfo_.env, &loop); #endif // NAPI_VERSION >= 2 + if (loop == nullptr) { + HILOG_INFO("loop instance is nullptr"); + return; + } + uv_work_t *work = new (std::nothrow) uv_work_t; if (work == nullptr) { HILOG_INFO("uv_work_t instance is nullptr"); @@ -66,6 +71,8 @@ void TriggerCompleteCallBack::OnSendFinished( TriggerReceiveDataWorker *dataWorker = new (std::nothrow) TriggerReceiveDataWorker(); if (dataWorker == nullptr) { HILOG_INFO("TriggerReceiveDataWorker instance is nullptr"); + delete work; + work = nullptr; return; } dataWorker->want = want; @@ -85,7 +92,7 @@ void TriggerCompleteCallBack::OnSendFinished( HILOG_INFO("TriggerReceiveDataWorker instance(uv_work_t) is nullptr"); return; } - napi_value result[2] = {0}; + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; napi_value callback; napi_value undefined; napi_value callResult = 0; @@ -135,7 +142,8 @@ void TriggerCompleteCallBack::OnSendFinished( napi_get_undefined(dataWorkerData->env, &undefined); napi_get_reference_value(dataWorkerData->env, dataWorkerData->ref, &callback); - napi_call_function(dataWorkerData->env, undefined, callback, 2, &result[0], &callResult); + napi_call_function( + dataWorkerData->env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); delete dataWorkerData; dataWorkerData = nullptr; @@ -176,16 +184,16 @@ napi_value WantAgentFlagsInit(napi_env env, napi_value exports) napi_value obj = nullptr; napi_create_object(env, &obj); - SetNamedPropertyByInteger(env, obj, 0, "ONE_TIME_FLAG"); - SetNamedPropertyByInteger(env, obj, 1, "NO_BUILD_FLAG"); - SetNamedPropertyByInteger(env, obj, 2, "CANCEL_PRESENT_FLAG"); - SetNamedPropertyByInteger(env, obj, 3, "UPDATE_PRESENT_FLAG"); - SetNamedPropertyByInteger(env, obj, 4, "CONSTANT_FLAG"); - SetNamedPropertyByInteger(env, obj, 5, "REPLACE_ELEMENT"); - SetNamedPropertyByInteger(env, obj, 6, "REPLACE_ACTION"); - SetNamedPropertyByInteger(env, obj, 7, "REPLACE_URI"); - SetNamedPropertyByInteger(env, obj, 8, "REPLACE_ENTITIES"); - SetNamedPropertyByInteger(env, obj, 9, "REPLACE_BUNDLE"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_ZERO, "ONE_TIME_FLAG"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_ONE, "NO_BUILD_FLAG"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_TWO, "CANCEL_PRESENT_FLAG"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_THREE, "UPDATE_PRESENT_FLAG"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_FOUR, "CONSTANT_FLAG"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_FIVE, "REPLACE_ELEMENT"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_SIX, "REPLACE_ACTION"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_SEVEN, "REPLACE_URI"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_EIGHT, "REPLACE_ENTITIES"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_NINE, "REPLACE_BUNDLE"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("Flags", obj), @@ -202,12 +210,12 @@ napi_value WantAgentOperationTypeInit(napi_env env, napi_value exports) napi_value obj = nullptr; napi_create_object(env, &obj); - SetNamedPropertyByInteger(env, obj, 0, "UNKNOWN_TYPE"); - SetNamedPropertyByInteger(env, obj, 1, "START_ABILITY"); - SetNamedPropertyByInteger(env, obj, 2, "START_ABILITIES"); - SetNamedPropertyByInteger(env, obj, 3, "START_SERVICE"); - SetNamedPropertyByInteger(env, obj, 4, "SEND_COMMON_EVENT"); - SetNamedPropertyByInteger(env, obj, 5, "START_FOREGROUND_SERVICE"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_ZERO, "UNKNOWN_TYPE"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_ONE, "START_ABILITY"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_TWO, "START_ABILITIES"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_THREE, "START_SERVICE"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_FOUR, "SEND_COMMON_EVENT"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_FIVE, "START_FOREGROUND_SERVICE"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("OperationType", obj), @@ -236,7 +244,7 @@ napi_value NAPI_GetBundleNameWrap( [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetBundleName compeleted(CallBack Mode)..."); AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = (AsyncGetBundleNameCallbackInfo *)data; - napi_value result[2] = {0}; + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; napi_value callback; napi_value undefined; napi_value callResult = 0; @@ -245,7 +253,7 @@ napi_value NAPI_GetBundleNameWrap( napi_create_string_utf8(env, asyncCallbackInfo->bundleName.c_str(), NAPI_AUTO_LENGTH, &result[1]); napi_get_undefined(env, &undefined); napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); - napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); if (asyncCallbackInfo->callback[0] != nullptr) { napi_delete_reference(env, asyncCallbackInfo->callback[0]); @@ -296,7 +304,7 @@ napi_value NAPI_GetBundleNameWrap( napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) { - size_t argc = 2; + size_t argc = NUMBER_OF_PARAMETERS_TWO; napi_value argv[argc]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); @@ -313,7 +321,7 @@ napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) } bool callBackMode = false; - if (argc >= 2) { + if (argc >= NUMBER_OF_PARAMETERS_TWO) { napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); @@ -356,7 +364,7 @@ napi_value NAPI_GetUidWrap( [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetUid compeleted(CallBack Mode)..."); AsyncGetUidCallbackInfo *asyncCallbackInfo = (AsyncGetUidCallbackInfo *)data; - napi_value result[2] = {0}; + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; napi_value callback; napi_value undefined; napi_value callResult = 0; @@ -365,7 +373,7 @@ napi_value NAPI_GetUidWrap( napi_create_int32(env, asyncCallbackInfo->uid, &result[1]); napi_get_undefined(env, &undefined); napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); - napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); if (asyncCallbackInfo->callback[0] != nullptr) { napi_delete_reference(env, asyncCallbackInfo->callback[0]); @@ -416,7 +424,7 @@ napi_value NAPI_GetUidWrap( napi_value NAPI_GetUid(napi_env env, napi_callback_info info) { - size_t argc = 2; + size_t argc = NUMBER_OF_PARAMETERS_TWO; napi_value argv[argc]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); @@ -432,7 +440,7 @@ napi_value NAPI_GetUid(napi_env env, napi_callback_info info) } bool callBackMode = false; - if (argc >= 2) { + if (argc >= NUMBER_OF_PARAMETERS_TWO) { napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); @@ -475,7 +483,7 @@ napi_value NAPI_GetWantWrap( [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetWant compeleted(CallBack Mode)..."); AsyncGetWantCallbackInfo *asyncCallbackInfo = (AsyncGetWantCallbackInfo *)data; - napi_value result[2] = {0}; + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; napi_value callback; napi_value undefined; napi_value callResult = 0; @@ -484,7 +492,7 @@ napi_value NAPI_GetWantWrap( result[1] = WrapWant(env, *(asyncCallbackInfo->want)); napi_get_undefined(env, &undefined); napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); - napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); if (asyncCallbackInfo->callback[0] != nullptr) { napi_delete_reference(env, asyncCallbackInfo->callback[0]); } @@ -534,7 +542,7 @@ napi_value NAPI_GetWantWrap( napi_value NAPI_GetWant(napi_env env, napi_callback_info info) { - size_t argc = 2; + size_t argc = NUMBER_OF_PARAMETERS_TWO; napi_value argv[argc]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); @@ -550,7 +558,7 @@ napi_value NAPI_GetWant(napi_env env, napi_callback_info info) } bool callBackMode = false; - if (argc >= 2) { + if (argc >= NUMBER_OF_PARAMETERS_TWO) { napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); @@ -604,14 +612,14 @@ napi_value NAPI_CancelWrap( [](napi_env env, void *data) { HILOG_INFO("Cancel called(CallBack Mode)..."); AsyncCancelCallbackInfo *asyncCallbackInfo = (AsyncCancelCallbackInfo *)data; - WantAgentHelper::Cancel(asyncCallbackInfo->wantAgent); int32_t code = WantAgentHelper::GetHashCode(asyncCallbackInfo->wantAgent); + WantAgentHelper::Cancel(asyncCallbackInfo->wantAgent); DeleteRecordByCode(code); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("Cancel compeleted(CallBack Mode)..."); AsyncCancelCallbackInfo *asyncCallbackInfo = (AsyncCancelCallbackInfo *)data; - napi_value result[2] = {0}; + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; napi_value callback; napi_value undefined; napi_value callResult = 0; @@ -620,7 +628,7 @@ napi_value NAPI_CancelWrap( napi_get_null(env, &result[1]); napi_get_undefined(env, &undefined); napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); - napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); if (asyncCallbackInfo->callback[0] != nullptr) { napi_delete_reference(env, asyncCallbackInfo->callback[0]); @@ -651,8 +659,8 @@ napi_value NAPI_CancelWrap( [](napi_env env, void *data) { HILOG_INFO("Cancel called(Promise Mode)..."); AsyncCancelCallbackInfo *asyncCallbackInfo = (AsyncCancelCallbackInfo *)data; - WantAgentHelper::Cancel(asyncCallbackInfo->wantAgent); int32_t code = WantAgentHelper::GetHashCode(asyncCallbackInfo->wantAgent); + WantAgentHelper::Cancel(asyncCallbackInfo->wantAgent); DeleteRecordByCode(code); }, [](napi_env env, napi_status status, void *data) { @@ -673,7 +681,7 @@ napi_value NAPI_CancelWrap( napi_value NAPI_Cancel(napi_env env, napi_callback_info info) { - size_t argc = 2; + size_t argc = NUMBER_OF_PARAMETERS_TWO; napi_value argv[argc]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); @@ -689,7 +697,7 @@ napi_value NAPI_Cancel(napi_env env, napi_callback_info info) } bool callBackMode = false; - if (argc >= 2) { + if (argc >= NUMBER_OF_PARAMETERS_TWO) { napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); @@ -750,7 +758,7 @@ napi_value NAPI_TriggerWrap(napi_env env, napi_callback_info info, AsyncTriggerC napi_value NAPI_Trigger(napi_env env, napi_callback_info info) { - size_t argc = 3; + size_t argc = NUMBER_OF_PARAMETERS_THREE; napi_value argv[argc]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); @@ -810,9 +818,9 @@ napi_value NAPI_Trigger(napi_env env, napi_callback_info info) context = ability->GetContext(); bool callBackMode = false; - if (argc >= 3) { + if (argc >= NUMBER_OF_PARAMETERS_THREE) { napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[NUMBER_OF_PARAMETERS_TWO], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); callBackMode = true; } @@ -829,7 +837,7 @@ napi_value NAPI_Trigger(napi_env env, napi_callback_info info) if (callBackMode) { asyncCallbackInfo->callBackMode = callBackMode; asyncCallbackInfo->triggerObj = std::make_shared(); - napi_create_reference(env, argv[2], 1, &asyncCallbackInfo->callback[0]); + napi_create_reference(env, argv[NUMBER_OF_PARAMETERS_TWO], 1, &asyncCallbackInfo->callback[0]); } napi_value ret = NAPI_TriggerWrap(env, info, asyncCallbackInfo); @@ -860,7 +868,7 @@ napi_value NAPI_EqualWrap( [](napi_env env, napi_status status, void *data) { HILOG_INFO("Equal compeleted(CallBack Mode)..."); AsyncEqualCallbackInfo *asyncCallbackInfo = (AsyncEqualCallbackInfo *)data; - napi_value result[2] = {0}; + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; napi_value callback; napi_value undefined; napi_value callResult = 0; @@ -869,7 +877,7 @@ napi_value NAPI_EqualWrap( napi_get_boolean(env, asyncCallbackInfo->result, &result[1]); napi_get_undefined(env, &undefined); napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); - napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); if (asyncCallbackInfo->callback[0] != nullptr) { napi_delete_reference(env, asyncCallbackInfo->callback[0]); @@ -921,7 +929,7 @@ napi_value NAPI_EqualWrap( napi_value NAPI_Equal(napi_env env, napi_callback_info info) { - size_t argc = 3; + size_t argc = NUMBER_OF_PARAMETERS_THREE; napi_value argv[argc]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); @@ -947,9 +955,9 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info) } bool callBackMode = false; - if (argc >= 3) { + if (argc >= NUMBER_OF_PARAMETERS_THREE) { napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[NUMBER_OF_PARAMETERS_TWO], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); callBackMode = true; } @@ -962,7 +970,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[NUMBER_OF_PARAMETERS_TWO], 1, &asyncCallbackInfo->callback[0]); } napi_value ret = NAPI_EqualWrap(env, info, callBackMode, asyncCallbackInfo); if (ret == nullptr) { @@ -1003,7 +1011,7 @@ napi_value NAPI_GetWantAgentWrap( [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetWantAgent compeleted(CallBack Mode)..."); AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = (AsyncGetWantAgentCallbackInfo *)data; - napi_value result[2] = {0}; + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; napi_value callback; napi_value undefined; napi_value callResult = 0; @@ -1032,7 +1040,7 @@ napi_value NAPI_GetWantAgentWrap( nullptr); napi_get_undefined(env, &undefined); napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); - napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); if (asyncCallbackInfo->callback[0] != nullptr) { napi_delete_reference(env, asyncCallbackInfo->callback[0]); @@ -1116,7 +1124,7 @@ napi_value NAPI_GetWantAgentWrap( napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) { - size_t argc = 2; + size_t argc = NUMBER_OF_PARAMETERS_TWO; napi_value argv[argc]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); @@ -1204,7 +1212,7 @@ napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) context = ability->GetContext(); bool callBackMode = false; - if (argc >= 2) { + if (argc >= NUMBER_OF_PARAMETERS_TWO) { napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); diff --git a/interfaces/kits/napi/wantagent/napi_want_agent.h b/interfaces/kits/napi/wantagent/napi_want_agent.h index 90b67e8e97b31fe8d546b49ba421d6fe4d8e5ca3..e5bf33c25f0fca3a67a4c56a935a904371d2d320 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.h +++ b/interfaces/kits/napi/wantagent/napi_want_agent.h @@ -38,6 +38,17 @@ using namespace OHOS::AppExecFwk; using namespace OHOS::Notification; using namespace OHOS::Notification::WantAgent; +const uint8_t NUMBER_OF_PARAMETERS_ZERO = 0; +const uint8_t NUMBER_OF_PARAMETERS_ONE = 1; +const uint8_t NUMBER_OF_PARAMETERS_TWO = 2; +const uint8_t NUMBER_OF_PARAMETERS_THREE = 3; +const uint8_t NUMBER_OF_PARAMETERS_FOUR = 4; +const uint8_t NUMBER_OF_PARAMETERS_FIVE = 5; +const uint8_t NUMBER_OF_PARAMETERS_SIX = 6; +const uint8_t NUMBER_OF_PARAMETERS_SEVEN = 7; +const uint8_t NUMBER_OF_PARAMETERS_EIGHT = 8; +const uint8_t NUMBER_OF_PARAMETERS_NINE = 9; + class TriggerCompleteCallBack; struct AsyncGetWantAgentCallbackInfo { diff --git a/ohos.build b/ohos.build index c196545802adf69d99def0adf86ffbc64d21cf73..747cde429e369f12c3689bc4e4b002f292cd031c 100644 --- a/ohos.build +++ b/ohos.build @@ -13,7 +13,9 @@ "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/wantagent/test/:unittest" + "//base/notification/ans_standard/frameworks/ans/test/moduletest:moduletest", + "//base/notification/ans_standard/frameworks/wantagent/test/:unittest", + "//base/notification/ans_standard/test:systemtest" ] } }, diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 8bd0738dffb4555a410cebb8d9ad2a3fc21815f3..60cfff6ba1fd54de3d85271d73f571ceab7d550f 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -29,6 +29,7 @@ #include "distributed_kv_data_manager.h" #include "distributed_kvstore_death_recipient.h" #include "notification.h" +#include "notification_bundle_option.h" #include "notification_record.h" #include "notification_sorting_map.h" #include "system_event_observer.h" @@ -47,13 +48,16 @@ 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; ErrCode GetSlotGroup(const std::string &groupId, sptr &group) override; ErrCode GetSlotGroups(std::vector> &groups) override; + ErrCode GetSlotNumAsBundle(const sptr &bundleOption, int &num) override; ErrCode RemoveSlotGroups(const std::vector &groupIds) override; ErrCode GetActiveNotifications(std::vector> ¬ifications) override; ErrCode GetActiveNotificationNums(int &num) override; @@ -72,28 +76,35 @@ public: ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; ErrCode SetPrivateNotificationsAllowed(bool allow) override; ErrCode GetPrivateNotificationsAllowed(bool &allow) override; + ErrCode RemoveNotification( + const sptr &bundleOption, int notificationId, const std::string &label) override; + ErrCode RemoveAllNotifications(const sptr &bundleOption) override; ErrCode Delete(const std::string &key) override; - ErrCode DeleteByBundle(const std::string &bundle) override; + ErrCode DeleteByBundle(const sptr &bundleOption) override; ErrCode DeleteAll() override; - ErrCode GetSlotsByBundle(const std::string &bundle, std::vector> &slots) override; - ErrCode UpdateSlots(const std::string &bundle, const std::vector> &slots) override; - ErrCode UpdateSlotGroups( - const std::string &bundle, const std::vector> &groups) override; + + ErrCode GetSlotsByBundle( + const sptr &bundleOption, std::vector> &slots) override; + ErrCode UpdateSlots( + const sptr &bundleOption, const std::vector> &slots) override; + ErrCode UpdateSlotGroups(const sptr &bundleOption, + const std::vector> &groups) override; ErrCode SetNotificationsEnabledForBundle(const std::string &bundle, bool enabled) override; ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) override; ErrCode SetNotificationsEnabledForSpecialBundle( - 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; + const std::string &deviceId, const sptr &bundleOption, bool enabled) override; + ErrCode SetShowBadgeEnabledForBundle(const sptr &bundleOption, bool enabled) override; + ErrCode GetShowBadgeEnabledForBundle(const sptr &bundleOption, 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; - ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) override; + ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override; ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; // SystemEvent - void OnBundleRemoved(const std::string &bundle); + void OnBundleRemoved(const sptr &bundleOption); // Distributed KvStore void OnDistributedKvStoreDeathRecipient(); @@ -108,10 +119,10 @@ private: void AddToNotificationList(const std::shared_ptr &record); void UpdateInNotificationList(const std::shared_ptr &record); - ErrCode RemoveFromNotificationList(const std::string &bundle, const std::string &label, int notificationId, - sptr ¬ification, bool isCancel = false); + ErrCode RemoveFromNotificationList(const sptr &bundleOption, const std::string &label, + int notificationId, sptr ¬ification, bool isCancel = false); ErrCode RemoveFromNotificationList(const std::string &key, sptr ¬ification, bool isCancel = false); - std::vector GetNotificationKeys(const std::string &bundle); + std::vector GetNotificationKeys(const sptr &bundleOption); bool IsNotificationExists(const std::string &key); void SortNotificationList(); static bool NotificationCompare( @@ -119,6 +130,8 @@ private: ErrCode FlowControl(const std::shared_ptr &record); sptr GenerateSortingMap(); + sptr GenerateBundleOption(); + sptr GenerateValidBundleOption(const sptr &bundleOption); std::string TimeToString(int64_t time); int64_t GetNowSysTime(); diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index 0e8936727857059b77fc5da4d8e88fad734762c4..bb8dc8169f727c85d7c76cd9043379b08c466d73 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -32,8 +32,9 @@ 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); + int GetDefaultUidByBundleName(const std::string& bundle); private: void Connect(); diff --git a/services/ans/include/interface_system_event.h b/services/ans/include/interface_system_event.h index 52075fded1c02d063669f756e728439df0fe48f9..b4aba38fcbc2d2b0886146ae80adae52b53b7b4c 100644 --- a/services/ans/include/interface_system_event.h +++ b/services/ans/include/interface_system_event.h @@ -19,11 +19,13 @@ #include #include +#include "notification_bundle_option.h" + namespace OHOS { namespace Notification { struct ISystemEvent { - std::function onBundleRemoved; + std::function &)> onBundleRemoved; }; } // namespace Notification diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index c2d476978cfe76982811916b929e3a0643bde0a8..bfd654130a34b53ca716a9f1c9702c2b9190f7c1 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -21,40 +21,44 @@ #include "notification_preferences_database.h" + namespace OHOS { namespace Notification { class NotificationPreferences final { public: DISALLOW_COPY_AND_MOVE(NotificationPreferences); static NotificationPreferences &GetInstance(); - ErrCode AddNotificationSlots(const std::string &bundleName, const std::vector> &slots); + ErrCode AddNotificationSlots(const sptr &bundleOption, const std::vector> &slots); ErrCode AddNotificationSlotGroups( - const std::string &bundleName, const std::vector> &groups); - ErrCode RemoveNotificationSlot(const std::string &bundleName, const NotificationConstant::SlotType &slotType); - 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); + const sptr &bundleOption, const std::vector> &groups); + ErrCode AddNotificationBundleProperty(const sptr &bundleOption); + ErrCode RemoveNotificationSlot(const sptr &bundleOption, const NotificationConstant::SlotType &slotType); + ErrCode RemoveNotificationAllSlots(const sptr &bundleOption); + ErrCode RemoveNotificationSlotGroups(const sptr &bundleOption, const std::vector &groupIds); + ErrCode RemoveNotificationForBundle(const sptr &bundleOption); + ErrCode UpdateNotificationSlots(const sptr &bundleOption, const std::vector> &slot); ErrCode UpdateNotificationSlotGroups( - const std::string &bundleName, const std::vector> &groups); + const sptr &bundleOption, const std::vector> &groups); ErrCode GetNotificationSlot( - const std::string &bundleName, const NotificationConstant::SlotType &type, sptr &slot); - ErrCode GetNotificationAllSlots(const std::string &bundleName, std::vector> &slots); + const sptr &bundleOption, const NotificationConstant::SlotType &type, sptr &slot); + ErrCode GetNotificationAllSlots(const sptr &bundleOption, std::vector> &slots); + ErrCode GetNotificationSlotsNumForBundle(const sptr &bundleOption, int &num); ErrCode GetNotificationSlotGroup( - const std::string &bundleName, const std::string &groupId, sptr &group); + const sptr &bundleOption, const std::string &groupId, sptr &group); ErrCode GetNotificationAllSlotGroups( - const std::string &bundleName, std::vector> &groups); + const sptr &bundleOption, std::vector> &groups); ErrCode GetNotificationAllSlotInSlotGroup( - const std::string &bundleName, const std::string &groupId, std::vector> &slots); - ErrCode IsShowBadge(const std::string &bundleName, bool &enable); - ErrCode SetShowBadge(const std::string &bundleName, const bool enable); - ErrCode GetImportance(const std::string &bundleName, int &importance); - ErrCode SetImportance(const std::string &bundleName, const int &importance); - ErrCode GetTotalBadgeNums(const std::string &bundleName, int &totalBadgeNum); - ErrCode SetTotalBadgeNums(const std::string &bundleName, const int num); - ErrCode GetPrivateNotificationsAllowed(const std::string &bundleName, bool &allow); - ErrCode SetPrivateNotificationsAllowed(const std::string &bundleName, const bool allow); - ErrCode GetNotificationsEnabledForBundle(const std::string &bundleName, bool &enabled); - ErrCode SetNotificationsEnabledForBundle(const std::string &bundleName, const bool enabled); + const sptr &bundleOption, const std::string &groupId, std::vector> &slots); + ErrCode IsShowBadge(const sptr &bundleOption, bool &enable); + ErrCode SetShowBadge(const sptr &bundleOption, const bool enable); + ErrCode GetImportance(const sptr &bundleOption, int &importance); + ErrCode SetImportance(const sptr &bundleOption, const int &importance); + ErrCode GetTotalBadgeNums(const sptr &bundleOption, int &totalBadgeNum); + ErrCode SetTotalBadgeNums(const sptr &bundleOption, const int num); + ErrCode GetPrivateNotificationsAllowed(const sptr &bundleOption, bool &allow); + ErrCode SetPrivateNotificationsAllowed(const sptr &bundleOption, const bool allow); + ErrCode GetNotificationsEnabledForBundle(const sptr &bundleOption, bool &enabled); + ErrCode SetNotificationsEnabledForBundle(const sptr &bundleOption, const bool enabled); ErrCode GetNotificationsEnabled(bool &enabled); ErrCode SetNotificationsEnabled(const bool &enabled); ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode); @@ -64,28 +68,27 @@ public: void OnDistributedKvStoreDeathRecipient(); private: - // enum class BundlePropertyType; - - ErrCode CheckSlotForCreateSlot(const std::string &bundleName, const sptr &slot, + ErrCode CheckSlotForCreateSlot(const sptr &bundleOption, const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const; - ErrCode CheckGroupForCreateSlotGroup(const std::string &bundleName, const sptr &group, + ErrCode CheckGroupForCreateSlotGroup(const sptr &bundleOption, const sptr &group, NotificationPreferencesInfo &preferencesInfo) const; - ErrCode CheckSlotForRemoveSlot(const std::string &bundleName, const NotificationConstant::SlotType &slotType, + ErrCode CheckSlotForRemoveSlot(const sptr &bundleOption, const NotificationConstant::SlotType &slotType, NotificationPreferencesInfo &preferencesInfo) const; ErrCode CheckGroupForRemoveSlotGroup( - const std::string &bundleName, const std::string &groupId, NotificationPreferencesInfo &preferencesInfo) const; - ErrCode CheckSlotForUpdateSlot(const std::string &bundleName, const sptr &slot, + const sptr &bundleOption, const std::string &groupId, NotificationPreferencesInfo &preferencesInfo) const; + ErrCode CheckSlotForUpdateSlot(const sptr &bundleOption, const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const; - ErrCode CheckGroupForUpdateSlotGroup(const std::string &bundleName, const sptr &group, + ErrCode CheckGroupForUpdateSlotGroup(const sptr &bundleOption, const sptr &group, NotificationPreferencesInfo &preferencesInfo) const; template - ErrCode SetBundleProperty(NotificationPreferencesInfo &preferencesInfo, const std::string &bundleName, + ErrCode SetBundleProperty(NotificationPreferencesInfo &preferencesInfo, const sptr &bundleOption, const BundleType &type, const T &value); template - ErrCode SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleName, + ErrCode SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, const sptr &bundleOption, const BundleType &type, const T &value); template - ErrCode GetBundleProperty(const std::string &bundleName, const BundleType &type, T &value) const; + ErrCode GetBundleProperty(const sptr &bundleOption, const BundleType &type, T &value) const; + std::string GenerateBundleKey(const sptr &bundleOption) const; private: NotificationPreferencesInfo preferencesInfo_ {}; diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 411098a4a1163a802af3b04d6cbbba54ac52f1cf..2425af4079aaf4339124f913230c34275ebc77ca 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -25,83 +25,85 @@ 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 PutShowBadge(const std::string &bundleName, const bool &enable); - bool PutImportance(const std::string &bundleName, const int &importance); - bool PutTotalBadgeNums(const std::string &bundleName, const int &totalBadgeNum); - bool PutPrivateNotificationsAllowed(const std::string &bundleName, const bool &allow); - bool PutNotificationsEnabledForBundle(const std::string &bundleName, const bool &enabled); + bool PutSlotsToDisturbeDB(const std::string &bundleKey, const std::vector> &slots); + bool PutGroupsToDisturbeDB(const std::string &bundleKey, const std::vector> &groups); + bool PutBundlePropertyToDisturbeDB(const NotificationPreferencesInfo::BundleInfo &bundleInfo); + + bool PutShowBadge(const std::string &bundleKey, const bool &enable); + bool PutImportance(const std::string &bundleKey, const int &importance); + bool PutTotalBadgeNums(const std::string &bundleKey, const int &totalBadgeNum); + bool PutPrivateNotificationsAllowed(const std::string &bundleKey, const bool &allow); + bool PutNotificationsEnabledForBundle(const std::string &bundleKey, const bool &enabled); bool PutNotificationsEnabled(const bool &enabled); bool PutDisturbMode(const NotificationConstant::DisturbMode &mode); bool ParseFromDisturbeDB(NotificationPreferencesInfo &info); - bool RemoveAllBundleFromDisturbeDB(); - bool RemoveBundleFromDisturbeDB(const std::string &bundleName); - bool RemoveSlotFromDisturbeDB(const std::string &bundleName, const NotificationConstant::SlotType &type); - bool RemoveGroupsFromDisturbeDB(const std::string &bundleName, const std::vector &groupId); + bool RemoveAllDataFromDisturbeDB(); + bool RemoveBundleFromDisturbeDB(const std::string &bundleKey); + bool RemoveSlotFromDisturbeDB(const std::string &bundleKey, const NotificationConstant::SlotType &type); + bool RemoveAllSlotsFromDisturbeDB(const std::string &bundleKey); + bool RemoveGroupsFromDisturbeDB(const std::string &bundleKey, 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 CheckBundle(const std::string &bundleKey); + 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); + const std::string &bundleKey, const BundleType &type, const T &t); + bool PutBundleToDisturbeDB( + const std::string &bundleKey, const NotificationPreferencesInfo::BundleInfo &bundleInfo); void GetValueFromDisturbeDB(const std::string &key, std::function funcion); void GetValueFromDisturbeDB(const std::string &key, std::function funcion); bool GetRemoveGroupKeysFromDisturbeDB( - const std::string &bundleName, const std::string &groupId, std::vector &keys); + const std::string &bundleKey, const std::string &groupId, std::vector &keys); - bool SlotToEntry(const std::string &bundleName, const sptr &slot, + bool SlotToEntry(const std::string &bundleKey, const sptr &slot, std::vector &entries); - bool GroupToEntry(const std::string &bundleName, const sptr &group, - std::vector &entries); - void GenerateGroupEntry(const std::string &bundleName, const sptr &group, - std::vector &entries); - void GenerateSlotEntry(const std::string &bundleName, const sptr &slot, + bool GroupToEntry(const std::string &bundleKey, const sptr &group, std::vector &entries); + void GenerateGroupEntry(const std::string &bundleKey, const sptr &group, + std::vector &entries) const; + void GenerateSlotEntry(const std::string &bundleKey, const sptr &slot, + 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; - std::string GenerateBundleKey(const std::string &bundleName, const std::string &type = "") const; + std::string GenerateBundleKey(const std::string &bundleKey, const std::string &type = "") const; void ParseBundleFromDistureDB( NotificationPreferencesInfo &info, const std::vector &entries); - void ParseSlotFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleName, + void ParseSlotFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleKey, const OHOS::DistributedKv::Entry &entry); - void ParseGroupFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleName, + void ParseGroupFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleKey, const OHOS::DistributedKv::Entry &entry); void ParseBundlePropertyFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, - const OHOS::DistributedKv::Key &key, const OHOS::DistributedKv::Value &value); + const std::string &bundleKey, 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 &bundleKey, 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 611a9d713ecb62ba0f93fda8343431205d800027..55ef82b58f85b6ccc4d259b2636b134167c46116 100644 --- a/services/ans/include/notification_preferences_info.h +++ b/services/ans/include/notification_preferences_info.h @@ -20,15 +20,16 @@ #include #include +#include "notification_bundle_option.h" #include "notification_slot.h" #include "notification_slot_group.h" #include "preferences_constant.h" namespace OHOS { namespace Notification { -class NotificationPreferencesInfo { +class NotificationPreferencesInfo final { public: - class BundleInfo { + class BundleInfo final { public: BundleInfo(); ~BundleInfo(); @@ -47,25 +48,31 @@ public: void SetSlot(const sptr &slot); bool GetSlot(const NotificationConstant::SlotType &type, sptr &slot) const; bool GetAllSlots(std::vector> &slots); - bool GetAllSlotsInGroup(const std::string groupId, std::vector> &slots); + uint32_t GetAllSlotsSize(); + bool GetAllSlotsInGroup(const std::string &groupId, std::vector> &slots); + bool GetAllSlotsInGroup(const std::string &groupId, std::vector &slots); void SetGroup(const sptr &group); - bool GetGroup(const std::string &groupId, sptr &group) const; + bool GetGroup(const std::string &groupId, sptr &group); bool GetAllGroups(std::vector> &group); uint32_t GetGroupSize() const; 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); + void SetBundleUid(const int &uid); + int GetBundleUid() const; private: - std::string bundleName_{}; + std::string bundleName_ {}; + int uid_ {}; 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() @@ -77,9 +84,9 @@ public: void SetDisturbMode(const NotificationConstant::DisturbMode &mode); NotificationConstant::DisturbMode GetDisturbMode() const; void SetBundleInfo(const BundleInfo &info); - bool GetBundleInfo(const std::string &bundleName, BundleInfo &info) const; - bool RemoveBundleInfo(const std::string &bundleName); - bool IsExsitBundleInfo(const std::string &bundleName) const; + bool GetBundleInfo(const sptr &bundleOption, BundleInfo &info) const; + bool RemoveBundleInfo(const sptr &bundleOption); + bool IsExsitBundleInfo(const sptr &bundleOption) const; void ClearBundleInfo(); private: diff --git a/services/ans/include/notification_record.h b/services/ans/include/notification_record.h index 5fd3f4ee7896d7827524cd69910e5d340d1b92fb..f41e65faf8544b23d92ee845e964744b9712207d 100644 --- a/services/ans/include/notification_record.h +++ b/services/ans/include/notification_record.h @@ -19,6 +19,7 @@ #include "refbase.h" #include "notification.h" +#include "notification_bundle_option.h" #include "notification_request.h" #include "notification_slot.h" @@ -26,6 +27,7 @@ namespace OHOS { namespace Notification { struct NotificationRecord { + sptr bundleOption; sptr request; sptr notification; sptr slot; diff --git a/services/ans/include/preferences_constant.h b/services/ans/include/preferences_constant.h index 1923774bab5a3f2199c5f449b40642b8c89d1dbe..30702e8febbf4f880693c3c088b5c6c8cfd3323f 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/include/system_event_subscriber.h b/services/ans/include/system_event_subscriber.h index 6b9a7a2ecfccea2fe8b5ed0ce6850378da072eca..41b58c48db1f91ffe03ad44bdd576be7f300204c 100644 --- a/services/ans/include/system_event_subscriber.h +++ b/services/ans/include/system_event_subscriber.h @@ -30,6 +30,9 @@ public: : EventFwk::CommonEventSubscriber(subscribeInfo), callback_(callback) {} + ~SystemEventSubscriber() + {} + void OnReceiveEvent(const EventFwk::CommonEventData &data) override { if (callback_ != nullptr) { diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 12c76f04978ab2f9e442916e88287c75e211cb71..810e075344a16148ab1e3b9b672d4de7e67b82b0 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -41,6 +41,9 @@ static const std::string ACTIVE_NOTIFICATION_OPTION = "active"; static const std::string RECENT_NOTIFICATION_OPTION = "recent"; static const std::string SET_RECENT_COUNT_OPTION = "setRecentCount"; +static const int32_t NOTIFICATION_MIN_COUNT = 0; +static const int32_t NOTIFICATION_MAX_COUNT = 1024; + static const int32_t DEFAULT_RECENT_COUNT = 16; struct RecentNotification { @@ -69,7 +72,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,11 +86,10 @@ inline bool IsSystemApp() { bool isSystemApp = false; - uid_t callingUid = IPCSkeleton::GetCallingUid(); + int callingUid = IPCSkeleton::GetCallingUid(); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { - printf("callingUid : %d\n", callingUid); isSystemApp = bundleManager->IsSystemApp(callingUid); } @@ -98,18 +100,20 @@ inline ErrCode AssignValidNotificationSlot(const std::shared_ptr slot; ErrCode result = NotificationPreferences::GetInstance().GetNotificationSlot( - record->notification->GetBundleName(), record->request->GetSlotType(), slot); + record->bundleOption, record->request->GetSlotType(), slot); if ((result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) || (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST)) { result = NotificationPreferences::GetInstance().GetNotificationSlot( - record->notification->GetBundleName(), NotificationConstant::SlotType::OTHER, slot); + record->bundleOption, NotificationConstant::SlotType::OTHER, slot); if ((result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) || (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST)) { slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); std::vector> slots; slots.push_back(slot); - result = NotificationPreferences::GetInstance().AddNotificationSlots( - record->notification->GetBundleName(), slots); + result = NotificationPreferences::GetInstance().AddNotificationSlots(record->bundleOption, slots); + } + if (result == ERR_OK) { + record->request->SetSlotType(NotificationConstant::SlotType::OTHER); } } if (result == ERR_OK) { @@ -128,8 +132,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); @@ -167,6 +171,36 @@ AdvancedNotificationService::~AdvancedNotificationService() StopFilters(); } +sptr AdvancedNotificationService::GenerateBundleOption() +{ + sptr bundleOption = nullptr; + std::string bundle = GetClientBundleName(); + if (bundle.empty()) { + return nullptr; + } + int uid = IPCSkeleton::GetCallingUid(); + bundleOption = new NotificationBundleOption(bundle, uid); + return bundleOption; +} + +sptr AdvancedNotificationService::GenerateValidBundleOption( + const sptr &bundleOption) +{ + sptr validBundleOption = nullptr; + if (bundleOption->GetUid() <= 0) { + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager != nullptr) { + int uid = bundleManager->GetDefaultUidByBundleName(bundleOption->GetBundleName()); + if (uid > 0) { + validBundleOption = new NotificationBundleOption(bundleOption->GetBundleName(), uid); + } + } + } else { + validBundleOption = bundleOption; + } + return validBundleOption; +} + ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr &request) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -176,10 +210,19 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt } ErrCode result = PrepereNotificationRequest(request); + if (result != ERR_OK) { + return result; + } + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } std::shared_ptr record = std::make_shared(); record->request = request; record->notification = new Notification(request); + record->bundleOption = bundleOption; handler_->PostSyncTask(std::bind([&]() { result = AssignValidNotificationSlot(record); @@ -281,13 +324,9 @@ sptr AdvancedNotificationService::GenerateSortingMap() std::vector sortingList; for (auto record : notificationList_) { NotificationSorting sorting; + sorting.SetRanking((int32_t)sortingList.size()); sorting.SetKey(record->notification->GetKey()); - sptr slot; - if (NotificationPreferences::GetInstance().GetNotificationSlot( - record->notification->GetBundleName(), record->request->GetSlotType(), slot) == ERR_OK) { - sorting.SetRanking((int32_t)sortingList.size()); - sorting.SetSlot(slot); - } + sorting.SetSlot(record->slot); sortingList.push_back(sorting); } @@ -314,15 +353,15 @@ ErrCode AdvancedNotificationService::Cancel(int notificationId, const std::strin { ANS_LOGD("%{public}s", __FUNCTION__); - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { sptr notification = nullptr; - result = RemoveFromNotificationList(bundle, label, notificationId, notification, true); + result = RemoveFromNotificationList(bundleOption, label, notificationId, notification, true); if (result != ERR_OK) { return; } @@ -341,16 +380,17 @@ ErrCode AdvancedNotificationService::CancelAll() { ANS_LOGD("%{public}s", __FUNCTION__); - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { sptr notification = nullptr; - std::vector keys = GetNotificationKeys(bundle); + std::vector keys = GetNotificationKeys(bundleOption); for (auto key : keys) { result = RemoveFromNotificationList(key, notification, true); if (result != ERR_OK) { @@ -370,116 +410,118 @@ 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__); - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { - return ERR_ANS_INVALID_BUNDLE; + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; } - bool isSystemApp = IsSystemApp(); - - if (IsCustomSlotContained(slots) && !isSystemApp) { - return ERR_ANS_NON_SYSTEM_APP; + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; } - 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; + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + std::vector> addSlots; + for (auto slot : slots) { + sptr originalSlot; + result = + NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, 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(bundleOption, addSlots); + } + })); return result; } ErrCode AdvancedNotificationService::AddSlotGroups(std::vector> groups) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundle, groups); })); + [&]() { result = NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleOption, groups); })); return result; } ErrCode AdvancedNotificationService::GetSlots(std::vector> &slots) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } - handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots); })); + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleOption, slots); })); return result; } ErrCode AdvancedNotificationService::GetSlotGroup(const std::string &groupId, sptr &group) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } - handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().GetNotificationSlotGroup(bundle, groupId, group); })); + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().GetNotificationSlotGroup(bundleOption, groupId, group); + })); return result; } ErrCode AdvancedNotificationService::GetSlotGroups(std::vector> &groups) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundle, groups); })); + [&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundleOption, groups); })); return result; } ErrCode AdvancedNotificationService::RemoveSlotGroups(const std::vector &groupIds) { + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundle, groupIds); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleOption, groupIds); + })); return result; } @@ -487,14 +529,17 @@ ErrCode AdvancedNotificationService::GetActiveNotifications(std::vector bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { + notifications.clear(); for (auto record : notificationList_) { - if (record->notification->GetBundleName() == bundle) { + if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && + (record->bundleOption->GetUid() == bundleOption->GetUid())) { notifications.push_back(record->request); } } @@ -506,15 +551,17 @@ ErrCode AdvancedNotificationService::GetActiveNotificationNums(int &num) { ANS_LOGD("%{public}s", __FUNCTION__); - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { int count = 0; for (auto record : notificationList_) { - if (record->notification->GetBundleName() == bundle) { + if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && + (record->bundleOption->GetUid() == bundleOption->GetUid())) { count += 1; } } @@ -525,67 +572,83 @@ ErrCode AdvancedNotificationService::GetActiveNotificationNums(int &num) ErrCode AdvancedNotificationService::SetNotificationAgent(const std::string &agent) { - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AdvancedNotificationService::GetNotificationAgent(std::string &agent) { - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AdvancedNotificationService::CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) { - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AdvancedNotificationService::PublishAsBundle( const sptr notification, const std::string &representativeBundle) { - return ERR_OK; + return ERR_INVALID_OPERATION; } ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int num) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + + ErrCode result = ERR_OK; handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().SetTotalBadgeNums(bundle, num); })); + std::bind([&]() { result = NotificationPreferences::GetInstance().SetTotalBadgeNums(bundleOption, num); })); return result; } ErrCode AdvancedNotificationService::GetBundleImportance(int &importance) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + + ErrCode result = ERR_OK; handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().GetImportance(bundle, importance); })); + std::bind([&]() { result = NotificationPreferences::GetInstance().GetImportance(bundleOption, importance); })); return result; } ErrCode AdvancedNotificationService::SetDisturbMode(NotificationConstant::DisturbMode mode) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { - return ERR_ANS_INVALID_BUNDLE; + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; } - handler_->PostSyncTask(std::bind([&]() { result = NotificationPreferences::GetInstance().SetDisturbMode(mode); })); + + ErrCode result = ERR_OK; + 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) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { - return ERR_ANS_INVALID_BUNDLE; + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; } - handler_->PostSyncTask(std::bind( - [this, &bundle, &mode, &result]() { result = NotificationPreferences::GetInstance().GetDisturbMode(mode); })); + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { result = NotificationPreferences::GetInstance().GetDisturbMode(mode); })); return result; } + ErrCode AdvancedNotificationService::HasNotificationPolicyAccessPermission(bool &granted) { return ERR_OK; @@ -593,25 +656,33 @@ ErrCode AdvancedNotificationService::HasNotificationPolicyAccessPermission(bool ErrCode AdvancedNotificationService::SetPrivateNotificationsAllowed(bool allow) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } - handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundle, allow); })); + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundleOption, allow); + })); return result; } ErrCode AdvancedNotificationService::GetPrivateNotificationsAllowed(bool &allow) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } - handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundle, allow); })); + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleOption, allow); + })); return result; } @@ -643,7 +714,7 @@ ErrCode AdvancedNotificationService::Delete(const std::string &key) return result; } -ErrCode AdvancedNotificationService::DeleteByBundle(const std::string &bundle) +ErrCode AdvancedNotificationService::DeleteByBundle(const sptr &bundleOption) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -651,13 +722,17 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const std::string &bundle) return ERR_ANS_NON_SYSTEM_APP; } - ErrCode result = ERR_OK; + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_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 +762,10 @@ ErrCode AdvancedNotificationService::DeleteAll() ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { - sptr notification = nullptr; - - std::vector keys = GetNotificationKeys(std::string()); + std::vector keys = GetNotificationKeys(nullptr); for (auto key : keys) { + sptr notification = nullptr; + result = RemoveFromNotificationList(key, notification); if (result != ERR_OK) { continue; @@ -710,12 +785,14 @@ ErrCode AdvancedNotificationService::DeleteAll() return result; } -std::vector AdvancedNotificationService::GetNotificationKeys(const std::string &bundle) +std::vector AdvancedNotificationService::GetNotificationKeys( + const sptr &bundleOption) { std::vector keys; for (auto record : notificationList_) { - if (!bundle.empty() && (record->notification->GetBundleName() != bundle)) { + if ((bundleOption != nullptr) && (record->bundleOption->GetBundleName() != bundleOption->GetBundleName() && + (record->bundleOption->GetUid() != bundleOption->GetUid()))) { continue; } keys.push_back(record->notification->GetKey()); @@ -725,7 +802,7 @@ std::vector AdvancedNotificationService::GetNotificationKeys(const } ErrCode AdvancedNotificationService::GetSlotsByBundle( - const std::string &bundle, std::vector> &slots) + const sptr &bundleOption, std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -733,6 +810,11 @@ ErrCode AdvancedNotificationService::GetSlotsByBundle( return ERR_ANS_NON_SYSTEM_APP; } + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ErrCode result = ERR_OK; handler_->PostSyncTask( std::bind([&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots); })); @@ -740,7 +822,7 @@ ErrCode AdvancedNotificationService::GetSlotsByBundle( } ErrCode AdvancedNotificationService::UpdateSlots( - const std::string &bundle, const std::vector> &slots) + const sptr &bundleOption, const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -748,6 +830,11 @@ ErrCode AdvancedNotificationService::UpdateSlots( return ERR_ANS_NON_SYSTEM_APP; } + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ErrCode result = ERR_OK; handler_->PostSyncTask( std::bind([&]() { result = NotificationPreferences::GetInstance().UpdateNotificationSlots(bundle, slots); })); @@ -755,7 +842,7 @@ ErrCode AdvancedNotificationService::UpdateSlots( } ErrCode AdvancedNotificationService::UpdateSlotGroups( - const std::string &bundle, const std::vector> &groups) + const sptr &bundleOption, const std::vector> &groups) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -763,13 +850,24 @@ ErrCode AdvancedNotificationService::UpdateSlotGroups( return ERR_ANS_NON_SYSTEM_APP; } + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind( [&]() { result = NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundle, groups); })); return result; } -ErrCode AdvancedNotificationService::SetNotificationsEnabledForBundle(const std::string &bundle, bool enabled) +ErrCode AdvancedNotificationService::SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) +{ + return ERR_INVALID_OPERATION; +} + +ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( + const sptr &bundleOption, bool enabled) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -777,13 +875,19 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForBundle(const std: return ERR_ANS_NON_SYSTEM_APP; } + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundle, enabled); })); + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().SetShowBadge(bundle, enabled); })); return result; } -ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) +ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle( + const sptr &bundleOption, bool &enabled) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -791,32 +895,39 @@ ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle(const std::str return ERR_ANS_NON_SYSTEM_APP; } + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ErrCode result = ERR_OK; handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().SetShowBadge(bundle, enabled); })); + std::bind([&]() { result = NotificationPreferences::GetInstance().IsShowBadge(bundle, enabled); })); return result; } -ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) +ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled) { ANS_LOGD("%{public}s", __FUNCTION__); - if (!IsSystemApp()) { - return ERR_ANS_NON_SYSTEM_APP; + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; } ErrCode result = ERR_OK; handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().IsShowBadge(bundle, enabled); })); + std::bind([&]() { result = NotificationPreferences::GetInstance().IsShowBadge(bundleOption, enabled); })); return result; } -ErrCode AdvancedNotificationService::RemoveFromNotificationList(const std::string &bundle, const std::string &label, - int notificationId, sptr ¬ification, bool isCancel) +ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptr &bundleOption, + const std::string &label, int notificationId, sptr ¬ification, bool isCancel) { for (auto record : notificationList_) { - if ((record->notification->GetBundleName() == bundle) && (record->notification->GetLabel() == label) && - (record->notification->GetId() == notificationId)) { + if (((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && + (record->bundleOption->GetUid() == bundleOption->GetUid())) && + (record->notification->GetLabel() == label) && (record->notification->GetId() == notificationId)) { if (!isCancel && record->request->IsUnremovable()) { return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; } @@ -883,25 +994,31 @@ ErrCode AdvancedNotificationService::Unsubscribe( ErrCode AdvancedNotificationService::GetSlotByType( const NotificationConstant::SlotType slotType, sptr &slot) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot); })); + [&]() { result = NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, slotType, slot); })); return result; } ErrCode AdvancedNotificationService::RemoveSlotByType(const NotificationConstant::SlotType slotType) { - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } - handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().RemoveNotificationSlot(bundle, slotType); })); + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleOption, slotType); })); return result; } @@ -915,6 +1032,7 @@ ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vectorPostSyncTask(std::bind([&]() { + notifications.clear(); for (auto record : notificationList_) { notifications.push_back(record->notification); } @@ -979,7 +1097,7 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const } ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( - const std::string &deviceId, const std::string &bundleName, bool enabled) + const std::string &deviceId, const sptr &bundleOption, bool enabled) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -987,11 +1105,16 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( return ERR_ANS_NON_SYSTEM_APP; } + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { if (deviceId.empty()) { // Local device - result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleName, enabled); + result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundle, enabled); } else { // Remote revice } @@ -1003,27 +1126,45 @@ ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed) { ANS_LOGD("%{public}s", __FUNCTION__); - ErrCode result = ERR_OK; - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { allowed = false; result = NotificationPreferences::GetInstance().GetNotificationsEnabled(allowed); if (result == ERR_OK && allowed) { - result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundle, allowed); + result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleOption, allowed); } })); return result; } -ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) +ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( + const sptr &bundleOption, bool &allowed) { ANS_LOGD("%{public}s", __FUNCTION__); - if (!IsSystemApp()) { - return ERR_ANS_NON_SYSTEM_APP; + sptr clientBundle = GenerateBundleOption(); + if (clientBundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + sptr targetBundle = nullptr; + if (bundleOption == nullptr) { + targetBundle = clientBundle; + } else { + if ((clientBundle->GetBundleName() == bundleOption->GetBundleName()) && + (clientBundle->GetUid() == bundleOption->GetUid())) { + targetBundle = bundleOption; + } else { + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + targetBundle = GenerateValidBundleOption(bundleOption); + } } ErrCode result = ERR_OK; @@ -1031,7 +1172,7 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(const std::str allowed = false; result = NotificationPreferences::GetInstance().GetNotificationsEnabled(allowed); if (result == ERR_OK && allowed) { - result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundle, allowed); + result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(targetBundle, allowed); } })); return result; @@ -1111,11 +1252,14 @@ ErrCode AdvancedNotificationService::SetRecentNotificationCount(const std::strin ANS_LOGD("%{public}s arg = %{public}s", __FUNCTION__, arg.c_str()); int count = atoi(arg.c_str()); - if (count < 0 || count > 1024) { + if (count < NOTIFICATION_MIN_COUNT || count > NOTIFICATION_MAX_COUNT) { return ERR_ANS_INVALID_PARAM; } recentInfo_->recentCount = count; + while (recentInfo_->list.size() > recentInfo_->recentCount) { + recentInfo_->list.pop_back(); + } return ERR_OK; } @@ -1158,7 +1302,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; @@ -1228,12 +1372,12 @@ ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr &bundleOption) { ANS_LOGD("%{public}s", __FUNCTION__); handler_->PostTask(std::bind([&]() { - ErrCode result = NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundle); + ErrCode result = NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleOption); if (result != ERR_OK) { ANS_LOGE("NotificationPreferences::RemoveNotificationForBundle failed: %{public}d", result); } @@ -1247,5 +1391,148 @@ void AdvancedNotificationService::OnDistributedKvStoreDeathRecipient() std::bind([&]() { NotificationPreferences::GetInstance().OnDistributedKvStoreDeathRecipient(); })); } +ErrCode AdvancedNotificationService::RemoveAllSlots() +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().RemoveNotificationAllSlots(bundleOption); })); + return result; +} + +ErrCode AdvancedNotificationService::AddSlotByType(NotificationConstant::SlotType slotType) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + sptr slot; + result = NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, 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(bundleOption, slots); + } + })); + return result; +} + +ErrCode AdvancedNotificationService::RemoveNotification( + const sptr &bundleOption, int notificationId, const std::string &label) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS; + + handler_->PostSyncTask(std::bind([&]() { + sptr notification = nullptr; + + for (auto record : notificationList_) { + if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) && + (record->bundleOption->GetUid() == bundleOption->GetUid()) && + (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 sptr &bundleOption) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + handler_->PostSyncTask(std::bind([&]() { + std::vector> removeList; + for (auto record : notificationList_) { + if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && + (record->bundleOption->GetUid() == bundleOption->GetUid()) && !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; +} + +ErrCode AdvancedNotificationService::GetSlotNumAsBundle(const sptr &bundleOption, int &num) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + ErrCode result = ERR_OK; + + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().GetNotificationSlotsNumForBundle(bundle, num); })); + + return result; +} + } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/bundle_manager_helper.cpp b/services/ans/src/bundle_manager_helper.cpp index fca92739b701cc1a953b56aae1294ce41a590eeb..a02c7f20a7cf1b6ad36e34733a4db79c67b03f0d 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; @@ -101,5 +101,23 @@ void BundleManagerHelper::Disconnect() } } +int BundleManagerHelper::GetDefaultUidByBundleName(const std::string& bundle) +{ + int uid = -1; + + std::lock_guard lock(connectionMutex_); + + Connect(); + + if (bundleMgr_ != nullptr) { + AppExecFwk::BundleInfo bundleInfo; + if (bundleMgr_->GetBundleInfo(bundle, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo)) { + uid = bundleInfo.uid; + } + } + + return uid; +} + } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/disturb_filter.cpp b/services/ans/src/disturb_filter.cpp index c6547f08113d8e1016415c55d33f22b4a1adb383..d5ebca7ba27ab60c321eff48361fc5e415368a24 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 04d67ccf9aed1407161b90e2ce04ce155555f8c2..94175a7114b601accd7fbb9d508643914e842341 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -37,23 +37,23 @@ NotificationPreferences &NotificationPreferences::GetInstance() } ErrCode NotificationPreferences::AddNotificationSlots( - const std::string &bundleName, const std::vector> &slots) + const sptr &bundleOption, const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleName.empty() || slots.empty()) { + if (bundleOption->GetBundleName().empty() || slots.empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; for (auto slot : slots) { - result = CheckSlotForCreateSlot(bundleName, slot, preferencesInfo); + result = CheckSlotForCreateSlot(bundleOption, slot, preferencesInfo); if (result != ERR_OK) { return result; } } - if (result == ERR_OK && (!preferncesDB_->PutSlotsToDisturbeDB(bundleName, slots))) { + if (result == ERR_OK && (!preferncesDB_->PutSlotsToDisturbeDB(GenerateBundleKey(bundleOption), slots))) { return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -64,25 +64,24 @@ ErrCode NotificationPreferences::AddNotificationSlots( } ErrCode NotificationPreferences::AddNotificationSlotGroups( - const std::string &bundleName, const std::vector> &groups) + const sptr &bundleOption, const std::vector> &groups) { ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleName.empty() || groups.empty()) { + if (bundleOption->GetBundleName().empty() || groups.empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; for (auto group : groups) { - result = CheckGroupForCreateSlotGroup(bundleName, group, preferencesInfo); + result = CheckGroupForCreateSlotGroup(bundleOption, group, preferencesInfo); if (result != ERR_OK) { return result; } } - if (result == ERR_OK && (!preferncesDB_->PutGroupsToDisturbeDB(bundleName, groups))) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - return result; + if (result == ERR_OK && (!preferncesDB_->PutGroupsToDisturbeDB(GenerateBundleKey(bundleOption), groups))) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } if (result == ERR_OK) { @@ -91,20 +90,62 @@ ErrCode NotificationPreferences::AddNotificationSlotGroups( return result; } +ErrCode NotificationPreferences::AddNotificationBundleProperty(const sptr &bundleOption) +{ + if (bundleOption->GetBundleName().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) + const sptr &bundleOption, const NotificationConstant::SlotType &slotType) { ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; - result = CheckSlotForRemoveSlot(bundleName, slotType, preferencesInfo); + result = CheckSlotForRemoveSlot(bundleOption, slotType, preferencesInfo); - if (result == ERR_OK && (!preferncesDB_->RemoveSlotFromDisturbeDB(bundleName, slotType))) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - return result; + if (result == ERR_OK && (!preferncesDB_->RemoveSlotFromDisturbeDB(GenerateBundleKey(bundleOption), slotType))) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } + return result; +} + +ErrCode NotificationPreferences::RemoveNotificationAllSlots(const sptr &bundleOption) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + if (bundleOption->GetBundleName().empty()) { + return ERR_ANS_INVALID_PARAM; + } + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + ErrCode result = ERR_OK; + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) { + bundleInfo.RemoveAllSlots(); + if (!preferncesDB_->RemoveAllSlotsFromDisturbeDB(GenerateBundleKey(bundleOption))) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + } else { + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } if (result == ERR_OK) { @@ -114,23 +155,22 @@ ErrCode NotificationPreferences::RemoveNotificationSlot( } ErrCode NotificationPreferences::RemoveNotificationSlotGroups( - const std::string &bundleName, const std::vector &groupIds) + const sptr &bundleOption, const std::vector &groupIds) { ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleName.empty() || groupIds.empty()) { + if (bundleOption->GetBundleName().empty() || groupIds.empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; for (auto groupId : groupIds) { - result = CheckGroupForRemoveSlotGroup(bundleName, groupId, preferencesInfo); + result = CheckGroupForRemoveSlotGroup(bundleOption, groupId, preferencesInfo); if (result != ERR_OK) { return result; } } - if (result == ERR_OK && (!preferncesDB_->RemoveGroupsFromDisturbeDB(bundleName, groupIds))) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - return result; + if (result == ERR_OK && (!preferncesDB_->RemoveGroupsFromDisturbeDB(GenerateBundleKey(bundleOption), groupIds))) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } if (result == ERR_OK) { @@ -139,19 +179,19 @@ ErrCode NotificationPreferences::RemoveNotificationSlotGroups( return result; } -ErrCode NotificationPreferences::RemoveNotificationForBundle(const std::string &bundleName) +ErrCode NotificationPreferences::RemoveNotificationForBundle(const sptr &bundleOption) { ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; - if (preferencesInfo.IsExsitBundleInfo(bundleName)) { - preferencesInfo.RemoveBundleInfo(bundleName); - if (!preferncesDB_->RemoveBundleFromDisturbeDB(bundleName)) { + if (preferencesInfo.IsExsitBundleInfo(bundleOption)) { + preferencesInfo.RemoveBundleInfo(bundleOption); + if (!preferncesDB_->RemoveBundleFromDisturbeDB(GenerateBundleKey(bundleOption))) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } } else { @@ -166,25 +206,24 @@ ErrCode NotificationPreferences::RemoveNotificationForBundle(const std::string & } ErrCode NotificationPreferences::UpdateNotificationSlots( - const std::string &bundleName, const std::vector> &slots) + const sptr &bundleOption, const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleName.empty() || slots.empty()) { + if (bundleOption->GetBundleName().empty() || slots.empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; for (auto slotIter : slots) { - result = CheckSlotForUpdateSlot(bundleName, slotIter, preferencesInfo); + result = CheckSlotForUpdateSlot(bundleOption, slotIter, preferencesInfo); if (result != ERR_OK) { return result; } } - if (result == ERR_OK && (!preferncesDB_->PutSlotsToDisturbeDB(bundleName, slots))) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - return result; + if (result == ERR_OK && (!preferncesDB_->PutSlotsToDisturbeDB(GenerateBundleKey(bundleOption), slots))) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } if (result == ERR_OK) { @@ -195,25 +234,25 @@ ErrCode NotificationPreferences::UpdateNotificationSlots( } ErrCode NotificationPreferences::UpdateNotificationSlotGroups( - const std::string &bundleName, const std::vector> &groups) + const sptr &bundleOption, const std::vector> &groups) { + ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleName.empty() || groups.empty()) { + if (bundleOption->GetBundleName().empty() || groups.empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; for (auto groupIter : groups) { - result = CheckGroupForUpdateSlotGroup(bundleName, groupIter, preferencesInfo); + result = CheckGroupForUpdateSlotGroup(bundleOption, groupIter, preferencesInfo); if (result != ERR_OK) { return result; } } - if (result == ERR_OK && (!preferncesDB_->PutGroupsToDisturbeDB(bundleName, groups))) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; - return result; + if (result == ERR_OK && (!preferncesDB_->PutGroupsToDisturbeDB(GenerateBundleKey(bundleOption), groups))) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } if (result == ERR_OK) { @@ -222,17 +261,17 @@ ErrCode NotificationPreferences::UpdateNotificationSlotGroups( return result; } -ErrCode NotificationPreferences::GetNotificationSlot( - const std::string &bundleName, const NotificationConstant::SlotType &type, sptr &slot) +ErrCode NotificationPreferences::GetNotificationSlot(const sptr &bundleOption, + const NotificationConstant::SlotType &type, sptr &slot) { ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { if (!bundleInfo.GetSlot(type, slot)) { result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; } @@ -244,15 +283,15 @@ ErrCode NotificationPreferences::GetNotificationSlot( } ErrCode NotificationPreferences::GetNotificationAllSlots( - const std::string &bundleName, std::vector> &slots) + const sptr &bundleOption, std::vector> &slots) { - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { bundleInfo.GetAllSlots(slots); } else { ANS_LOGE("Notification bundle does not exsit."); @@ -262,16 +301,33 @@ ErrCode NotificationPreferences::GetNotificationAllSlots( return result; } +ErrCode NotificationPreferences::GetNotificationSlotsNumForBundle( + const sptr &bundleOption, int &num) +{ + if (bundleOption->GetBundleName().empty()) { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + num = bundleInfo.GetAllSlotsSize(); + } else { + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + return result; +} + ErrCode NotificationPreferences::GetNotificationSlotGroup( - const std::string &bundleName, const std::string &groupId, sptr &group) + const sptr &bundleOption, const std::string &groupId, sptr &group) { - if (bundleName.empty() || groupId.empty()) { + if (bundleOption->GetBundleName().empty() || groupId.empty()) { return ERR_ANS_INVALID_PARAM; } ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { if (!bundleInfo.GetGroup(groupId, group)) { result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST; } @@ -283,15 +339,15 @@ ErrCode NotificationPreferences::GetNotificationSlotGroup( } ErrCode NotificationPreferences::GetNotificationAllSlotGroups( - const std::string &bundleName, std::vector> &groups) + const sptr &bundleOption, std::vector> &groups) { - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { bundleInfo.GetAllGroups(groups); } else { ANS_LOGE("Notification bundle does not exsit."); @@ -300,16 +356,16 @@ ErrCode NotificationPreferences::GetNotificationAllSlotGroups( return result; } -ErrCode NotificationPreferences::GetNotificationAllSlotInSlotGroup( - const std::string &bundleName, const std::string &groupId, std::vector> &slots) +ErrCode NotificationPreferences::GetNotificationAllSlotInSlotGroup(const sptr &bundleOption, + const std::string &groupId, std::vector> &slots) { - if (bundleName.empty() || groupId.empty()) { + if (bundleOption->GetBundleName().empty() || groupId.empty()) { return ERR_ANS_INVALID_PARAM; } ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { bundleInfo.GetAllSlotsInGroup(groupId, slots); } else { ANS_LOGE("Notification bundle does not exsit."); @@ -318,113 +374,119 @@ ErrCode NotificationPreferences::GetNotificationAllSlotInSlotGroup( return result; } -ErrCode NotificationPreferences::IsShowBadge(const std::string &bundleName, bool &enable) +ErrCode NotificationPreferences::IsShowBadge(const sptr &bundleOption, bool &enable) { - ErrCode result = ERR_ANS_INVALID_PARAM; - if (bundleName.empty()) { - return result; + if (bundleOption->GetBundleName().empty()) { + return ERR_ANS_INVALID_PARAM; } - result = GetBundleProperty(bundleName, BundleType::kBundleShowBadgeType, enable); - return result; + return GetBundleProperty(bundleOption, BundleType::BUNDLE_SHOW_BADGE_TYPE, enable); } -ErrCode NotificationPreferences::SetShowBadge(const std::string &bundleName, const bool enable) +ErrCode NotificationPreferences::SetShowBadge(const sptr &bundleOption, const bool enable) { - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleShowBadgeType, enable); + ErrCode result = + SetBundleProperty(preferencesInfo, bundleOption, BundleType::BUNDLE_SHOW_BADGE_TYPE, enable); if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } return result; } -ErrCode NotificationPreferences::GetImportance(const std::string &bundleName, int &importance) +ErrCode NotificationPreferences::GetImportance(const sptr &bundleOption, int &importance) { - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundleType::kBundleImportanceType, importance); - return result; + return GetBundleProperty(bundleOption, BundleType::BUNDLE_IMPORTANCE_TYPE, importance); } -ErrCode NotificationPreferences::SetImportance(const std::string &bundleName, const int &importance) +ErrCode NotificationPreferences::SetImportance( + const sptr &bundleOption, const int &importance) { - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleImportanceType, importance); + ErrCode result = SetBundleProperty( + preferencesInfo, bundleOption, BundleType::BUNDLE_IMPORTANCE_TYPE, importance); if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } return result; } -ErrCode NotificationPreferences::GetTotalBadgeNums(const std::string &bundleName, int &totalBadgeNum) +ErrCode NotificationPreferences::GetTotalBadgeNums( + const sptr &bundleOption, int &totalBadgeNum) { - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundleType::kBundleBadgeTotalNumType, totalBadgeNum); - return result; + return GetBundleProperty(bundleOption, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, totalBadgeNum); } -ErrCode NotificationPreferences::SetTotalBadgeNums(const std::string &bundleName, const int num) +ErrCode NotificationPreferences::SetTotalBadgeNums(const sptr &bundleOption, const int num) { - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleBadgeTotalNumType, num); + ErrCode result = + SetBundleProperty(preferencesInfo, bundleOption, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, num); if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } return result; } -ErrCode NotificationPreferences::GetPrivateNotificationsAllowed(const std::string &bundleName, bool &allow) +ErrCode NotificationPreferences::GetPrivateNotificationsAllowed( + const sptr &bundleOption, bool &allow) { - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundleType::kBundlePrivateAllowedType, allow); - return result; + return GetBundleProperty(bundleOption, BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE, allow); } -ErrCode NotificationPreferences::SetPrivateNotificationsAllowed(const std::string &bundleName, const bool allow) +ErrCode NotificationPreferences::SetPrivateNotificationsAllowed( + const sptr &bundleOption, const bool allow) { - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundlePrivateAllowedType, allow); + ErrCode result = SetBundleProperty( + preferencesInfo, bundleOption, BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE, allow); if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } return result; } -ErrCode NotificationPreferences::GetNotificationsEnabledForBundle(const std::string &bundleName, bool &enabled) +ErrCode NotificationPreferences::GetNotificationsEnabledForBundle( + const sptr &bundleOption, bool &enabled) { - if (bundleName.empty()) { + if (bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundleType::kBundleEnableNotificationType, enabled); - return result; + return GetBundleProperty(bundleOption, BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE, enabled); } -ErrCode NotificationPreferences::SetNotificationsEnabledForBundle(const std::string &bundleName, const bool enabled) +ErrCode NotificationPreferences::SetNotificationsEnabledForBundle( + const sptr &bundleOption, const bool enabled) { - if (bundleName.empty()) { - return ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + if (bundleOption->GetBundleName().empty()) { + return ERR_ANS_INVALID_PARAM; } + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleEnableNotificationType, enabled); + ErrCode result = SetBundleProperty( + preferencesInfo, bundleOption, BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE, enabled); if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; @@ -446,6 +508,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 +529,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,13 +541,17 @@ 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; } -ErrCode NotificationPreferences::CheckSlotForCreateSlot(const std::string &bundleName, +ErrCode NotificationPreferences::CheckSlotForCreateSlot(const sptr &bundleOption, const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const { if (slot == nullptr) { @@ -485,18 +559,18 @@ 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); + if (!preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) { + bundleInfo.SetBundleName(bundleOption->GetBundleName()); + bundleInfo.SetBundleUid(bundleOption->GetUid()); } bundleInfo.SetSlot(slot); preferencesInfo.SetBundleInfo(bundleInfo); - return result; + return ERR_OK; } -ErrCode NotificationPreferences::CheckGroupForCreateSlotGroup(const std::string &bundleName, +ErrCode NotificationPreferences::CheckGroupForCreateSlotGroup(const sptr &bundleOption, const sptr &group, NotificationPreferencesInfo &preferencesInfo) const { if (group == nullptr) { @@ -509,29 +583,28 @@ 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); + if (!preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) { + bundleInfo.SetBundleName(bundleOption->GetBundleName()); + bundleInfo.SetBundleUid(bundleOption->GetUid()); } 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, +ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const sptr &bundleOption, const NotificationConstant::SlotType &slotType, NotificationPreferencesInfo &preferencesInfo) const { ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + if (preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) { if (bundleInfo.IsExsitSlot(slotType)) { bundleInfo.RemoveSlot(slotType); preferencesInfo.SetBundleInfo(bundleInfo); @@ -546,12 +619,12 @@ ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const std::string &bundl return result; } -ErrCode NotificationPreferences::CheckGroupForRemoveSlotGroup( - const std::string &bundleName, const std::string &groupId, NotificationPreferencesInfo &preferencesInfo) const +ErrCode NotificationPreferences::CheckGroupForRemoveSlotGroup(const sptr &bundleOption, + const std::string &groupId, NotificationPreferencesInfo &preferencesInfo) const { ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + if (preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) { if (bundleInfo.IsExsitSlotGroup(groupId)) { bundleInfo.RemoveSlotGroup(groupId); preferencesInfo.SetBundleInfo(bundleInfo); @@ -566,7 +639,7 @@ ErrCode NotificationPreferences::CheckGroupForRemoveSlotGroup( return result; } -ErrCode NotificationPreferences::CheckSlotForUpdateSlot(const std::string &bundleName, +ErrCode NotificationPreferences::CheckSlotForUpdateSlot(const sptr &bundleOption, const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const { if (slot == nullptr) { @@ -576,30 +649,33 @@ ErrCode NotificationPreferences::CheckSlotForUpdateSlot(const std::string &bundl ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + if (preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) { if (bundleInfo.IsExsitSlot(slot->GetType())) { - bundleInfo.SetBundleName(bundleName); + bundleInfo.SetBundleName(bundleOption->GetBundleName()); + bundleInfo.SetBundleUid(bundleOption->GetUid()); 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; } -ErrCode NotificationPreferences::CheckGroupForUpdateSlotGroup(const std::string &bundleName, +ErrCode NotificationPreferences::CheckGroupForUpdateSlotGroup(const sptr &bundleOption, const sptr &group, NotificationPreferencesInfo &preferencesInfo) const { ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + if (preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) { if (bundleInfo.IsExsitSlotGroup(group->GetId())) { - bundleInfo.SetBundleName(bundleName); + bundleInfo.SetBundleName(bundleOption->GetBundleName()); + bundleInfo.SetBundleUid(bundleOption->GetUid()); bundleInfo.SetGroup(group); preferencesInfo.SetBundleInfo(bundleInfo); } else { @@ -607,22 +683,23 @@ 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; } template -ErrCode NotificationPreferences::SetBundleProperty( - NotificationPreferencesInfo &preferencesInfo, const std::string &bundleName, const BundleType &type, const T &value) +ErrCode NotificationPreferences::SetBundleProperty(NotificationPreferencesInfo &preferencesInfo, + const sptr &bundleOption, const BundleType &type, const T &value) { ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (!preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { - bundleInfo.SetBundleName(bundleName); + if (!preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + bundleInfo.SetBundleName(bundleOption->GetBundleName()); + bundleInfo.SetBundleUid(bundleOption->GetUid()); } - result = SaveBundleProperty(bundleInfo, bundleName, type, value); + result = SaveBundleProperty(bundleInfo, bundleOption, type, value); preferencesInfo.SetBundleInfo(bundleInfo); return result; @@ -630,61 +707,57 @@ ErrCode NotificationPreferences::SetBundleProperty( template ErrCode NotificationPreferences::SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, - const std::string &bundleName, const BundleType &type, const T &value) + const sptr &bundleOption, const BundleType &type, const T &value) { bool storeDBResult = true; switch (type) { - case BundleType::kBundleImportanceType: + case BundleType::BUNDLE_IMPORTANCE_TYPE: bundleInfo.SetImportance(value); - storeDBResult = preferncesDB_->PutImportance(bundleName, value); + storeDBResult = preferncesDB_->PutImportance(bundleOption->GetBundleName(), value); break; - case BundleType::kBundleBadgeTotalNumType: + case BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE: bundleInfo.SetBadgeTotalNum(value); - storeDBResult = preferncesDB_->PutTotalBadgeNums(bundleName, value); + storeDBResult = preferncesDB_->PutTotalBadgeNums(bundleOption->GetBundleName(), value); break; - case BundleType::kBundleShowBadgeType: + case BundleType::BUNDLE_SHOW_BADGE_TYPE: bundleInfo.SetIsShowBadge(value); - storeDBResult = preferncesDB_->PutShowBadge(bundleName, value); + storeDBResult = preferncesDB_->PutShowBadge(bundleOption->GetBundleName(), value); break; - case BundleType::kBundlePrivateAllowedType: + case BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE: bundleInfo.SetIsPrivateAllowed(value); - storeDBResult = preferncesDB_->PutPrivateNotificationsAllowed(bundleName, value); + storeDBResult = preferncesDB_->PutPrivateNotificationsAllowed(bundleOption->GetBundleName(), value); break; - case BundleType::kBundleEnableNotificationType: + case BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE: bundleInfo.SetEnableNotification(value); - storeDBResult = preferncesDB_->PutNotificationsEnabledForBundle(bundleName, value); + storeDBResult = preferncesDB_->PutNotificationsEnabledForBundle(bundleOption->GetBundleName(), 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 ErrCode NotificationPreferences::GetBundleProperty( - const std::string &bundleName, const BundleType &type, T &value) const + const sptr &bundleOption, const BundleType &type, T &value) const { ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + if (preferencesInfo_.GetBundleInfo(bundleOption, 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: @@ -698,10 +771,16 @@ ErrCode NotificationPreferences::GetBundleProperty( return result; } +std::string NotificationPreferences::GenerateBundleKey(const sptr &bundleOption) const +{ + return bundleOption->GetBundleName().append(std::to_string(bundleOption->GetUid())); +} + 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 98c59565439cda6199c88eca298f5af7193306cb..5cfc88b316b938e6f7d60e864ccbcbf9a40c4448 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) + const std::string &bundleKey, const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + if (bundleKey.empty()) { + ANS_LOGE("Bundle name is null."); return false; } if (slots.empty()) { - ANS_LOGE("Slot is empty"); + ANS_LOGE("Slot is empty."); return false; } bool result = true; std::vector entries; for (auto iter : slots) { - result = SlotToEntry(bundleName, iter, entries); + result = SlotToEntry(bundleKey, iter, entries); if (!result) { return result; } } if (!CheckKvStore()) { - ANS_LOGE("KvStore is nullptr"); + ANS_LOGE("KvStore is nullptr."); return false; } OHOS::DistributedKv::Status status = kvStorePtr_->PutBatch(entries); @@ -190,122 +174,154 @@ bool NotificationPreferencesDatabase::PutSlotsToDisturbeDB( } bool NotificationPreferencesDatabase::PutGroupsToDisturbeDB( - const std::string &bundleName, const std::vector> &groups) + const std::string &bundleKey, const std::vector> &groups) { - if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + if (bundleKey.empty()) { + ANS_LOGE("Bundle name is null."); return false; } if (groups.empty()) { - ANS_LOGE("Slot is empty"); + ANS_LOGE("Slot is empty."); return false; } bool result = true; std::vector entries; for (auto iter : groups) { - result = GroupToEntry(bundleName, iter, entries); + result = GroupToEntry(bundleKey, iter, entries); if (!result) { return result; } } 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::PutShowBadge(const std::string &bundleName, const bool &enable) +bool NotificationPreferencesDatabase::PutBundlePropertyToDisturbeDB( + const NotificationPreferencesInfo::BundleInfo &bundleInfo) { - if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + if (bundleInfo.GetBundleName().empty()) { + ANS_LOGE("Bundle name is null."); return false; } - if (!CheckBundle(bundleName)) { + 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 &bundleKey, const bool &enable) +{ + if (bundleKey.empty()) { + ANS_LOGE("Bundle name is null."); + return false; + } + + if (!CheckBundle(bundleKey)) { return false; } OHOS::DistributedKv::Status status = - PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleShowBadgeType, enable); + PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_SHOW_BADGE_TYPE, enable); return (status == OHOS::DistributedKv::Status::SUCCESS); } -bool NotificationPreferencesDatabase::PutImportance(const std::string &bundleName, const int &importance) +bool NotificationPreferencesDatabase::PutImportance(const std::string &bundleKey, const int &importance) { - if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + if (bundleKey.empty()) { + ANS_LOGE("Bundle name is null."); return false; } - if (!CheckBundle(bundleName)) { + if (!CheckBundle(bundleKey)) { return false; } OHOS::DistributedKv::Status status = - PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleImportanceType, importance); + PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_IMPORTANCE_TYPE, importance); return (status == OHOS::DistributedKv::Status::SUCCESS); } -bool NotificationPreferencesDatabase::PutTotalBadgeNums(const std::string &bundleName, const int &totalBadgeNum) +bool NotificationPreferencesDatabase::PutTotalBadgeNums(const std::string &bundleKey, const int &totalBadgeNum) { - if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + if (bundleKey.empty()) { + ANS_LOGE("Bundle name is null."); return false; } - if (!CheckBundle(bundleName)) { + if (!CheckBundle(bundleKey)) { return false; } OHOS::DistributedKv::Status status = - PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleBadgeTotalNumType, totalBadgeNum); + PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, totalBadgeNum); return (status == OHOS::DistributedKv::Status::SUCCESS); } -bool NotificationPreferencesDatabase::PutPrivateNotificationsAllowed(const std::string &bundleName, const bool &allow) +bool NotificationPreferencesDatabase::PutPrivateNotificationsAllowed(const std::string &bundleKey, const bool &allow) { - if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + if (bundleKey.empty()) { + ANS_LOGE("Bundle name is null."); return false; } - if (!CheckBundle(bundleName)) { + if (!CheckBundle(bundleKey)) { return false; } OHOS::DistributedKv::Status status = - PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundlePrivateAllowedType, allow); + PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE, allow); return (status == OHOS::DistributedKv::Status::SUCCESS); } bool NotificationPreferencesDatabase::PutNotificationsEnabledForBundle( - const std::string &bundleName, const bool &enabled) + const std::string &bundleKey, const bool &enabled) { - if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + if (bundleKey.empty()) { + ANS_LOGE("Bundle name is null."); return false; } - if (!CheckBundle(bundleName)) { + if (!CheckBundle(bundleKey)) { return false; } OHOS::DistributedKv::Status status = - PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleEnableNotificationType, enabled); + PutBundlePropertyToDisturbeDB(bundleKey, 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; } @@ -373,14 +389,16 @@ void NotificationPreferencesDatabase::GetValueFromDisturbeDB( funcion(status, value); } -bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleName) +bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleKey) { - std::string bundleKeyStr = kBundleLabel + bundleName; + std::string bundleKeyStr = KEY_BUNDLE_LABEL + bundleKey; 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(bundleKey); + result = PutBundleToDisturbeDB(bundleKey, 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 bundleKey = bundleInfo.GetBundleName(); + GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_NAME), bundleKey, entries); + GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_BADGE_TOTAL_NUM), + std::to_string(bundleInfo.GetBadgeTotalNum()), + entries); GenerateEntry( - GenerateBundleKey(bundleName, kBundlePrivateAllowed), std::to_string(BUNDLE_PRIVATE_ALLOWED), entries); + GenerateBundleKey(bundleKey, KEY_BUNDLE_IMPORTANCE), std::to_string(bundleInfo.GetImportance()), entries); GenerateEntry( - GenerateBundleKey(bundleName, kBundleEnableNotification), std::to_string(BUNDLE_ENABLE_NOTIFICATION), entries); + GenerateBundleKey(bundleKey, KEY_BUNDLE_SHOW_BADGE), std::to_string(bundleInfo.GetIsShowBadge()), entries); + GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_PRIVATE_ALLOWED), + std::to_string(bundleInfo.GetIsPrivateAllowed()), + entries); + GenerateEntry(GenerateBundleKey(bundleKey, 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,28 +465,28 @@ 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_); return (status == OHOS::DistributedKv::Status::SUCCESS); } -bool NotificationPreferencesDatabase::RemoveBundleFromDisturbeDB(const std::string &bundleName) +bool NotificationPreferencesDatabase::RemoveBundleFromDisturbeDB(const std::string &bundleKey) { 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 + bundleKey + KEY_UNDER_LINE}, entries); if (status != OHOS::DistributedKv::Status::SUCCESS) { ANS_LOGE("Get Bundle Info failed."); @@ -472,8 +498,8 @@ bool NotificationPreferencesDatabase::RemoveBundleFromDisturbeDB(const std::stri keys.push_back(iter.key); } - OHOS::DistributedKv::Key bundleKey({kBundleLabel + kBundleName + kUnderLine + bundleName}); - keys.push_back(bundleKey); + OHOS::DistributedKv::Key bundleDBKey({KEY_BUNDLE_LABEL + KEY_BUNDLE_NAME + KEY_UNDER_LINE + bundleKey}); + keys.push_back(bundleDBKey); status = kvStorePtr_->DeleteBatch(keys); if (status != OHOS::DistributedKv::Status::SUCCESS) { ANS_LOGE("delete bundle Info failed."); @@ -483,23 +509,23 @@ bool NotificationPreferencesDatabase::RemoveBundleFromDisturbeDB(const std::stri } bool NotificationPreferencesDatabase::RemoveSlotFromDisturbeDB( - const std::string &bundleName, const NotificationConstant::SlotType &type) + const std::string &bundleKey, const NotificationConstant::SlotType &type) { ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + if (bundleKey.empty()) { + 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(bundleKey, slotType) + KEY_UNDER_LINE}, slotentries); if (status != DistributedKv::Status::SUCCESS) { return false; } @@ -508,62 +534,89 @@ 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 &bundleKey) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + if (bundleKey.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(bundleKey) + 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) + const std::string &bundleKey, const std::vector &groupIds) { - if (bundleName.empty()) { - ANS_LOGE("Bundle Name is Null"); + if (bundleKey.empty()) { + 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; } std::vector keys; bool result = true; for (auto iter : groupIds) { - result = GetRemoveGroupKeysFromDisturbeDB(bundleName, iter, keys); + result = GetRemoveGroupKeysFromDisturbeDB(bundleKey, iter, keys); if (!result) { return result; } } 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) + const std::string &bundleKey, 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); + std::string slotKeyStr = GenerateGroupKey(bundleKey, groupId); + status = kvStorePtr_->GetEntries({slotKeyStr + KEY_UNDER_LINE}, groupentries); if (status != DistributedKv::Status::SUCCESS) { return false; } @@ -571,88 +624,70 @@ 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 OHOS::DistributedKv::Status NotificationPreferencesDatabase::PutBundlePropertyToDisturbeDB( - const std::string &bundleName, const BundleType &type, const T &t) + const std::string &bundleKey, const BundleType &type, const T &t) { std::string keyStr; switch (type) { - case BundleType::kBundleBadgeTotalNumType: - keyStr = GenerateBundleKey(bundleName, kBundleBadgeTotalNum); + case BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE: + keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_BADGE_TOTAL_NUM); break; - case BundleType::kBundleImportanceType: - keyStr = GenerateBundleKey(bundleName, kBundleImportance); + case BundleType::BUNDLE_IMPORTANCE_TYPE: + keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_IMPORTANCE); break; - case BundleType::kBundleShowBadgeType: - keyStr = GenerateBundleKey(bundleName, kBundleShowBadge); + case BundleType::BUNDLE_SHOW_BADGE_TYPE: + keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_SHOW_BADGE); break; - case BundleType::kBundlePrivateAllowedType: - keyStr = GenerateBundleKey(bundleName, kBundlePrivateAllowed); + case BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE: + keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_PRIVATE_ALLOWED); break; - case BundleType::kBundleEnableNotificationType: - keyStr = GenerateBundleKey(bundleName, kBundleEnableNotification); + case BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE: + keyStr = GenerateBundleKey(bundleKey, 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 &bundleKey, 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); - OHOS::DistributedKv::Value bundleValue(bundleName); - if (kvStorePtr_->Put(bundleKey, bundleValue) != OHOS::DistributedKv::Status::SUCCESS) { + ANS_LOGD("Key not fund, so create a bundle, bundle key is %{public}s.", bundleKey.c_str()); + OHOS::DistributedKv::Key bundleDBKey(KEY_BUNDLE_LABEL + bundleKey); + OHOS::DistributedKv::Value bundleValue(bundleKey); + if (kvStorePtr_->Put(bundleDBKey, 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); @@ -671,99 +706,101 @@ void NotificationPreferencesDatabase::GenerateEntry( } bool NotificationPreferencesDatabase::SlotToEntry( - const std::string &bundleName, const sptr &slot, std::vector &entries) + const std::string &bundleKey, const sptr &slot, std::vector &entries) { if (slot == nullptr) { - ANS_LOGE("Notification group is nullptr"); + ANS_LOGE("Notification group is nullptr."); return false; } - if (!CheckBundle(bundleName)) { + if (!CheckBundle(bundleKey)) { return false; } - GenerateSlotEntry(bundleName, slot, entries); + GenerateSlotEntry(bundleKey, slot, entries); return true; } -void NotificationPreferencesDatabase::GenerateSlotEntry( - const std::string &bundleName, const sptr &slot, std::vector &entries) +void NotificationPreferencesDatabase::GenerateSlotEntry(const std::string &bundleKey, + 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(bundleKey, slotType, KEY_SLOT_TYPE), std::to_string(slot->GetType()), entries); + GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_ID), slot->GetId(), entries); + GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_GROUPID), slot->GetSlotGroup(), entries); + GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_NAME), slot->GetName(), entries); + GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_DESCRIPTION), slot->GetDescription(), entries); + GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_LEVEL), std::to_string(slot->GetLevel()), entries); GenerateEntry( - GenerateSlotKey(bundleName, slotType, kSlotEnableLight), std::to_string(slot->CanEnableLight()), entries); + GenerateSlotKey(bundleKey, slotType, KEY_SLOT_SHOW_BADGE), std::to_string(slot->IsShowBadge()), entries); GenerateEntry( - GenerateSlotKey(bundleName, slotType, kSlotEnableVrbration), std::to_string(slot->CanVibrate()), entries); + GenerateSlotKey(bundleKey, 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(bundleKey, slotType, KEY_SLOT_ENABLE_VRBRATION), std::to_string(slot->CanVibrate()), entries); + GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_LED_LIGHT_COLOR), + std::to_string(slot->GetLedLightColor()), + entries); + GenerateEntry(GenerateSlotKey(bundleKey, 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(bundleKey, slotType, KEY_SLOT_SOUND), slot->GetSound().ToString(), entries); + GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_VIBRATION_STYLE), std::to_string(slot->IsEnableBypassDnd()), entries); - GenerateEntry( - GenerateSlotKey(bundleName, slotType, kSlotVibrationSytle), VectorToString(slot->GetVibrationStyle()), entries); + GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_VIBRATION_STYLE), + VectorToString(slot->GetVibrationStyle()), + entries); } -bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleName, +bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleKey, const sptr &group, std::vector &entries) { if (group == nullptr) { - ANS_LOGE("Notification group is nullptr"); + ANS_LOGE("Notification group is nullptr."); return false; } - if (!CheckBundle(bundleName)) { + if (!CheckBundle(bundleKey)) { return false; } - GenerateGroupEntry(bundleName, group, entries); + GenerateGroupEntry(bundleKey, group, entries); return true; } -void NotificationPreferencesDatabase::GenerateGroupEntry(const std::string &bundleName, - const sptr &group, std::vector &entries) +void NotificationPreferencesDatabase::GenerateGroupEntry(const std::string &bundleKey, + 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(bundleKey, groupLebal + KEY_GROUP_ID), group->GetId(), entries); + GenerateEntry(GenerateGroupKey(bundleKey, groupLebal + KEY_GROUP_NAME), group->GetName(), entries); + GenerateEntry(GenerateGroupKey(bundleKey, groupLebal + KEY_GROUP_DESCRIPTION), group->GetDescription(), entries); GenerateEntry( - GenerateGroupKey(bundleName, groupLebal + kGroupDisable), std::to_string(group->IsDisabled()), entries); + GenerateGroupKey(bundleKey, 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()); + std::string bundleKey = item.value.ToString(); + ANS_LOGD("Bundle name is %{public}s.", bundleKey.c_str()); std::vector bundleEntries; - kvStorePtr_->GetEntries({GenerateBundleKey(bundleName)}, bundleEntries); - ANS_LOGD("bundle key is %{public}s", GenerateBundleKey(bundleName).c_str()); + kvStorePtr_->GetEntries({GenerateBundleKey(bundleKey)}, bundleEntries); + ANS_LOGD("Bundle key is %{public}s.", GenerateBundleKey(bundleKey).c_str()); NotificationPreferencesInfo::BundleInfo bunldeInfo; for (auto bundleEntry : bundleEntries) { - if (bundleEntry.key.ToString().find(kSlot) != std::string::npos) { - ParseSlotFromDisturbeDB(bunldeInfo, bundleName, bundleEntry); - } else if (bundleEntry.key.ToString().find(kGroup) != std::string::npos) { - ParseGroupFromDisturbeDB(bunldeInfo, bundleName, bundleEntry); + if (bundleEntry.key.ToString().find(KEY_SLOT) != std::string::npos) { + ParseSlotFromDisturbeDB(bunldeInfo, bundleKey, bundleEntry); + } else if (bundleEntry.key.ToString().find(KEY_GROUP) != std::string::npos) { + ParseGroupFromDisturbeDB(bunldeInfo, bundleKey, bundleEntry); } else { - ParseBundlePropertyFromDisturbeDB(bunldeInfo, bundleEntry.key, bundleEntry.value); + ParseBundlePropertyFromDisturbeDB(bunldeInfo, bundleKey, bundleEntry); } } @@ -772,33 +809,33 @@ void NotificationPreferencesDatabase::ParseBundleFromDistureDB( } void NotificationPreferencesDatabase::ParseSlotFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, - const std::string &bundleName, const OHOS::DistributedKv::Entry &entry) + const std::string &bundleKey, 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(bundleKey) + 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(bundleKey, typeStr) + KEY_UNDER_LINE; + ParseSlot(findString, slot, entry); bundleInfo.SetSlot(slot); } void NotificationPreferencesDatabase::ParseGroupFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, - const std::string &bundleName, const OHOS::DistributedKv::Entry &entry) + const std::string &bundleKey, 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(bundleKey) + 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(bundleKey, 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(bundleKey, 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 &bundleKey, + 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(bundleKey), 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,44 +951,48 @@ 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; } std::string NotificationPreferencesDatabase::GenerateBundleKey( - const std::string &bundleName, const std::string &type) const + const std::string &bundleKey, const std::string &type) const { /*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(bundleKey).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 &bundleKey, sptr &group, const OHOS::DistributedKv::Entry &entry) { - std::string typeStr = FindLastString(entry.key.ToString()); + std::string findStr = GenerateGroupKey(bundleKey, 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 1202b287063c5ea1cb8dea9106de0465fdcd0fe4..b77906aaa177ce84c565331c2eee7bf16f3d712e 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -108,12 +108,17 @@ bool NotificationPreferencesInfo::BundleInfo::GetAllSlots(std::vector> &slots) + const std::string &groupId, std::vector> &slots) { std::for_each(slots_.begin(), slots_.end(), - [&slots, &groupId](std::map>::reference &iter) { + [&](std::map>::reference iter) { if (!iter.second->GetSlotGroup().compare(groupId)) { slots.emplace_back(iter.second); } @@ -121,17 +126,32 @@ bool NotificationPreferencesInfo::BundleInfo::GetAllSlotsInGroup( return true; } +bool NotificationPreferencesInfo::BundleInfo::GetAllSlotsInGroup( + const std::string &groupId, std::vector &slots) +{ + std::for_each(slots_.begin(), + slots_.end(), + [&](std::map>::reference &iter) { + if (!iter.second->GetSlotGroup().compare(groupId)) { + slots.emplace_back(*iter.second); + } + }); + return true; +} + void NotificationPreferencesInfo::BundleInfo::SetGroup(const sptr &group) { groups_.insert_or_assign(group->GetId(), group); } -bool NotificationPreferencesInfo::BundleInfo::GetGroup( - const std::string &groupId, sptr &group) const +bool NotificationPreferencesInfo::BundleInfo::GetGroup(const std::string &groupId, sptr &group) { auto iter = groups_.find(groupId); if (iter != groups_.end()) { group = iter->second; + std::vector slots; + GetAllSlotsInGroup(groupId, slots); + group->SetSlots(slots); return true; } return false; @@ -140,7 +160,10 @@ bool NotificationPreferencesInfo::BundleInfo::GetGroup( bool NotificationPreferencesInfo::BundleInfo::GetAllGroups(std::vector> &group) { std::for_each( - groups_.begin(), groups_.end(), [&group](std::map>::reference &iter) { + groups_.begin(), groups_.end(), [&](std::map>::reference iter) { + std::vector slots; + GetAllSlotsInGroup(iter.second->GetId(), slots); + iter.second->SetSlots(slots); group.emplace_back(iter.second); }); return true; @@ -179,6 +202,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); @@ -189,6 +217,16 @@ bool NotificationPreferencesInfo::BundleInfo::RemoveSlotGroup(const std::string return false; } +void NotificationPreferencesInfo::BundleInfo::SetBundleUid(const int &uid) +{ + uid_ = uid; +} + +int NotificationPreferencesInfo::BundleInfo::GetBundleUid() const +{ + return uid_; +} + void NotificationPreferencesInfo::SetEnabledAllNotification(const bool &value) { isEnabledAllNotification_ = value; @@ -211,12 +249,15 @@ NotificationConstant::DisturbMode NotificationPreferencesInfo::GetDisturbMode() void NotificationPreferencesInfo::SetBundleInfo(const BundleInfo &info) { - infos_.insert_or_assign(info.GetBundleName(), info); + std::string bundleKey = info.GetBundleName().append(std::to_string(info.GetBundleUid())); + infos_.insert_or_assign(bundleKey, info); } -bool NotificationPreferencesInfo::GetBundleInfo(const std::string &bundleName, BundleInfo &info) const +bool NotificationPreferencesInfo::GetBundleInfo( + const sptr &bundleOption, BundleInfo &info) const { - auto iter = infos_.find(bundleName); + std::string bundleKey = bundleOption->GetBundleName() + std::to_string(bundleOption->GetUid()); + auto iter = infos_.find(bundleKey); if (iter != infos_.end()) { info = iter->second; return true; @@ -224,9 +265,10 @@ bool NotificationPreferencesInfo::GetBundleInfo(const std::string &bundleName, B return false; } -bool NotificationPreferencesInfo::RemoveBundleInfo(const std::string &bundleName) +bool NotificationPreferencesInfo::RemoveBundleInfo(const sptr &bundleOption) { - auto iter = infos_.find(bundleName); + std::string bundleKey = bundleOption->GetBundleName() + std::to_string(bundleOption->GetUid()); + auto iter = infos_.find(bundleKey); if (iter != infos_.end()) { infos_.erase(iter); return true; @@ -234,9 +276,10 @@ bool NotificationPreferencesInfo::RemoveBundleInfo(const std::string &bundleName return false; } -bool NotificationPreferencesInfo::IsExsitBundleInfo(const std::string &bundleName) const +bool NotificationPreferencesInfo::IsExsitBundleInfo(const sptr &bundleOption) const { - auto iter = infos_.find(bundleName); + std::string bundleKey = bundleOption->GetBundleName() + std::to_string(bundleOption->GetUid()); + auto iter = infos_.find(bundleKey); if (iter != infos_.end()) { return true; } diff --git a/services/ans/src/notification_slot_filter.cpp b/services/ans/src/notification_slot_filter.cpp index 6231cccb2fd67cce5d16540e062ed27db20272be..d59d1d181ee1fbf38621f09547dd0c1dbb3066f7 100644 --- a/services/ans/src/notification_slot_filter.cpp +++ b/services/ans/src/notification_slot_filter.cpp @@ -32,16 +32,30 @@ 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()); + if (record->request->GetVisibleness() == NotificationConstant::VisiblenessType::NO_OVERRIDE) { + record->request->SetVisibleness(record->slot->GetLockScreenVisibleness()); + } } else { ANS_LOGE("Non valid slot!"); return ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index f39e953f557f960f878c343deccdf97c73f95175..fedc523f82bbe35a6a536534d1cbe9e7bcea6811 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -271,7 +271,7 @@ void NotificationSubscriberManager::NotifyConsumedInner( auto BundleNames = notification->GetBundleName(); auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); - if (record->subscribedAll ^ (iter != record->bundleList_.end())) { + if (!record->subscribedAll == (iter != record->bundleList_.end())) { record->subscriber->OnConsumed(notification, notificationMap); record->subscriber->OnConsumed(notification); } @@ -285,7 +285,7 @@ void NotificationSubscriberManager::NotifyCanceledInner( auto BundleNames = notification->GetBundleName(); auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); - if (iter != record->bundleList_.end() ^ record->subscribedAll) { + if (!record->subscribedAll == (iter != record->bundleList_.end())) { record->subscriber->OnCanceled(notification, notificationMap, deleteReason); record->subscriber->OnCanceled(notification); } diff --git a/services/ans/src/permission_filter.cpp b/services/ans/src/permission_filter.cpp index 9f368e08df56faa8746f8464270ae2f610a20f07..d66946c6c9b92638229969941dca7ead26920e74 100644 --- a/services/ans/src/permission_filter.cpp +++ b/services/ans/src/permission_filter.cpp @@ -31,8 +31,8 @@ void PermissionFilter::OnStop() ErrCode PermissionFilter::OnPublish(const std::shared_ptr &record) { bool enable = false; - ErrCode result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle( - record->notification->GetBundleName(), enable); + ErrCode result = + NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(record->bundleOption, enable); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { result = ERR_OK; enable = true; diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index 2130524d959a9b4de40fd110b855898c1be613c7..959e85f80e9dbf9c559497a5259ff22ad50636f9 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -15,6 +15,7 @@ #include "system_event_observer.h" +#include "bundle_constants.h" #include "common_event_manager.h" #include "common_event_support.h" @@ -45,8 +46,10 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { if (callbacks_.onBundleRemoved != nullptr) { auto element = want.GetElement(); - std::string bundle = element.GetBundleName(); - callbacks_.onBundleRemoved(bundle); + std::string bundleName = element.GetBundleName(); + int uid = want.GetIntParam(AppExecFwk::Constants::UID, -1); + sptr bundleOption = new NotificationBundleOption(bundleName, uid); + callbacks_.onBundleRemoved(bundleOption); } } } diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index a2288126eb9da3d2f46f46702ea6e3262fdf20d3..8da3be02ecd880a23a342e6fda4560ae0cac2988 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -24,6 +24,7 @@ config("json_config") { ohos_unittest("ans_unit_test") { module_out_path = module_output_path include_dirs = [ + ".", "include", "//foundation/appexecfwk/standard/libs/libeventhandler/src", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", @@ -44,7 +45,6 @@ ohos_unittest("ans_unit_test") { sources = [ "${services_path}/ans/src/advanced_notification_service.cpp", "${services_path}/ans/src/advanced_notification_service_ability.cpp", - "${services_path}/ans/src/bundle_manager_helper.cpp", "${services_path}/ans/src/disturb_filter.cpp", "${services_path}/ans/src/notification_preferences.cpp", "${services_path}/ans/src/notification_preferences_database.cpp", @@ -57,12 +57,10 @@ ohos_unittest("ans_unit_test") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/autils/src/constant.cpp", "advanced_notification_service_ability_test.cpp", "advanced_notification_service_test.cpp", - "bundle_manager_helper_test.cpp", "disturb_filter_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", - "mock/mock_bundle_manager.cpp", - "mock/mock_bundle_mgr_proxy.cpp", + "mock/mock_bundle_manager_helper.cpp", "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", diff --git a/services/ans/test/unittest/advanced_notification_service_ability_test.cpp b/services/ans/test/unittest/advanced_notification_service_ability_test.cpp index 553e8fcbe1245ec42d8a0c8a3493acd1e4f185e9..a13769aa91a7dcacf035df2ba7f4cc4777570d8e 100644 --- a/services/ans/test/unittest/advanced_notification_service_ability_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_ability_test.cpp @@ -19,33 +19,22 @@ #include "advanced_notification_service_ability.h" using namespace testing::ext; + namespace OHOS { namespace Notification { class AdvancedNotificationServiceAbilityTest : public testing::Test { public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); + static void SetUpTestCase(){}; + static void TearDownTestCase(){}; + void SetUp(){}; + void TearDown(){}; }; -void AdvancedNotificationServiceAbilityTest::SetUpTestCase() -{} - -void AdvancedNotificationServiceAbilityTest::TearDownTestCase() -{} - -void AdvancedNotificationServiceAbilityTest::SetUp() -{} - -void AdvancedNotificationServiceAbilityTest::TearDown() -{} - /** * @tc.number : AdvancedNotificationServiceAbilityTest_00100 * @tc.name : AMS_ANS_AdvancedNotificationServiceAbility_0100 - * @tc.desc : structure AdvancedNotificationServiceAbility with systemAbilityId and runOnCreate + * @tc.desc : Structure AdvancedNotificationServiceAbility with systemAbilityId and runOnCreate */ HWTEST_F( AdvancedNotificationServiceAbilityTest, AdvancedNotificationServiceAbilityTest_00100, Function | SmallTest | Level1) @@ -54,5 +43,6 @@ HWTEST_F( bool runOnCreate = true; AdvancedNotificationServiceAbility(systemAbilityId, runOnCreate); } + } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index b483171c2118e1e5aeac8423b56fc1d75fd821de..90d0cbc84faec23e3db0d39eafbff568b730bae5 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -13,18 +13,24 @@ * limitations under the License. */ +#include #include -#include +#include + +#include "gtest/gtest.h" #define private public + #include "advanced_notification_service.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "ans_ut_constant.h" #include "mock_ipc_skeleton.h" #include "notification_preferences.h" #include "notification_subscriber.h" -#include "ans_inner_errors.h" - using namespace testing::ext; + namespace OHOS { namespace Notification { @@ -34,29 +40,41 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + +private: + void TestAddSlot(NotificationConstant::SlotType type); + void TestAddSlotGroup(); + +private: + static sptr advancedNotificationService_; }; -sptr g_advancedNotificationService; + +sptr AdvancedNotificationServiceTest::advancedNotificationService_ = nullptr; + void AdvancedNotificationServiceTest::SetUpTestCase() { - g_advancedNotificationService = AdvancedNotificationService::GetInstance(); + advancedNotificationService_ = AdvancedNotificationService::GetInstance(); } void AdvancedNotificationServiceTest::TearDownTestCase() { - sptr g_advancedNotificationService = nullptr; + advancedNotificationService_ = nullptr; } void AdvancedNotificationServiceTest::SetUp() { NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); - IPCSkeleton::SetCallingUid(1); - g_advancedNotificationService->CancelAll(); + IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + advancedNotificationService_->CancelAll(); } void AdvancedNotificationServiceTest::TearDown() +{} + +inline void SleepForFC() { - NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); - sleep(1); + // For ANS Flow Control + std::this_thread::sleep_for(std::chrono::seconds(1)); } class TestAnsSubscriber : public NotificationSubscriber { @@ -83,60 +101,68 @@ public: {} }; -void TestAddSlots(NotificationConstant::SlotType type) +void AdvancedNotificationServiceTest::TestAddSlot(NotificationConstant::SlotType type) { std::vector> slots; sptr slot = new NotificationSlot(type); slots.push_back(slot); - g_advancedNotificationService->AddSlots(slots); + EXPECT_EQ(advancedNotificationService_->AddSlots(slots), (int)ERR_OK); } -void TestAddSlotGroups() +void AdvancedNotificationServiceTest::TestAddSlotGroup() { std::vector> groups; sptr group = new NotificationSlotGroup("id0", "name0"); groups.push_back(group); - g_advancedNotificationService->AddSlotGroups(groups); + advancedNotificationService_->AddSlotGroups(groups); } /** * @tc.number : AMS_ANS_Publish_00100 * @tc.name : ANSPublish00100 - * @tc.desc : When there is no such notification in the notification queue, - * the test publish interface can successfully publish a normal text type notification. + * @tc.desc : Publish a normal text type notification. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00100, Function | SmallTest | Level1) { - sptr req = new NotificationRequest(); + TestAddSlot(NotificationConstant::SlotType::OTHER); + sptr req = new NotificationRequest(1); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::OTHER); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + SleepForFC(); } /** * @tc.number : AMS_ANS_Publish_00200 * @tc.name : ANSPublish00200 - * @tc.desc : When the notification is in the notification queue, - * the test publish interface can successfully publish a notification of normal text type. + * @tc.desc : Publish a normal text type notification twice. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00200, Function | SmallTest | Level1) { - sptr req = new NotificationRequest(); + TestAddSlot(NotificationConstant::SlotType::OTHER); + sptr req = new NotificationRequest(1); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::OTHER); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - g_advancedNotificationService->Publish(label, req); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + SleepForFC(); } /** @@ -147,38 +173,46 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00200, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00300, Function | SmallTest | Level1) { - IPCSkeleton::SetCallingUid(750); + IPCSkeleton::SetCallingUid(NON_SYSTEM_APP_UID); sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::CUSTOM); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_ANS_NON_SYSTEM_APP); + SleepForFC(); } /** * @tc.number : AMS_ANS_Publish_00400 * @tc.name : ANSPublish00400 * @tc.desc : When the obtained bundleName is empty, the notification publish interface returns - * ERR_ANS_INVALID_PARAM. + * ERR_ANS_INVALID_BUNDLE. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00400, Function | SmallTest | Level1) { - IPCSkeleton::SetCallingUid(1250); + IPCSkeleton::SetCallingUid(NON_BUNDLE_NAME_UID); sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_ANS_INVALID_BUNDLE); + SleepForFC(); } /** @@ -189,16 +223,21 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00400, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00500, Function | SmallTest | Level1) { + TestAddSlot(NotificationConstant::SlotType::SERVICE_REMINDER); sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + SleepForFC(); } /** @@ -209,17 +248,21 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00500, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00600, Function | SmallTest | Level1) { + TestAddSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); sptr req = new NotificationRequest(); - req->SetSlotType(NotificationConstant::SlotType::OTHER); + EXPECT_NE(req, nullptr); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - TestAddSlots(NotificationConstant::SlotType::OTHER); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + SleepForFC(); } /** @@ -231,16 +274,19 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00600, HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00700, Function | SmallTest | Level1) { sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - TestAddSlots(NotificationConstant::SlotType::OTHER); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + SleepForFC(); } /** @@ -250,16 +296,21 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00700, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00800, Function | SmallTest | Level1) { + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + SleepForFC(); } /** @@ -269,16 +320,21 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00800, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00900, Function | SmallTest | Level1) { + TestAddSlot(NotificationConstant::SlotType::SERVICE_REMINDER); sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::SERVICE_REMINDER); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + SleepForFC(); } /** @@ -288,16 +344,21 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00900, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01000, Function | SmallTest | Level1) { + TestAddSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + SleepForFC(); } /** @@ -307,16 +368,21 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01000, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01100, Function | SmallTest | Level1) { + TestAddSlot(NotificationConstant::SlotType::OTHER); sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::OTHER); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + SleepForFC(); } /** @@ -326,16 +392,21 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01100, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01200, Function | SmallTest | Level1) { + TestAddSlot(NotificationConstant::SlotType::CUSTOM); sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::CUSTOM); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + SleepForFC(); } /** @@ -346,30 +417,37 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01200, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01300, Function | SmallTest | Level1) { + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); req->SetLabel("req's label"); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", false); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_ANS_NOT_ALLOWED); + EXPECT_EQ(advancedNotificationService_->SetNotificationsEnabledForSpecialBundle( + std::string(), new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), false), + (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_ANS_NOT_ALLOWED); + SleepForFC(); } /** * @tc.number : AMS_ANS_Publish_01400 * @tc.name : ANSPublish01400 - * @tc.desc : When IsAlertOneTime, reset ColorEnabled, Sound, VibrationStyle, and publish the notification + * @tc.desc : */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01400, Function | SmallTest | Level1) { - TestAddSlotGroups(); + TestAddSlotGroup(); std::vector groupIds; groupIds.push_back("id0"); - EXPECT_EQ(g_advancedNotificationService->RemoveSlotGroups(groupIds), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->RemoveSlotGroups(groupIds), (int)ERR_OK); } /** @@ -385,8 +463,8 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01600, slots.push_back(slot0); slots.push_back(slot1); std::vector> slotsResult; - g_advancedNotificationService->AddSlots(slots); - g_advancedNotificationService->GetSlots(slotsResult); + advancedNotificationService_->AddSlots(slots); + advancedNotificationService_->GetSlots(slotsResult); EXPECT_EQ((int)slots.size(), 2); EXPECT_EQ((int)slotsResult.size(), 1); } @@ -402,9 +480,9 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01700, sptr group2 = new NotificationSlotGroup("id2", "name2"); group2->SetDescription("Description"); groups.push_back(group2); - g_advancedNotificationService->AddSlotGroups(groups); + advancedNotificationService_->AddSlotGroups(groups); sptr group = new NotificationSlotGroup(); - EXPECT_EQ(g_advancedNotificationService->GetSlotGroup("id2", group), ERR_OK); + EXPECT_EQ(advancedNotificationService_->GetSlotGroup("id2", group), ERR_OK); EXPECT_EQ(group2->GetId(), group->GetId()); EXPECT_EQ(group2->GetName(), group->GetName()); EXPECT_EQ(group2->GetDescription(), group->GetDescription()); @@ -417,8 +495,8 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01700, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01800, Function | SmallTest | Level1) { - TestAddSlots(NotificationConstant::SlotType::OTHER); - EXPECT_EQ((int)g_advancedNotificationService->SetNotificationBadgeNum(2), (int)ERR_OK); + TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ((int)advancedNotificationService_->SetNotificationBadgeNum(2), (int)ERR_OK); } /** @@ -428,9 +506,9 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01800, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01900, Function | SmallTest | Level1) { - TestAddSlots(NotificationConstant::SlotType::OTHER); + TestAddSlot(NotificationConstant::SlotType::OTHER); int importance; - EXPECT_EQ((int)g_advancedNotificationService->GetBundleImportance(importance), (int)ERR_OK); + EXPECT_EQ((int)advancedNotificationService_->GetBundleImportance(importance), (int)ERR_OK); } /** @@ -440,8 +518,8 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01900, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02000, Function | SmallTest | Level1) { - TestAddSlots(NotificationConstant::SlotType::OTHER); - EXPECT_EQ((int)g_advancedNotificationService->SetPrivateNotificationsAllowed(true), (int)ERR_OK); + TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ((int)advancedNotificationService_->SetPrivateNotificationsAllowed(true), (int)ERR_OK); } /** @@ -451,13 +529,29 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02000, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02100, Function | SmallTest | Level1) { - TestAddSlots(NotificationConstant::SlotType::OTHER); - EXPECT_EQ((int)g_advancedNotificationService->SetPrivateNotificationsAllowed(true), (int)ERR_OK); - bool allow; - EXPECT_EQ((int)g_advancedNotificationService->GetPrivateNotificationsAllowed(allow), (int)ERR_OK); + TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ((int)advancedNotificationService_->SetPrivateNotificationsAllowed(true), (int)ERR_OK); + bool allow = false; + EXPECT_EQ((int)advancedNotificationService_->GetPrivateNotificationsAllowed(allow), (int)ERR_OK); EXPECT_TRUE(allow); } +/** + * @tc.number : AdvancedNotificationServiceTest_02200 + * @tc.name : AMS_ANS_UpdateSlots_0100 + * @tc.desc : Test UpdateSlots function when no slot + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02200, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + EXPECT_EQ((int)advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST); +} + /** * @tc.number : AdvancedNotificationServiceTest_02300 * @tc.name : AMS_ANS_UpdateSlots_0200 @@ -465,39 +559,45 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02100, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02300, Function | SmallTest | Level1) { - std::string bundle = "bundleName"; + TestAddSlot(NotificationConstant::SlotType::OTHER); std::vector> slots; - TestAddSlots(NotificationConstant::SlotType::OTHER); sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); slots.push_back(slot0); - EXPECT_EQ((int)g_advancedNotificationService->UpdateSlots(bundle, slots), (int)ERR_OK); + EXPECT_EQ((int)advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), + (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_02500 - * @tc.name : AMS_ANS_UpdateSlotGroups_0200 - * @tc.desc : Test UpdateSlotGroups function + * @tc.number : AdvancedNotificationServiceTest_02400 + * @tc.name : AMS_ANS_UpdateSlotGroups_0100 + * @tc.desc : Test UpdateSlotGroups function when no group */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02500, Function | SmallTest | Level1) +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02400, Function | SmallTest | Level1) { - std::string bundle = "bundleName"; + TestAddSlotGroup(); std::vector> groups; - sptr group2 = new NotificationSlotGroup("id0", "name2"); + sptr group2 = new NotificationSlotGroup("id1", "name1"); groups.push_back(group2); - TestAddSlotGroups(); - EXPECT_EQ((int)g_advancedNotificationService->UpdateSlotGroups(bundle, groups), (int)ERR_OK); + EXPECT_EQ((int)advancedNotificationService_->UpdateSlotGroups( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), groups), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST); } /** - * @tc.number : AdvancedNotificationServiceTest_02600 - * @tc.name : AMS_ANS_SetNotificationsEnabledForBundle_0100 - * @tc.desc : Test SetNotificationsEnabledForBundle function when no bundle + * @tc.number : AdvancedNotificationServiceTest_02500 + * @tc.name : AMS_ANS_UpdateSlotGroups_0200 + * @tc.desc : Test UpdateSlotGroups function */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02600, Function | SmallTest | Level1) +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02500, Function | SmallTest | Level1) { - std::string bundle = ""; - EXPECT_EQ((int)g_advancedNotificationService->SetNotificationsEnabledForBundle(bundle, true), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + TestAddSlotGroup(); + std::vector> groups; + sptr group2 = new NotificationSlotGroup("id0", "name1"); + groups.push_back(group2); + EXPECT_EQ((int)advancedNotificationService_->UpdateSlotGroups( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), groups), + (int)ERR_OK); } /** @@ -507,8 +607,9 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02600, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02700, Function | SmallTest | Level1) { - std::string bundle = ""; - EXPECT_EQ(g_advancedNotificationService->SetShowBadgeEnabledForBundle(bundle, true), (int)ERR_ANS_INVALID_PARAM); + EXPECT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), + (int)ERR_OK); } /** @@ -518,9 +619,10 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02700, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02800, Function | SmallTest | Level1) { - std::string bundle = "bundleName"; - bool allow; - EXPECT_EQ((int)g_advancedNotificationService->GetShowBadgeEnabledForBundle(bundle, allow), (int)ERR_OK); + bool allow = false; + EXPECT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); } /** @@ -531,53 +633,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02800, HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02900, Function | SmallTest | Level1) { std::vector> notifications; - EXPECT_EQ((int)g_advancedNotificationService->GetActiveNotifications(notifications), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03000 - * @tc.name : AMS_ANS_SetNotificationAgent_0100 - * @tc.desc : Test SetNotificationAgent function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03000, Function | SmallTest | Level1) -{ - std::string agent = "agent"; - g_advancedNotificationService->SetNotificationAgent(agent); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03100 - * @tc.name : AMS_ANS_GetNotificationAgent_0100 - * @tc.desc : Test GetNotificationAgent function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03100, Function | SmallTest | Level1) -{ - std::string agent; - g_advancedNotificationService->GetNotificationAgent(agent); -} - -/** - * @tc.number : NotificationPreferencesTest_03200 - * @tc.name : AMS_ANS_CanPublishAsBundle_0100 - * @tc.desc : Test CanPublishAsBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03200, Function | SmallTest | Level1) -{ - std::string representativeBundle = "representativeBundle"; - bool canPublish = true; - g_advancedNotificationService->CanPublishAsBundle(representativeBundle, canPublish); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03300 - * @tc.name : AMS_ANS_PublishAsBundle_0100 - * @tc.desc : Test PublishAsBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03300, Function | SmallTest | Level1) -{ - std::string representativeBundle = "representativeBundle"; - sptr notification = new NotificationRequest(); - g_advancedNotificationService->PublishAsBundle(notification, representativeBundle); + EXPECT_EQ((int)advancedNotificationService_->GetActiveNotifications(notifications), (int)ERR_OK); } /** @@ -587,8 +643,8 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03300, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03400, Function | SmallTest | Level1) { - EXPECT_EQ((int)g_advancedNotificationService->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_PRIORITY), - (int)ERR_OK); + EXPECT_EQ( + (int)advancedNotificationService_->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_NONE), (int)ERR_OK); } /** @@ -598,20 +654,11 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03400, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03500, Function | SmallTest | Level1) { - TestAddSlots(NotificationConstant::SlotType::OTHER); + EXPECT_EQ( + (int)advancedNotificationService_->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_NONE), (int)ERR_OK); NotificationConstant::DisturbMode mode; - EXPECT_EQ((int)g_advancedNotificationService->GetDisturbMode(mode), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03600 - * @tc.name : AMS_ANS_HasNotificationPolicyAccessPermission_0100 - * @tc.desc : Test HasNotificationPolicyAccessPermission function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03600, Function | SmallTest | Level1) -{ - bool granted; - g_advancedNotificationService->HasNotificationPolicyAccessPermission(granted); + EXPECT_EQ((int)advancedNotificationService_->GetDisturbMode(mode), (int)ERR_OK); + EXPECT_EQ(mode, NotificationConstant::DisturbMode::ALLOW_NONE); } /** @@ -622,7 +669,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03600, HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03700, Function | SmallTest | Level1) { const std::string key = "key"; - EXPECT_EQ((int)g_advancedNotificationService->Delete(key), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + EXPECT_EQ((int)advancedNotificationService_->Delete(key), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); } /** @@ -632,8 +679,9 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03700, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03800, Function | SmallTest | Level1) { - const std::string bundle = "bundleName"; - EXPECT_EQ(g_advancedNotificationService->DeleteByBundle(bundle), ERR_OK); + EXPECT_EQ(advancedNotificationService_->DeleteByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID)), + ERR_OK); } /** @@ -643,7 +691,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03800, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03900, Function | SmallTest | Level1) { - EXPECT_EQ(g_advancedNotificationService->DeleteAll(), ERR_OK); + EXPECT_EQ(advancedNotificationService_->DeleteAll(), ERR_OK); } /** @@ -653,10 +701,12 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03900, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04000, Function | SmallTest | Level1) { - TestAddSlots(NotificationConstant::SlotType::OTHER); - std::string bundle = "bundleName"; + TestAddSlot(NotificationConstant::SlotType::OTHER); std::vector> slots; - EXPECT_EQ(g_advancedNotificationService->GetSlotsByBundle(bundle, slots), ERR_OK); + EXPECT_EQ(advancedNotificationService_->GetSlotsByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), + ERR_OK); + EXPECT_EQ(slots.size(), (size_t)1); } /** @@ -666,20 +716,563 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04000, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04100, Function | SmallTest | Level1) { + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); req->SetLabel("req's label"); req->SetAlertOneTime(true); std::string label = "publish's label"; std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); normalContent->SetText("normalContent's text"); normalContent->SetTitle("normalContent's title"); std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); req->SetContent(content); - g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", true); - g_advancedNotificationService->Publish(label, req); - EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + std::vector> allNotifications; + EXPECT_EQ(advancedNotificationService_->GetAllActiveNotifications(allNotifications), (int)ERR_OK); + EXPECT_EQ(allNotifications.size(), (size_t)1); + std::vector keys; + for (auto notification : allNotifications) { + keys.push_back(notification->GetKey()); + } + std::vector> specialActiveNotifications; + EXPECT_EQ( + advancedNotificationService_->GetSpecialActiveNotifications(keys, specialActiveNotifications), (int)ERR_OK); + EXPECT_EQ(specialActiveNotifications.size(), (size_t)1); + SleepForFC(); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04600 + * @tc.name : AMS_ANS_Publish_0500 + * @tc.desc : publish function when NotificationsEnabled is false + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04600, Function | SmallTest | Level1) +{ + sptr req = new NotificationRequest(1); + req->SetSlotType(NotificationConstant::OTHER); + TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ(advancedNotificationService_->SetNotificationsEnabledForSpecialBundle( + std::string(), new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), false), + (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Publish(std::string(), req), (int)ERR_ANS_NOT_ALLOWED); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04700 + * @tc.name : AMS_ANS_Cancel_0100 + * @tc.desc : public two notification to cancel one of them + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04700, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + std::string label = "testLabel"; + { + sptr req = new NotificationRequest(1); + req->SetSlotType(NotificationConstant::OTHER); + req->SetLabel(label); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + } + { + sptr req = new NotificationRequest(2); + req->SetSlotType(NotificationConstant::OTHER); + req->SetLabel(label); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + } + EXPECT_EQ(advancedNotificationService_->Cancel(1, label), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04800 + * @tc.name : AMS_ANS_Cancel_0200 + * @tc.desc : Test Cancel function when notification no exists + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04800, Function | SmallTest | Level1) +{ + int32_t notificationId = 0; + std::string label = "testLabel"; + EXPECT_EQ((int)advancedNotificationService_->Cancel(notificationId, label), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04900 + * @tc.name : AMS_ANS_CancelAll_0100 + * @tc.desc : Test CancelAll function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04900, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + sptr req = new NotificationRequest(1); + req->SetSlotType(NotificationConstant::OTHER); + EXPECT_EQ(advancedNotificationService_->CancelAll(), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05000 + * @tc.name : AMS_ANS_Cancel_0100 + * @tc.desc : Test Cancel function when unremovable is true + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05000, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + int32_t notificationId = 2; + std::string label = "testLabel"; + sptr req = new NotificationRequest(notificationId); + req->SetSlotType(NotificationConstant::OTHER); + req->SetLabel(label); + req->SetUnremovable(true); + EXPECT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->Cancel(notificationId, label), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05100 + * @tc.name : AMS_ANS_AddSlots_0100 + * @tc.desc : Test AddSlots function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05100, Function | SmallTest | Level1) +{ + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + sptr slot1 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + slots.push_back(slot1); + EXPECT_EQ(advancedNotificationService_->AddSlots(slots), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05200 + * @tc.name : AMS_ANS_RemoveSlotByType_0100 + * @tc.desc : Test RemoveSlotByType function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05200, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ(advancedNotificationService_->RemoveSlotByType(NotificationConstant::OTHER), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05300 + * @tc.name : AMS_ANS_RemoveSlotByType_0200 + * @tc.desc : Test RemoveSlotByType function when no type + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05300, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ((int)advancedNotificationService_->RemoveSlotByType(NotificationConstant::CUSTOM), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05400 + * @tc.name : AMS_ANS_AddSlotGroups_0100 + * @tc.desc : Test AddSlotGroups function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05400, Function | SmallTest | Level1) +{ + std::vector> groups; + sptr group0 = new NotificationSlotGroup("id0", "name0"); + sptr group1 = new NotificationSlotGroup("id1", "name1"); + groups.push_back(group0); + groups.push_back(group1); + EXPECT_EQ(advancedNotificationService_->AddSlotGroups(groups), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05500 + * @tc.name : AMS_ANS_RemoveSlotGroups_0100 + * @tc.desc : Test RemoveSlotGroups function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05500, Function | SmallTest | Level1) +{ + TestAddSlotGroup(); + std::vector groupIds; + groupIds.push_back("id0"); + EXPECT_EQ(advancedNotificationService_->RemoveSlotGroups(groupIds), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05600 + * @tc.name : AMS_ANS_GetSlot_0100 + * @tc.desc : Test GetSlot function for data + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05600, Function | SmallTest | Level1) +{ + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::OTHER); + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + advancedNotificationService_->AddSlots(slots); + EXPECT_EQ((int)advancedNotificationService_->GetSlotByType(NotificationConstant::OTHER, slot), ERR_OK); + EXPECT_EQ(slot->GetName(), slot0->GetName()); + EXPECT_EQ(slot->GetId(), slot0->GetId()); + EXPECT_EQ(slot->GetLevel(), slot0->GetLevel()); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05800 + * @tc.name : AMS_ANS_GetSlotGroup_0100 + * @tc.desc : Test GetSlotGroup function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05800, Function | SmallTest | Level1) +{ + std::vector> groups; + sptr group2 = new NotificationSlotGroup("id2", "name2"); + group2->SetDescription("Description"); + groups.push_back(group2); + advancedNotificationService_->AddSlotGroups(groups); + sptr group = new NotificationSlotGroup(); + EXPECT_EQ(advancedNotificationService_->GetSlotGroup("id2", group), ERR_OK); + EXPECT_EQ(group2->GetId(), group->GetId()); + EXPECT_EQ(group2->GetName(), group->GetName()); + EXPECT_EQ(group2->GetDescription(), group->GetDescription()); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05900 + * @tc.name : AMS_ANS_SetNotificationBadgeNum_0100 + * @tc.desc : Test SetNotificationBadgeNum function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05900, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ((int)advancedNotificationService_->SetNotificationBadgeNum(2), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06000 + * @tc.name : AMS_ANS_GetBundleImportance_0100 + * @tc.desc : Test GetBundleImportance function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06000, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + int importance = 0; + EXPECT_EQ((int)advancedNotificationService_->GetBundleImportance(importance), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06100 + * @tc.name : AMS_ANS_SetPrivateNotificationsAllowed_0100 + * @tc.desc : Test SetPrivateNotificationsAllowed function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06100, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ((int)advancedNotificationService_->SetPrivateNotificationsAllowed(true), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06200 + * @tc.name : AMS_ANS_GetPrivateNotificationsAllowed_0100 + * @tc.desc : Test GetPrivateNotificationsAllowed function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06200, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ((int)advancedNotificationService_->SetPrivateNotificationsAllowed(true), (int)ERR_OK); + bool allow = false; + EXPECT_EQ((int)advancedNotificationService_->GetPrivateNotificationsAllowed(allow), (int)ERR_OK); + EXPECT_TRUE(allow); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06300 + * @tc.name : AMS_ANS_UpdateSlots_0100 + * @tc.desc : Test UpdateSlots function when no slot + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06300, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + EXPECT_EQ((int)advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06400 + * @tc.name : AMS_ANS_UpdateSlots_0200 + * @tc.desc : Test UpdateSlots function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06400, Function | SmallTest | Level1) +{ + std::vector> slots; + TestAddSlot(NotificationConstant::SlotType::OTHER); + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + EXPECT_EQ((int)advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06500 + * @tc.name : AMS_ANS_UpdateSlotGroups_0100 + * @tc.desc : Test UpdateSlotGroups function when no group + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06500, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + std::vector> groups; + sptr group2 = new NotificationSlotGroup("id2", "name2"); + groups.push_back(group2); + EXPECT_EQ((int)advancedNotificationService_->UpdateSlotGroups( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), groups), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06600 + * @tc.name : AMS_ANS_UpdateSlotGroups_0200 + * @tc.desc : Test UpdateSlotGroups function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06600, Function | SmallTest | Level1) +{ + TestAddSlotGroup(); + std::vector> groups; + sptr group2 = new NotificationSlotGroup("id0", "name2"); + groups.push_back(group2); + EXPECT_EQ((int)advancedNotificationService_->UpdateSlotGroups( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), groups), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06800 + * @tc.name : AMS_ANS_SetShowBadgeEnabledForBundle_0100 + * @tc.desc : Test the SetShowBadgeEnabledForBundle function when the parameter is wrong + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06800, Function | SmallTest | Level1) +{ + EXPECT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( + new NotificationBundleOption("", SYSTEM_APP_UID), true), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06900 + * @tc.name : AMS_ANS_GetShowBadgeEnabledForBundle_0100 + * @tc.desc : Test GetShowBadgeEnabledForBundle function when no bundle + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06900, Function | SmallTest | Level1) +{ + bool allow = false; + EXPECT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_07000 + * @tc.name : AMS_ANS_GetActiveNotifications_0100 + * @tc.desc : Test GetActiveNotifications function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07000, Function | SmallTest | Level1) +{ + std::vector> notifications; + EXPECT_EQ((int)advancedNotificationService_->GetActiveNotifications(notifications), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_07800 + * @tc.name : AMS_ANS_Delete_0100 + * @tc.desc : Test Delete function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07800, Function | SmallTest | Level1) +{ + const std::string key = "key"; + EXPECT_EQ((int)advancedNotificationService_->Delete(key), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_07900 + * @tc.name : AMS_ANS_DeleteByBundle_0100 + * @tc.desc : Test DeleteByBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07900, Function | SmallTest | Level1) +{ + EXPECT_EQ(advancedNotificationService_->DeleteByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID)), + ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_08000 + * @tc.name : AMS_ANS_DeleteAll_0100 + * @tc.desc : Test DeleteAll function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08000, Function | SmallTest | Level1) +{ + EXPECT_EQ(advancedNotificationService_->DeleteAll(), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_08300 + * @tc.name : AMS_ANS_Subscribe_0100 + * @tc.desc : Test Subscribe function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08300, Function | SmallTest | Level1) +{ + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + EXPECT_EQ((int)advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), (int)ERR_OK); + EXPECT_EQ((int)advancedNotificationService_->Unsubscribe(subscriber->GetImpl(), nullptr), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_08600 + * @tc.name : AMS_ANS_GetShowBadgeEnabledForBundle_0200 + * @tc.desc : Test GetShowBadgeEnabledForBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08600, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ((int)advancedNotificationService_->SetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), + (int)ERR_OK); + bool allow = false; + EXPECT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), + (int)ERR_OK); + EXPECT_TRUE(allow); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_08700 + * @tc.name : AMS_ANS_GetSlotByType_0100 + * @tc.desc : Test GetSlotByType function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08700, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + sptr slot; + EXPECT_EQ((int)advancedNotificationService_->GetSlotByType(NotificationConstant::OTHER, slot), (int)ERR_OK); + EXPECT_EQ(slot->GetType(), NotificationConstant::SlotType::OTHER); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_08900 + * @tc.name : AMS_ANS_GetSlotGroups_0100 + * @tc.desc : Test GetSlotGroups function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08900, Function | SmallTest | Level1) +{ + std::vector> groups; + sptr group2 = new NotificationSlotGroup("id2", "name2"); + group2->SetDescription("Description"); + groups.push_back(group2); + advancedNotificationService_->AddSlotGroups(groups); + std::vector> group; + EXPECT_EQ(advancedNotificationService_->GetSlotGroups(group), ERR_OK); + EXPECT_EQ(groups.size(), group.size()); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09000 + * @tc.name : AMS_ANS_GetAllActiveNotifications_0100 + * @tc.desc : Test GetAllActiveNotifications function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09000, Function | SmallTest | Level1) +{ + std::vector> notifications; + EXPECT_EQ(advancedNotificationService_->GetAllActiveNotifications(notifications), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09200 + * @tc.name : AMS_ANS_SetNotificationsEnabledForAllBundles_0200 + * @tc.desc : Test SetNotificationsEnabledForAllBundles function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09200, Function | SmallTest | Level1) +{ + EXPECT_EQ( + (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09300 + * @tc.name : AMS_ANS_SetNotificationsEnabledForSpecialBundle_0100 + * @tc.desc : Test SetNotificationsEnabledForSpecialBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09300, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + std::vector> notifications; + EXPECT_EQ((int)advancedNotificationService_->SetNotificationsEnabledForSpecialBundle( + std::string(), new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09500 + * @tc.name : AMS_ANS_IsAllowedNotify_0100 + * @tc.desc : Test IsAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09500, Function | SmallTest | Level1) +{ + bool allowed = false; + EXPECT_EQ((int)advancedNotificationService_->IsAllowedNotify(allowed), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09600 + * @tc.name : AMS_ANS_IsAllowedNotify_0200 + * @tc.desc : Test IsAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09600, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + bool allowed = false; + EXPECT_EQ((int)advancedNotificationService_->IsAllowedNotify(allowed), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09700 + * @tc.name : AMS_ANS_IsSpecialBundleAllowedNotify_0100 + * @tc.desc : Test IsSpecialBundleAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09700, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + bool allowed = true; + EXPECT_EQ((int)advancedNotificationService_->IsSpecialBundleAllowedNotify( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09800 + * @tc.name : AMS_ANS_IsSpecialBundleAllowedNotify_0200 + * @tc.desc : Test IsSpecialBundleAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09800, Function | SmallTest | Level1) +{ + std::vector> notifications; + bool allowed = true; + EXPECT_EQ((int)advancedNotificationService_->IsSpecialBundleAllowedNotify( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09900 + * @tc.name : AMS_ANS_GetSlotsByBundle_0200 + * @tc.desc : Test GetSlotsByBundle function when no bundle + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09900, Function | SmallTest | Level1) +{ + std::vector> slots; + EXPECT_EQ((int)advancedNotificationService_->GetSlotsByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), slots), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); } } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/ans/test/unittest/ans_ut_constant.h b/services/ans/test/unittest/ans_ut_constant.h new file mode 100644 index 0000000000000000000000000000000000000000..886634b712c7763886178d30c05387d834abc23d --- /dev/null +++ b/services/ans/test/unittest/ans_ut_constant.h @@ -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. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_TEST_UNITEST_ANS_UT_CONSTANT_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_TEST_UNITEST_ANS_UT_CONSTANT_H + +#include + +namespace OHOS { +namespace Notification { +constexpr int SYSTEM_APP_UID = 100; +constexpr int NON_SYSTEM_APP_UID = 1000; +constexpr int NON_BUNDLE_NAME_UID = 2000; +const std::string TEST_DEFUALT_BUNDLE = "bundleName"; +} // namespace Notification +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/ans/test/unittest/bundle_manager_helper_test.cpp b/services/ans/test/unittest/bundle_manager_helper_test.cpp index b64140c3f1e163b02e9097b33ba6babaee7d6a8f..69f6b11f28cf7037f77ac42a0d62147066ed9993 100644 --- a/services/ans/test/unittest/bundle_manager_helper_test.cpp +++ b/services/ans/test/unittest/bundle_manager_helper_test.cpp @@ -28,24 +28,12 @@ namespace Notification { class BundleManagerHelperTest : public testing::Test { public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); + static void SetUpTestCase(){}; + static void TearDownTestCase(){}; + void SetUp(){}; + void TearDown(){}; }; -void BundleManagerHelperTest::SetUpTestCase() -{} - -void BundleManagerHelperTest::TearDownTestCase() -{} - -void BundleManagerHelperTest::SetUp() -{} - -void BundleManagerHelperTest::TearDown() -{} - /** * @tc.number : BundleManagerHelperTest_00100 * @tc.name : AMS_ANS_GetBundleNameByUid_0100 @@ -53,7 +41,7 @@ void BundleManagerHelperTest::TearDown() */ HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00100, Function | SmallTest | Level1) { - uid_t callingUid = IPCSkeleton::GetCallingUid(); + pid_t callingUid = IPCSkeleton::GetCallingUid(); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); EXPECT_EQ(bundleManager->GetBundleNameByUid(callingUid), "bundleName"); } @@ -65,9 +53,9 @@ HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00100, Function | Smal */ HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00200, Function | SmallTest | Level1) { - uid_t callingUid = IPCSkeleton::GetCallingUid(); + pid_t callingUid = IPCSkeleton::GetCallingUid(); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); EXPECT_TRUE(bundleManager->IsSystemApp(callingUid)); } } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/ans/test/unittest/disturb_filter_test.cpp b/services/ans/test/unittest/disturb_filter_test.cpp index 4c00d8a28c2e7f4e4a4033b80aa75fec23a30628..7ef21bb507f1aad2ade4945a7aca0761cd158498 100644 --- a/services/ans/test/unittest/disturb_filter_test.cpp +++ b/services/ans/test/unittest/disturb_filter_test.cpp @@ -24,24 +24,12 @@ namespace Notification { class DisturbFilterTest : public testing::Test { public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); + static void SetUpTestCase(){}; + static void TearDownTestCase(){}; + void SetUp(){}; + void TearDown(){}; }; -void DisturbFilterTest::SetUpTestCase() -{} - -void DisturbFilterTest::TearDownTestCase() -{} - -void DisturbFilterTest::SetUp() -{} - -void DisturbFilterTest::TearDown() -{} - /** * @tc.number : DisturbFilterTest_00100 * @tc.name : AMS_ANS_OnStart_0100 diff --git a/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp b/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp index 33a1c730b25abe5dffc90ad7d709a51105799ba7..d755b0151ac19b60f4e18e540bc2c2488c1895fc 100644 --- a/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp +++ b/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp @@ -17,7 +17,6 @@ #include "distributed_kv_data_manager.h" #include "constant.h" -//#include "ikvstore.h" #include "mock_single_kv_store.h" #include "types.h" @@ -56,14 +55,10 @@ Status DistributedKvDataManager::DeleteKvStore(const AppId &appId, const StoreId void DistributedKvDataManager::RegisterKvStoreServiceDeathRecipient( std::shared_ptr kvStoreDeathRecipient) -{ - printf("@DistributedKvDataManager 3"); -} +{} void DistributedKvDataManager::UnRegisterKvStoreServiceDeathRecipient( std::shared_ptr kvStoreDeathRecipient) -{ - printf("@UnRegisterKvStoreServiceDeathRecipient 3"); -} +{} } // namespace DistributedKv } // namespace OHOS diff --git a/services/ans/test/unittest/mock/include/mock_bundle_manager.h b/services/ans/test/unittest/mock/include/mock_bundle_manager.h deleted file mode 100644 index 4b7875b331662556f3ea345dd2ce95619d193c76..0000000000000000000000000000000000000000 --- a/services/ans/test/unittest/mock/include/mock_bundle_manager.h +++ /dev/null @@ -1,412 +0,0 @@ -/* - * 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 FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H -#define FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H - -#include - -#include "ability_info.h" -#include "application_info.h" -#include "bundle_mgr_host.h" -#include "bundle_mgr_interface.h" -#include "iremote_proxy.h" -#include "iremote_stub.h" -#include "ohos/aafwk/content/want.h" - -namespace OHOS { -namespace AppExecFwk { -class MockBundleMgrService : public BundleMgrHost { -public: - MockBundleMgrService() - {} - - ~MockBundleMgrService() - {} - - /** - * @brief Obtains the ApplicationInfo based on a given bundle name. - * @param appName Indicates the application bundle name to be queried. - * @param flag Indicates the flag used to specify information contained - * in the ApplicationInfo object that will be returned. - * @param userId Indicates the user ID. - * @param appInfo Indicates the obtained ApplicationInfo object. - * @return Returns true if the application is successfully obtained; returns false otherwise. - */ - virtual bool GetApplicationInfo( - const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override - { - return true; - } - /** - * @brief Obtains information about all installed applications of a specified user. - * @param flag Indicates the flag used to specify information contained - * in the ApplicationInfo objects that will be returned. - * @param userId Indicates the user ID. - * @param appInfos Indicates all of the obtained ApplicationInfo objects. - * @return Returns true if the application is successfully obtained; returns false otherwise. - */ - virtual bool GetApplicationInfos( - const ApplicationFlag flag, const int userId, std::vector &appInfos) override - { - return true; - } - /** - * @brief Obtains the BundleInfo based on a given bundle name. - * @param bundleName Indicates the application bundle name to be queried. - * @param flag Indicates the information contained in the BundleInfo object to be returned. - * @param bundleInfo Indicates the obtained BundleInfo object. - * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override - { - return true; - } - /** - * @brief Obtains BundleInfo of all bundles available in the system. - * @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned. - * @param bundleInfos Indicates all of the obtained BundleInfo objects. - * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override - { - return true; - }; - /** - * @brief Obtains the application UID based on the given bundle name and user ID. - * @param bundleName Indicates the bundle name of the application. - * @param userId Indicates the user ID. - * @return Returns the uid if successfully obtained; returns -1 otherwise. - */ - virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override - { - return 0; - } - /** - * @brief Obtains the bundle name of a specified application based on the given UID. - * @param uid Indicates the uid. - * @param bundleName Indicates the obtained bundle name. - * @return Returns true if the bundle name is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override - { - bundleName = "hello"; - return true; - } - /** - * @brief Obtains an array of all group IDs associated with a specified bundle. - * @param bundleName Indicates the bundle name. - * @param gids Indicates the group IDs associated with the specified bundle. - * @return Returns true if the gids is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override - { - return true; - } - /** - * @brief Obtains the type of a specified application based on the given bundle name. - * @param bundleName Indicates the bundle name. - * @return Returns "system" if the bundle is a system application; returns "third-party" otherwise. - */ - virtual std::string GetAppType(const std::string &bundleName) override - { - return ""; - } - /** - * @brief Check whether the app is system app by it's UID. - * @param uid Indicates the uid. - * @return Returns true if the bundle is a system application; returns false otherwise. - */ - virtual bool CheckIsSystemAppByUid(const int uid) override; - - /** - * @brief Obtains the BundleInfo of application bundles based on the specified metaData. - * @param metaData Indicates the metadata to get in the bundle. - * @param bundleInfos Indicates all of the obtained BundleInfo objects. - * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override - { - return true; - } - /** - * @brief Query the AbilityInfo by the given Want. - * @param want Indicates the infomation of the ability. - * @param abilityInfo Indicates the obtained AbilityInfo object. - * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. - */ - virtual bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override - { - return true; - } - /** - * @brief Query the AbilityInfo by ability.uri in config.json. - * @param abilityUri Indicates the uri of the ability. - * @param abilityInfo Indicates the obtained AbilityInfo object. - * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. - */ - virtual bool QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) override - { - return true; - } - /** - * @brief Obtains the BundleInfo of all keep-alive applications in the system. - * @param bundleInfos Indicates all of the obtained BundleInfo objects. - * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. - */ - virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override - { - return true; - }; - /** - * @brief Obtains the label of a specified ability. - * @param bundleName Indicates the bundle name. - * @param className Indicates the ability class name. - * @return Returns the label of the ability if exist; returns empty string otherwise. - */ - virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override - { - return ""; - } - /** - * @brief Obtains information about an application bundle contained in a ohos Ability Package (HAP). - * @param hapFilePath Indicates the absolute file path of the HAP. - * @param flag Indicates the information contained in the BundleInfo object to be returned. - * @param bundleInfo Indicates the obtained BundleInfo object. - * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleArchiveInfo( - const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override - { - return true; - } - /** - * @brief Obtain the HAP module info of a specific ability. - * @param abilityInfo Indicates the ability. - * @param hapModuleInfo Indicates the obtained HapModuleInfo object. - * @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise. - */ - virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override - { - return true; - } - /** - * @brief Obtains the Want for starting the main ability of an application based on the given bundle name. - * @param bundleName Indicates the bundle name. - * @param want Indicates the obtained launch Want object. - * @return Returns true if the launch Want object is successfully obtained; returns false otherwise. - */ - virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override - { - return true; - } - /** - * @brief Confirms with the permission management module to check whether a request prompt is required for granting - * a certain permission. - * @param bundleName Indicates the name of the bundle to check. - * @param permission Indicates the permission to check. - * @param userId Indicates the user id. - * @return Returns true if the current application does not have the permission and the user does not turn off - * further requests; returns false if the current application already has the permission, the permission is rejected - * by the system, or the permission is denied by the user and the user has turned off further requests. - */ - virtual bool CanRequestPermission( - const std::string &bundleName, const std::string &permissionName, const int userId) override - { - return true; - } - /** - * @brief Checks whether the publickeys of two bundles are the same. - * @param firstBundleName Indicates the first bundle name. - * @param secondBundleName Indicates the second bundle name. - * @return Returns SIGNATURE_UNKNOWN_BUNDLE if at least one of the given bundles is not found; - * returns SIGNATURE_NOT_MATCHED if their publickeys are different; - * returns SIGNATURE_MATCHED if their publickeys are the same. - */ - virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override - { - return 0; - } - /** - * @brief Checks whether a specified bundle has been granted a specific permission. - * @param bundleName Indicates the name of the bundle to check. - * @param permission Indicates the permission to check. - * @return Returns 0 if the bundle has the permission; returns -1 otherwise. - */ - virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override; - /** - * @brief Obtains detailed information about a specified permission. - * @param permissionName Indicates the name of the ohos permission. - * @param permissionDef Indicates the object containing detailed information about the given ohos permission. - * @return Returns true if the PermissionDef object is successfully obtained; returns false otherwise. - */ - virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override - { - return true; - } - /** - * @brief Obtains all known permission groups in the system. - * @param permissionDefs Indicates the list of objects containing the permission group information. - * @return Returns true if the PermissionDef objects is successfully obtained; returns false otherwise. - */ - virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override - { - return true; - } - /** - * @brief Obtains all known permission groups in the system. - * @param permissions Indicates the permission array. - * @param appNames Indicates the list of application names that have the specified permissions. - * @return Returns true if the application names is successfully obtained; returns false otherwise. - */ - virtual bool GetAppsGrantedPermissions( - const std::vector &permissions, std::vector &appNames) override - { - return true; - } - /** - * @brief Requests a certain permission from user. - * @param bundleName Indicates the name of the bundle to request permission. - * @param permission Indicates the permission to request permission. - * @param userId Indicates the user id. - * @return Returns true if the permission request successfully; returns false otherwise. - */ - virtual bool RequestPermissionFromUser( - const std::string &bundleName, const std::string &permission, const int userId) override - { - return true; - } - /** - * @brief Checks whether the system has a specified capability. - * @param capName Indicates the name of the system feature to check. - * @return Returns true if the given feature specified by name is available in the system; returns false otherwise. - */ - virtual bool HasSystemCapability(const std::string &capName) override - { - return true; - } - /** - * @brief Obtains the capabilities that are available in the system. - * @param systemCaps Indicates the list of capabilities available in the system. - * @return Returns true if capabilities in the system are successfully obtained; returns false otherwise. - */ - virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override - { - return true; - } - /** - * @brief Checks whether the current device has been started in safe mode. - * @return Returns true if the device is in safe mode; returns false otherwise. - */ - virtual bool IsSafeMode() override - { - return true; - } - /** - * @brief Clears cache data of a specified application. - * @param bundleName Indicates the bundle name of the application whose cache data is to be cleared. - * @param cleanCacheCallback Indicates the callback to be invoked for returning the operation result. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) override - { - return true; - } - /** - * @brief Clears application running data of a specified application. - * @param bundleName Indicates the bundle name of the application whose data is to be cleared. - * @return Returns true if the data cleared successfully; returns false otherwise. - */ - virtual bool CleanBundleDataFiles(const std::string &bundleName) override - { - return true; - } - /** - * @brief Register the specific bundle status callback. - * @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override - { - return true; - } - /** - * @brief Clear the specific bundle status callback. - * @param bundleStatusCallback Indicates the callback to be cleared. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override - { - return true; - } - /** - * @brief Unregister all the callbacks of status changed. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool UnregisterBundleStatusCallback() override - { - return true; - } - /** - * @brief Dump the bundle informations with specifc flags. - * @param flag Indicates the information contained in the dump result. - * @param bundleName Indicates the bundle name if needed. - * @param result Indicates the dump infomation result. - * @return Returns true if the dump result is successfully obtained; returns false otherwise. - */ - virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override - { - return true; - } - /** - * @brief Checks whether a specified application is enabled. - * @param bundleName Indicates the bundle name of the application. - * @return Returns true if the application is enabled; returns false otherwise. - */ - virtual bool IsApplicationEnabled(const std::string &bundleName) override - { - return true; - } - /** - * @brief Sets whether to enable a specified application. - * @param bundleName Indicates the bundle name of the application. - * @param isEnable Specifies whether to enable the application. - * The value true means to enable it, and the value false means to disable it. - * @return Returns true if the application is enabled; returns false otherwise. - */ - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) 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. - */ - virtual sptr GetBundleInstaller() override - { - return nullptr; - } - - void MockSetIsSystemApp(bool isSystemApp); - -private: - bool isSystemApp_ = false; - bool isSystemAppMock_ = false; -}; -} // namespace AppExecFwk -} // namespace OHOS - -#endif // FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H \ No newline at end of file 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 39c56acabef2ab760551f9edb59aea969dc902d3..aafcb863794e9ce7f188b80081f6ad94ff8626c3 100755 --- a/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h +++ b/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 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 b7aa3f47499c5fc5c5cf856aa0156de7bd85bf0a..efde9364abf099b910403f6fb44b7e646bb97663 100644 --- a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -15,6 +15,7 @@ #include "bundle_manager_helper.h" +#include "ans_ut_constant.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "system_ability_definition.h" @@ -31,14 +32,19 @@ 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"; + return (uid == NON_BUNDLE_NAME_UID) ? "" : "bundleName"; } -bool BundleManagerHelper::IsSystemApp(uid_t uid) +int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle) { - return 500 < uid && uid < 1000 ? false : true; + return NON_SYSTEM_APP_UID; +} + +bool BundleManagerHelper::IsSystemApp(int uid) +{ + return (uid == SYSTEM_APP_UID); } void BundleManagerHelper::Connect() diff --git a/services/ans/test/unittest/mock/mock_bundle_mgr_proxy.cpp b/services/ans/test/unittest/mock/mock_bundle_mgr_proxy.cpp deleted file mode 100644 index 6c9526322d216064ea2b63a997b6037c74913d15..0000000000000000000000000000000000000000 --- a/services/ans/test/unittest/mock/mock_bundle_mgr_proxy.cpp +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "bundle_mgr_proxy.h" - -#include "ipc_types.h" -#include "parcel.h" -#include "string_ex.h" - -#include "appexecfwk_errors.h" -#include "bundle_constants.h" - -namespace OHOS { -namespace AppExecFwk { - -BundleMgrProxy::BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) -{} - -BundleMgrProxy::~BundleMgrProxy() -{} - -bool BundleMgrProxy::GetApplicationInfo( - const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) -{ - return true; -} - -bool BundleMgrProxy::GetApplicationInfos( - const ApplicationFlag flag, const int userId, std::vector &appInfos) -{ - return true; -} - -bool BundleMgrProxy::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) -{ - return true; -} - -bool BundleMgrProxy::GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) -{ - return true; -} - -int BundleMgrProxy::GetUidByBundleName(const std::string &bundleName, const int userId) -{ - return 1; -} - -std::string BundleMgrProxy::GetAppIdByBundleName(const std::string &bundleName, const int userId) -{ - return "appId"; -} - -bool BundleMgrProxy::GetBundleNameForUid(const int uid, std::string &bundleName) -{ - bundleName = "bundleName"; - return true; -} - -bool BundleMgrProxy::GetBundlesForUid(const int uid, std::vector &bundleNames) -{ - return true; -} - -bool BundleMgrProxy::GetNameForUid(const int uid, std::string &name) -{ - return true; -} - -bool BundleMgrProxy::GetBundleGids(const std::string &bundleName, std::vector &gids) -{ - return true; -} - -std::string BundleMgrProxy::GetAppType(const std::string &bundleName) -{ - return "Constants::EMPTY_STRING"; -} - -bool BundleMgrProxy::CheckIsSystemAppByUid(const int uid) -{ - return true; -} - -bool BundleMgrProxy::GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) -{ - return true; -} - -bool BundleMgrProxy::QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) -{ - return true; -} - -bool BundleMgrProxy::QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) -{ - return true; -} - -bool BundleMgrProxy::QueryKeepAliveBundleInfos(std::vector &bundleInfos) -{ - return true; -} - -std::string BundleMgrProxy::GetAbilityLabel(const std::string &bundleName, const std::string &className) -{ - return "reply.ReadString()"; -} - -bool BundleMgrProxy::GetBundleArchiveInfo(const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) -{ - return true; -} - -bool BundleMgrProxy::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) -{ - return true; -} - -bool BundleMgrProxy::GetLaunchWantForBundle(const std::string &bundleName, Want &want) -{ - return true; -} - -int BundleMgrProxy::CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) -{ - return 1; -} - -int BundleMgrProxy::CheckPermission(const std::string &bundleName, const std::string &permission) -{ - return 1; -} - -bool BundleMgrProxy::GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) -{ - return true; -} - -bool BundleMgrProxy::GetAllPermissionGroupDefs(std::vector &permissionDefs) -{ - return true; -} - -bool BundleMgrProxy::GetAppsGrantedPermissions( - const std::vector &permissions, std::vector &appNames) -{ - return true; -} - -bool BundleMgrProxy::HasSystemCapability(const std::string &capName) -{ - return true; -} - -bool BundleMgrProxy::GetSystemAvailableCapabilities(std::vector &systemCaps) -{ - return true; -} - -bool BundleMgrProxy::IsSafeMode() -{ - return true; -} - -bool BundleMgrProxy::CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) -{ - return true; -} - -bool BundleMgrProxy::CleanBundleDataFiles(const std::string &bundleName) -{ - return true; -} - -bool BundleMgrProxy::RegisterBundleStatusCallback(const sptr &bundleStatusCallback) -{ - return true; -} - -bool BundleMgrProxy::ClearBundleStatusCallback(const sptr &bundleStatusCallback) -{ - return true; -} - -bool BundleMgrProxy::UnregisterBundleStatusCallback() -{ - return true; -} - -bool BundleMgrProxy::DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) -{ - return true; -} - -bool BundleMgrProxy::IsApplicationEnabled(const std::string &bundleName) -{ - return true; -} - -bool BundleMgrProxy::SetApplicationEnabled(const std::string &bundleName, bool isEnable) -{ - return true; -} - -bool BundleMgrProxy::IsAbilityEnabled(const AbilityInfo &abilityInfo) -{ - return true; -} - -bool BundleMgrProxy::SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) -{ - return true; -} - -std::string BundleMgrProxy::GetAbilityIcon(const std::string &bundleName, const std::string &className) -{ - return "AbilityIcon"; -} - -bool BundleMgrProxy::CanRequestPermission( - const std::string &bundleName, const std::string &permissionName, const int userId) -{ - return true; -} - -bool BundleMgrProxy::RequestPermissionFromUser( - const std::string &bundleName, const std::string &permission, const int userId) -{ - return true; -} - -bool BundleMgrProxy::RegisterAllPermissionsChanged(const sptr &callback) -{ - return true; -} - -bool BundleMgrProxy::RegisterPermissionsChanged( - const std::vector &uids, const sptr &callback) -{ - return true; -} - -bool BundleMgrProxy::UnregisterPermissionsChanged(const sptr &callback) -{ - return true; -} - -template -bool BundleMgrProxy::GetParcelableInfo(IBundleMgr::Message code, MessageParcel &data, T &parcelableInfo) -{ - return true; -} - -template -bool BundleMgrProxy::GetParcelableInfos(IBundleMgr::Message code, MessageParcel &data, std::vector &parcelableInfos) -{ - return true; -} - -bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &data, MessageParcel &reply) -{ - return true; -} - -} // namespace AppExecFwk -} // namespace OHOS diff --git a/services/ans/test/unittest/mock/mock_ipc.cpp b/services/ans/test/unittest/mock/mock_ipc.cpp index 3c2bc08da34937d5f9bb2ec3c40eff95a87a7e13..42687ac92276295c9d7355f0ed18070969e909b9 100644 --- a/services/ans/test/unittest/mock/mock_ipc.cpp +++ b/services/ans/test/unittest/mock/mock_ipc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 @@ -29,8 +29,7 @@ pid_t IPCSkeleton::GetCallingUid() pid_t IPCSkeleton::GetCallingPid() { - uid_ = 1; - return uid_; + return 1; } void IPCSkeleton::SetCallingUid(pid_t uid) diff --git a/services/ans/test/unittest/mock/mock_single_kv_store.cpp b/services/ans/test/unittest/mock/mock_single_kv_store.cpp index 4b580d297471fb6658f861e020621e89b8cb9382..4f9c78aa8ccf6eebfbd66c35e224daad606cb9b0 100644 --- a/services/ans/test/unittest/mock/mock_single_kv_store.cpp +++ b/services/ans/test/unittest/mock/mock_single_kv_store.cpp @@ -57,11 +57,9 @@ Status AnsTestSingleKvStore::GetEntriesWithQuery(const DataQuery &query, std::ve // resultSet: resultSet will be returned in this parameter. // Return: // Status of this GetResultSet operation. -void AnsTestSingleKvStore::GetResultSet(const Key &prefixKey, - std::function)> callback) const -{ - -} +void AnsTestSingleKvStore::GetResultSet( + const Key &prefixKey, std::function)> callback) const +{} // Get ResultSet in this store by Query. // Parameters: @@ -69,11 +67,9 @@ void AnsTestSingleKvStore::GetResultSet(const Key &prefixKey, // 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 -{ - -} +void AnsTestSingleKvStore::GetResultSetWithQuery( + const std::string &query, std::function)> callback) const +{} // Get ResultSet in this store by Query. // Parameters: @@ -81,11 +77,9 @@ void AnsTestSingleKvStore::GetResultSetWithQuery(const std::string &query, // resultSet: resultSet will be returned in this parameter. // Return: // Status of this GetResultSet operation. -void AnsTestSingleKvStore::GetResultSetWithQuery(const DataQuery &query, - std::function)> callback) const -{ - -} +void AnsTestSingleKvStore::GetResultSetWithQuery( + const DataQuery &query, std::function)> callback) const +{} // Close the ResultSet returned by GetResultSet. // Parameters: @@ -128,7 +122,8 @@ Status AnsTestSingleKvStore::GetCountWithQuery(const DataQuery &query, int &resu // 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) +Status AnsTestSingleKvStore::Sync( + const std::vector &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs) { return Status::SUCCESS; } @@ -230,7 +225,6 @@ 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. @@ -290,8 +284,8 @@ Status AnsTestSingleKvStore::SetCapabilityEnabled(bool enabled) const return Status::SUCCESS; } -Status AnsTestSingleKvStore::SetCapabilityRange(const std::vector &localLabels, - const std::vector &remoteSupportLabels) const +Status AnsTestSingleKvStore::SetCapabilityRange( + const std::vector &localLabels, const std::vector &remoteSupportLabels) const { return Status::SUCCESS; } @@ -306,6 +300,5 @@ Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam return Status::SUCCESS; } - } // namespace DistributedKv } // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/notification_preferences_database_test.cpp b/services/ans/test/unittest/notification_preferences_database_test.cpp index b2ad8c94a5f03aad03556e327bb8a73b18966f30..36f044d30881b80593d47fea34d89f424adeefc2 100644 --- a/services/ans/test/unittest/notification_preferences_database_test.cpp +++ b/services/ans/test/unittest/notification_preferences_database_test.cpp @@ -16,7 +16,6 @@ #define private public #include -#include "notification_preferences.h" #include "notification_preferences_database.h" using namespace testing::ext; @@ -25,46 +24,35 @@ namespace Notification { class NotificationPreferencesDatabaseTest : public testing::Test { public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); + static void SetUpTestCase(){}; + static void TearDownTestCase(){}; + void SetUp(){}; + void TearDown(){}; + + const std::string bundleName_ = "bundleName"; + std::unique_ptr preferncesDB_ = + std::make_unique(); }; -void NotificationPreferencesDatabaseTest::SetUpTestCase() -{} - -void NotificationPreferencesDatabaseTest::TearDownTestCase() -{} - -void NotificationPreferencesDatabaseTest::SetUp() -{} - -void NotificationPreferencesDatabaseTest::TearDown() -{} - -std::unique_ptr preferncesDB_ = std::make_unique(); - /** + * @tc.name : PutSlotsToDisturbeDB_00100 * @tc.number : - * @tc.name : - * @tc.desc : PutSlotsToDisturbeDB_00100 + * @tc.desc : Put slots into Disturbe DB, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutSlotsToDisturbeDB_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; std::vector> slots; sptr slot1 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); sptr slot2 = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); slots.push_back(slot1); slots.push_back(slot2); - EXPECT_EQ(true, preferncesDB_->PutSlotsToDisturbeDB(bundleName, slots)); + EXPECT_TRUE(preferncesDB_->PutSlotsToDisturbeDB(bundleName_, slots)); } /** + * @tc.name : PutSlotsToDisturbeDB_00200 * @tc.number : - * @tc.name : - * @tc.desc : PutSlotsToDisturbeDB_00200 + * @tc.desc : Put slots into Disturbe DB when bundle name is null, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutSlotsToDisturbeDB_00200, Function | SmallTest | Level1) { @@ -73,348 +61,324 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutSlotsToDisturbeDB_00200, Functi sptr slot2 = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); slots.push_back(slot1); slots.push_back(slot2); - EXPECT_EQ(false, preferncesDB_->PutSlotsToDisturbeDB(std::string(), slots)); + EXPECT_FALSE(preferncesDB_->PutSlotsToDisturbeDB(std::string(), slots)); } /** + * @tc.name : PutSlotsToDisturbeDB_00300 * @tc.number : - * @tc.name : - * @tc.desc : PutSlotsToDisturbeDB_00300 + * @tc.desc : Put slots into Disturbe DB when slots is null, return is false. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutSlotsToDisturbeDB_00300, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; std::vector> slots; - EXPECT_EQ(false, preferncesDB_->PutSlotsToDisturbeDB(std::string(), slots)); + EXPECT_FALSE(preferncesDB_->PutSlotsToDisturbeDB(bundleName_, slots)); } /** + * @tc.name : PutGroupsToDisturbeDB_00100 * @tc.number : - * @tc.name : - * @tc.desc : PutGroupsToDisturbeDB_00100 + * @tc.desc : Put slot group into disturbe DB, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutGroupsToDisturbeDB_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - sptr slotGroup = new NotificationSlotGroup("id", "name"); std::vector> groups; groups.push_back(slotGroup); - EXPECT_EQ(true, preferncesDB_->PutGroupsToDisturbeDB(bundleName, groups)); + EXPECT_TRUE(preferncesDB_->PutGroupsToDisturbeDB(bundleName_, groups)); } /** + * @tc.name : PutGroupsToDisturbeDB_00200 * @tc.number : - * @tc.name : - * @tc.desc : PutGroupsToDisturbeDB_00200 + * @tc.desc : Put slot group into disturbe DB when bundle name is null, return is false. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutGroupsToDisturbeDB_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - + sptr slotGroup = new NotificationSlotGroup("id", "name"); std::vector> groups; + groups.push_back(slotGroup); + EXPECT_FALSE(preferncesDB_->PutGroupsToDisturbeDB(std::string(), groups)); +} - EXPECT_EQ(false, preferncesDB_->PutGroupsToDisturbeDB(bundleName, groups)); +/** + * @tc.number : PutGroupsToDisturbeDB_00300 + * @tc.name : + * @tc.desc : Put slot group into disturbe DB when groups is null, return is false. + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutGroupsToDisturbeDB_00300, Function | SmallTest | Level1) +{ + std::vector> groups; + EXPECT_FALSE(preferncesDB_->PutGroupsToDisturbeDB(bundleName_, groups)); } /** + * @tc.name : PutShowBadge_00100 * @tc.number : - * @tc.name : - * @tc.desc : PutShowBadge_00100 + * @tc.desc : Put bundle show badge into disturbe DB, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutShowBadge_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - - EXPECT_EQ(true, preferncesDB_->PutShowBadge(bundleName, true)); + EXPECT_TRUE(preferncesDB_->PutShowBadge(bundleName_, true)); + EXPECT_TRUE(preferncesDB_->PutShowBadge(bundleName_, false)); } /** - * @tc.number : + * @tc.number : PutShowBadge_00200 * @tc.name : - * @tc.desc : PutShowBadge_00200 + * @tc.desc : Put bundle show badge into disturbe DB when bundle name is null, return is false. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutShowBadge_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - - EXPECT_EQ(true, preferncesDB_->PutShowBadge(bundleName, false)); + EXPECT_FALSE(preferncesDB_->PutShowBadge(std::string(), false)); } /** + * @tc.name : PutImportance_00100 * @tc.number : - * @tc.name : - * @tc.desc : PutShowBadge_00300 + * @tc.desc : Put bundle importance into disturbe DB, return is true. */ -HWTEST_F(NotificationPreferencesDatabaseTest, PutShowBadge_00300, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, PutImportance_00100, Function | SmallTest | Level1) { - EXPECT_EQ(false, preferncesDB_->PutShowBadge(std::string(), false)); + EXPECT_TRUE( + preferncesDB_->PutImportance(bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_NONE)); + EXPECT_TRUE( + preferncesDB_->PutImportance(bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_MIN)); + EXPECT_TRUE( + preferncesDB_->PutImportance(bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_LOW)); + EXPECT_TRUE(preferncesDB_->PutImportance( + bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_DEFAULT)); + EXPECT_TRUE( + preferncesDB_->PutImportance(bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_HIGH)); + EXPECT_TRUE(preferncesDB_->PutImportance( + bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_UNDEFINED)); } /** + * @tc.name : PutImportance_00200 * @tc.number : - * @tc.name : - * @tc.desc : PutImportance_00100 + * @tc.desc : Put bundle importance into disturbe DB when bundle name is null, return is false. */ -HWTEST_F(NotificationPreferencesDatabaseTest, PutImportance_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, PutImportance_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - - EXPECT_EQ(true, - preferncesDB_->PutImportance(bundleName, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_NONE)); - EXPECT_EQ(true, - preferncesDB_->PutImportance(bundleName, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_MIN)); - EXPECT_EQ(true, - preferncesDB_->PutImportance(bundleName, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_LOW)); - EXPECT_EQ(true, - preferncesDB_->PutImportance( - bundleName, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_DEFAULT)); - EXPECT_EQ(true, - preferncesDB_->PutImportance(bundleName, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_HIGH)); - EXPECT_EQ(true, - preferncesDB_->PutImportance( - bundleName, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_UNDEFINED)); + EXPECT_FALSE(preferncesDB_->PutImportance( + std::string(), OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_NONE)); } /** + * @tc.name : PutTotalBadgeNums_00100 * @tc.number : - * @tc.name : - * @tc.desc : PutTotalBadgeNums_00100 + * @tc.desc : Put bundle total badge nums into disturbe DB, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutTotalBadgeNums_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - EXPECT_EQ(true, preferncesDB_->PutTotalBadgeNums(bundleName, 0)); + EXPECT_TRUE(preferncesDB_->PutTotalBadgeNums(bundleName_, 0)); } /** - * @tc.number : + * @tc.number : PutTotalBadgeNums_00200 * @tc.name : - * @tc.desc : PutTotalBadgeNums_00200 + * @tc.desc : Put bundle total badge nums into disturbe DB when bundle name is null, return is false. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutTotalBadgeNums_00200, Function | SmallTest | Level1) { - EXPECT_EQ(false, preferncesDB_->PutTotalBadgeNums(std::string(), 0)); + EXPECT_FALSE(preferncesDB_->PutTotalBadgeNums(std::string(), 0)); } /** + * @tc.name : PutPrivateNotificationsAllowed_00100 * @tc.number : - * @tc.name : - * @tc.desc : PutPrivateNotificationsAllowed_00100 + * @tc.desc : Put bundle private notification allowed into disturbe DB, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutPrivateNotificationsAllowed_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - - EXPECT_EQ(true, preferncesDB_->PutPrivateNotificationsAllowed(bundleName, true)); + EXPECT_TRUE(preferncesDB_->PutPrivateNotificationsAllowed(bundleName_, true)); + EXPECT_TRUE(preferncesDB_->PutPrivateNotificationsAllowed(bundleName_, true)); } /** + * @tc.name : PutPrivateNotificationsAllowed_00200 * @tc.number : - * @tc.name : - * @tc.desc : PutPrivateNotificationsAllowed_00200 + * @tc.desc : Put bundle private notification allowed into disturbe DB when bundle name is null, return is false. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutPrivateNotificationsAllowed_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - - EXPECT_EQ(true, preferncesDB_->PutPrivateNotificationsAllowed(bundleName, false)); -} - -/** - * @tc.number : - * @tc.name : - * @tc.desc : PutPrivateNotificationsAllowed_00300 - */ -HWTEST_F(NotificationPreferencesDatabaseTest, PutPrivateNotificationsAllowed_00300, Function | SmallTest | Level1) -{ - EXPECT_EQ(false, preferncesDB_->PutPrivateNotificationsAllowed(std::string(), false)); + EXPECT_FALSE(preferncesDB_->PutPrivateNotificationsAllowed(std::string(), false)); } /** + * @tc.name : PutNotificationsEnabledForBundle_00100 * @tc.number : - * @tc.name : - * @tc.desc : PutNotificationsEnabledForBundle_00100 + * @tc.desc : Put bundle enable into disturbe DB, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabledForBundle_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - - EXPECT_EQ(true, preferncesDB_->PutNotificationsEnabledForBundle(bundleName, true)); + EXPECT_TRUE(preferncesDB_->PutNotificationsEnabledForBundle(bundleName_, true)); + EXPECT_TRUE(preferncesDB_->PutNotificationsEnabledForBundle(bundleName_, false)); } /** + * @tc.name : PutNotificationsEnabledForBundle_00200 * @tc.number : - * @tc.name : - * @tc.desc : PutNotificationsEnabledForBundle_00200 + * @tc.desc : Put bundle enable into disturbe DB when bundle name is null, return is false. */ HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabledForBundle_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - - EXPECT_EQ(true, preferncesDB_->PutNotificationsEnabledForBundle(bundleName, false)); + EXPECT_FALSE(preferncesDB_->PutNotificationsEnabledForBundle(std::string(), false)); } /** - * @tc.number : + * @tc.number : PutNotificationsEnabled_00100 * @tc.name : - * @tc.desc : PutNotificationsEnabledForBundle_00300 + * @tc.desc : Put notification enable into disturbe DB, return is true. */ -HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabledForBundle_00300, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabled_00100, Function | SmallTest | Level1) { - EXPECT_EQ(false, preferncesDB_->PutNotificationsEnabledForBundle(std::string(), false)); + EXPECT_TRUE(preferncesDB_->PutNotificationsEnabled(true)); + EXPECT_TRUE(preferncesDB_->PutNotificationsEnabled(false)); } /** - * @tc.number : + * @tc.number : PutDisturbMode_00100 * @tc.name : - * @tc.desc : PutNotificationsEnabled_00100 + * @tc.desc : Put disturbe mode into disturbe DB, return is true. */ -HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabled_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, PutDisturbMode_00100, Function | SmallTest | Level1) { - - EXPECT_EQ(true, preferncesDB_->PutNotificationsEnabled(true)); + EXPECT_TRUE(preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALARMS)); + EXPECT_TRUE(preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALL)); + EXPECT_TRUE(preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_NONE)); + EXPECT_TRUE(preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_PRIORITY)); + EXPECT_TRUE(preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_UNKNOWN)); } /** - * @tc.number : + * @tc.number : ParseFromDisturbeDB_00100 * @tc.name : - * @tc.desc : PutNotificationsEnabled_00200 + * @tc.desc : Parse store date from disturbe DB, return is true. */ -HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabled_00200, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, ParseFromDisturbeDB_00100, Function | SmallTest | Level1) { - EXPECT_EQ(true, preferncesDB_->PutNotificationsEnabled(false)); + EXPECT_TRUE(preferncesDB_->PutPrivateNotificationsAllowed(bundleName_, true)); + NotificationPreferencesInfo info; + EXPECT_TRUE(preferncesDB_->ParseFromDisturbeDB(info)); } /** + * @tc.name : RemoveAllDataFromDisturbeDB_00100 * @tc.number : - * @tc.name : - * @tc.desc : PutDisturbMode_00100 + * @tc.desc : Remove all bundle info from disturbe DB, return is true. */ -HWTEST_F(NotificationPreferencesDatabaseTest, PutDisturbMode_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, RemoveAllDataFromDisturbeDB_00100, Function | SmallTest | Level1) { - EXPECT_EQ(true, preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALARMS)); - EXPECT_EQ(true, preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALL)); - EXPECT_EQ(true, preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_NONE)); - EXPECT_EQ( - true, preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_PRIORITY)); - EXPECT_EQ( - true, preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_UNKNOWN)); + EXPECT_TRUE(preferncesDB_->RemoveAllDataFromDisturbeDB()); } /** + * @tc.name : RemoveBundleFromDisturbeDB_00100 * @tc.number : - * @tc.name : - * @tc.desc : CreateExsitBundle_00100 + * @tc.desc : Remove a bundle info from disturbe DB, return is true. */ -HWTEST_F(NotificationPreferencesDatabaseTest, CreateExsitBundle_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, RemoveBundleFromDisturbeDB_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - EXPECT_EQ(true, preferncesDB_->CheckBundle(bundleName)); + EXPECT_TRUE(preferncesDB_->PutTotalBadgeNums(bundleName_, 0)); + EXPECT_EQ(true, preferncesDB_->RemoveBundleFromDisturbeDB(bundleName_)); } /** + * @tc.name : RemoveBundleFromDisturbeDB_00200 * @tc.number : - * @tc.name : - * @tc.desc : RemoveAllBundleFromDisturbeDB_00100 + * @tc.desc : Remove a bundle info from disturbe DB when bundle name is null, return is true. */ -HWTEST_F(NotificationPreferencesDatabaseTest, RemoveAllBundleFromDisturbeDB_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, RemoveBundleFromDisturbeDB_00200, Function | SmallTest | Level1) { - EXPECT_EQ(true, preferncesDB_->RemoveAllBundleFromDisturbeDB()); + EXPECT_EQ(true, preferncesDB_->RemoveBundleFromDisturbeDB(std::string())); } /** + * @tc.name : RemoveSlotFromDisturbeDB_00100 * @tc.number : - * @tc.name : - * @tc.desc : RemoveBundleFromDisturbeDB_00100 + * @tc.desc : Remove slot from disturbe DB, return is true. */ -HWTEST_F(NotificationPreferencesDatabaseTest, RemoveBundleFromDisturbeDB_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, RemoveSlotFromDisturbeDB_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - EXPECT_EQ(true, preferncesDB_->RemoveBundleFromDisturbeDB(bundleName)); + std::vector> slots; + sptr slot1 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot1); + EXPECT_TRUE(preferncesDB_->PutSlotsToDisturbeDB(bundleName_, slots)); + + EXPECT_TRUE(preferncesDB_->RemoveSlotFromDisturbeDB( + bundleName_, OHOS::Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION)); } /** + * @tc.name : RemoveSlotFromDisturbeDB_00200 * @tc.number : - * @tc.name : - * @tc.desc : RemoveSlotFromDisturbeDB_00100 + * @tc.desc : Remove slot from disturbe DB when bundle name is null, return is false */ -HWTEST_F(NotificationPreferencesDatabaseTest, RemoveSlotFromDisturbeDB_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, RemoveSlotFromDisturbeDB_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - EXPECT_EQ(true, - preferncesDB_->RemoveSlotFromDisturbeDB( - bundleName, OHOS::Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION)); - EXPECT_EQ(true, - preferncesDB_->RemoveSlotFromDisturbeDB( - bundleName, OHOS::Notification::NotificationConstant::SlotType::SERVICE_REMINDER)); - EXPECT_EQ(true, - preferncesDB_->RemoveSlotFromDisturbeDB( - bundleName, OHOS::Notification::NotificationConstant::SlotType::CONTENT_INFORMATION)); - EXPECT_EQ(true, - preferncesDB_->RemoveSlotFromDisturbeDB(bundleName, OHOS::Notification::NotificationConstant::SlotType::OTHER)); - EXPECT_EQ(true, - preferncesDB_->RemoveSlotFromDisturbeDB( - bundleName, OHOS::Notification::NotificationConstant::SlotType::CUSTOM)); + EXPECT_FALSE(preferncesDB_->RemoveSlotFromDisturbeDB( + std::string(), OHOS::Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION)); } /** + * @tc.name : RemoveGroupsFromDisturbeDB_00100 * @tc.number : - * @tc.name : - * @tc.desc : RemoveGroupsFromDisturbeDB_00100 + * @tc.desc : Remove slot froup from disturbe DB, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, RemoveGroupsFromDisturbeDB_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; + sptr slotGroup = new NotificationSlotGroup("id", "name"); + std::vector> groups; + groups.push_back(slotGroup); + EXPECT_TRUE(preferncesDB_->PutGroupsToDisturbeDB(bundleName_, groups)); std::vector groupIds; - EXPECT_EQ(true, preferncesDB_->RemoveGroupsFromDisturbeDB(bundleName, groupIds)); + groupIds.push_back("id"); + EXPECT_TRUE(preferncesDB_->RemoveGroupsFromDisturbeDB(bundleName_, groupIds)); } /** - * @tc.number : + * @tc.number : RemoveGroupsFromDisturbeDB_00200 * @tc.name : - * @tc.desc : RemoveGroupsFromDisturbeDB_00200 + * @tc.desc : Remove slot froup from disturbe DB when bundle name is null, return is false. */ HWTEST_F(NotificationPreferencesDatabaseTest, RemoveGroupsFromDisturbeDB_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; std::vector groupIds; groupIds.push_back("group1"); groupIds.push_back("group2"); - EXPECT_EQ(true, preferncesDB_->RemoveGroupsFromDisturbeDB(bundleName, groupIds)); + EXPECT_FALSE(preferncesDB_->RemoveGroupsFromDisturbeDB(std::string(), groupIds)); } /** - * @tc.number : + * @tc.number : GetRemoveGroupKeys_00100 * @tc.name : - * @tc.desc : GetRemoveGroupKeys_00100 + * @tc.desc : Get remove group disturbe key, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, GetRemoveGroupKeys_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - std::string groupId = ""; + std::string groupId = "id"; std::vector keys; - EXPECT_EQ(true, preferncesDB_->GetRemoveGroupKeysFromDisturbeDB(bundleName, groupId, keys)); + EXPECT_TRUE(preferncesDB_->GetRemoveGroupKeysFromDisturbeDB(bundleName_, groupId, keys)); } /** + * @tc.name : StoreDeathRecipient_00100 * @tc.number : - * @tc.name : - * @tc.desc : StoreDeathRecipient_00100 + * @tc.desc : Test store when death recipient. */ HWTEST_F(NotificationPreferencesDatabaseTest, StoreDeathRecipient_00100, Function | SmallTest | Level1) { - NotificationPreferencesInfo preferencesInfo_{}; - NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - EXPECT_EQ(true, preferncesDB_->StoreDeathRecipient(preferencesInfo)); + EXPECT_TRUE(preferncesDB_->StoreDeathRecipient()); } /** + * @tc.name : GetKvStore_00100 * @tc.number : - * @tc.name : - * @tc.desc : GetKvStore_00100 + * @tc.desc : Open disturbe DB, return is SUCCESS. */ HWTEST_F(NotificationPreferencesDatabaseTest, GetKvStore_00100, Function | SmallTest | Level1) { @@ -422,87 +386,60 @@ HWTEST_F(NotificationPreferencesDatabaseTest, GetKvStore_00100, Function | Small } /** - * @tc.number : - * @tc.name : - * @tc.desc : CheckKvStore_00100 + * @tc.name : CheckKvStore_00100 + * @tc.number : + * @tc.desc : Check disturbe DB is exsit, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, CheckKvStore_00100, Function | SmallTest | Level1) { - EXPECT_EQ(true, preferncesDB_->CheckKvStore()); + EXPECT_TRUE(preferncesDB_->CheckKvStore()); } /** + * @tc.name : PutBundlePropertyValueToDisturbeDB_00100 * @tc.number : - * @tc.name : - * @tc.desc : ResetStore_00100 + * @tc.desc : Put bundle property value to disturbeDB, return is true. */ -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)); } /** - * @tc.number : + * @tc.number : ChangeSlotToEntry_00100 * @tc.name : - * @tc.desc : SetSlotEntry_00200 + * @tc.desc : Change slot to entry. */ -HWTEST_F(NotificationPreferencesDatabaseTest, SetSlotEntry_00200, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, ChangeSlotToEntry_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; sptr slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); std::vector entries; - EXPECT_EQ(true, preferncesDB_->SlotToEntry(bundleName, slot, entries)); + EXPECT_TRUE(preferncesDB_->SlotToEntry(bundleName_, slot, entries)); } /** + * @tc.name : ChangeGroupToEntry_00100 * @tc.number : - * @tc.name : - * @tc.desc : GetGroupEntry_00100 + * @tc.desc : Change slot group to entry. */ -HWTEST_F(NotificationPreferencesDatabaseTest, GetGroupEntry_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, ChangeGroupToEntry_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; sptr slotGroup = new NotificationSlotGroup("id", "name"); std::vector entries; - EXPECT_EQ(true, preferncesDB_->GroupToEntry(bundleName, slotGroup, entries)); + EXPECT_TRUE(preferncesDB_->GroupToEntry(bundleName_, slotGroup, entries)); } /** + * @tc.name : CheckBundle_00100 * @tc.number : - * @tc.name : - * @tc.desc : GetRemoveGroupKeys_00200 - */ -HWTEST_F(NotificationPreferencesDatabaseTest, GetRemoveGroupKeys_00200, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName"; - std::string groupId = "group1"; - std::vector keys; - EXPECT_EQ(true, preferncesDB_->GetRemoveGroupKeysFromDisturbeDB(bundleName, groupId, keys)); -} - -/** - * @tc.number : - * @tc.name : - * @tc.desc : ParseGroupFromDisturbeDB_00100 + * @tc.desc :Check bundle is exsit, return true when exsiting, create a bundle when does not exsit. */ -HWTEST_F(NotificationPreferencesDatabaseTest, ParseGroupFromDisturbeDB_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, CheckBundle_00100, Function | SmallTest | Level1) { - NotificationPreferencesInfo::BundleInfo bundleInfo; - bundleInfo.SetBundleName("BundleName"); - // preferncesDB_->ParseGroupFromDisturbeDB(bundleInfo, std::string()); // TODO Q - EXPECT_EQ("BundleName", bundleInfo.GetBundleName()); + EXPECT_EQ(true, preferncesDB_->CheckBundle(bundleName_)); } } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/ans/test/unittest/notification_preferences_test.cpp b/services/ans/test/unittest/notification_preferences_test.cpp index 5c3e5b45da69d743ddc94a58d92e6028d71e2479..79f4069800385a32e53f203b0a48932bb071865d 100644 --- a/services/ans/test/unittest/notification_preferences_test.cpp +++ b/services/ans/test/unittest/notification_preferences_test.cpp @@ -15,8 +15,9 @@ #include -#include "notification_preferences.h" #include "ans_inner_errors.h" +#include "ans_ut_constant.h" +#include "notification_preferences.h" using namespace testing::ext; namespace OHOS { @@ -24,584 +25,1040 @@ namespace Notification { class NotificationPreferencesTest : public testing::Test { public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); + static void SetUpTestCase(){}; + static void TearDownTestCase(){}; + void SetUp(){}; void TearDown(); -}; -void NotificationPreferencesTest::SetUpTestCase() -{} + void TestAddNotificationSlot(); + void TestAddNotificationSlotGroup(); -void NotificationPreferencesTest::TearDownTestCase() -{} + static sptr bundleOption_; + static sptr noExsitbundleOption_; + static sptr bundleEmptyOption_; +}; -void NotificationPreferencesTest::SetUp() -{} +sptr NotificationPreferencesTest::bundleOption_ = + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); +sptr NotificationPreferencesTest::noExsitbundleOption_ = + new NotificationBundleOption(std::string("notExsitBundleName"), NON_SYSTEM_APP_UID); +sptr NotificationPreferencesTest::bundleEmptyOption_ = + new NotificationBundleOption(std::string(), NON_SYSTEM_APP_UID); void NotificationPreferencesTest::TearDown() { NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); } -void TestAddNotificationSlot() +void NotificationPreferencesTest::TestAddNotificationSlot() { - std::string bundleName = "bundleName"; - sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); - std::vector> spSlots; - spSlots.push_back(spSlot); - NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + std::vector> slots; + slots.push_back(slot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption_, slots); } -void TestAddNotificationSlotGroup() +void NotificationPreferencesTest::TestAddNotificationSlotGroup() { - std::string bundleName = "bundleName"; - sptr spGroup = new NotificationSlotGroup("id", "name"); + sptr group = new NotificationSlotGroup("id", "name"); std::vector> groups; - groups.push_back(spGroup); - NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, groups); + groups.push_back(group); + NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleOption_, groups); } /** - * @tc.number : - * @tc.name : - * @tc.desc : AddNotificationSlots_00100 + * @tc.number : AddNotificationSlots_00100 + * @tc.name : + * @tc.desc : Add a notification slot into distrube DB , return is ERR_OK. */ HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); std::vector> slots; slots.push_back(slot); - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption_, slots), (int)ERR_OK); } /** - * @tc.number : - * @tc.name : - * @tc.desc : AddNotificationSlots_00200 + * @tc.number : AddNotificationSlots_00200 + * @tc.name : + * @tc.desc : Add a notification slot into distrube DB when bundleName is null, return is ERR_ANS_INVALID_PARAM. */ HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00200, Function | SmallTest | Level1) { sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); std::vector> slots; slots.push_back(slot); - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(std::string(), slots), (int)ERR_ANS_INVALID_PARAM); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleEmptyOption_, slots), + (int)ERR_ANS_INVALID_PARAM); } /** - * @tc.number : - * @tc.name : - * @tc.desc : AddNotificationSlots_00300 + * @tc.number : AddNotificationSlots_00300 + * @tc.name : + * @tc.desc : Add a notification slot into distrube DB when slots is null, return is ERR_ANS_INVALID_PARAM. */ HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00300, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; std::vector> slots; - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots), (int)ERR_ANS_INVALID_PARAM); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption_, slots), + (int)ERR_ANS_INVALID_PARAM); } /** - * @tc.number : - * @tc.name : - * @tc.desc : AddNotificationSlots_00400 + * @tc.number : AddNotificationSlots_00400 + * @tc.name : + * @tc.desc : Add a notification slot into distrube DB when slot is nullptr in vector, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST. */ HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00400, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; sptr slot = nullptr; std::vector> slots; slots.push_back(slot); - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots), (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption_, slots), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST); } /** - * @tc.number : - * @tc.name : - * @tc.desc : AddNotificationSlots_00500 + * @tc.number : AddNotificationSlots_00500 + * @tc.name : + * @tc.desc : Add a notification slot into distrube DB when slots is same, return is ERR_OK. */ HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00500, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; sptr slot1 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr slot2 = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); - sptr slot3 = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); - sptr slot4 = new NotificationSlot(NotificationConstant::SlotType::OTHER); - sptr slot5 = new NotificationSlot(NotificationConstant::SlotType::CUSTOM); + sptr slot2 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); std::vector> slots; slots.push_back(slot1); slots.push_back(slot2); - slots.push_back(slot3); - slots.push_back(slot4); - slots.push_back(slot5); - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots), (int)ERR_OK); - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots), (int)ERR_OK); + + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption_, slots), (int)ERR_OK); } /** - * @tc.number : - * @tc.name : - * @tc.desc : AddNotificationSlots_00600 + * @tc.number : AddNotificationSlotGroups_00100 + * @tc.name : + * @tc.desc : Add a notification groups into disturbe DB , return is ERR_OK */ -HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00600, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, AddNotificationSlotGroups_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; + sptr group = new NotificationSlotGroup("id", "name"); + std::vector> groups; + groups.push_back(group); + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleOption_, groups), (int)ERR_OK); +} - sptr slot1 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr slot2 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); +/** + * @tc.number : AddNotificationSlotGroups_00200 + * @tc.name : + * @tc.desc : Add a notification groups into disturbe DB when bundle name is null, return is ERR_ANS_INVALID_PARAM. + */ +HWTEST_F(NotificationPreferencesTest, AddNotificationSlotGroups_00200, Function | SmallTest | Level1) +{ + sptr group = new NotificationSlotGroup("id", "name"); + std::vector> groups; + groups.push_back(group); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleEmptyOption_, groups), + (int)ERR_ANS_INVALID_PARAM); +} - std::vector> slots; - slots.push_back(slot1); - slots.push_back(slot2); +/** + * @tc.number : AddNotificationSlotGroups_00300 + * @tc.name : + * @tc.desc : Add a notification groups into disturbe DB when groups is null, return is ERR_ANS_INVALID_PARAM. + */ +HWTEST_F(NotificationPreferencesTest, AddNotificationSlotGroups_00300, Function | SmallTest | Level1) +{ + std::vector> groups; + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleOption_, groups), + (int)ERR_ANS_INVALID_PARAM); +} - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots), (int)ERR_OK); +/** + * @tc.number : AddNotificationSlotGroups_00400 + * @tc.name : + * @tc.desc : Add a notification groups into disturbe DB when group id is null, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID + */ +HWTEST_F(NotificationPreferencesTest, AddNotificationSlotGroups_00400, Function | SmallTest | Level1) +{ + sptr group = new NotificationSlotGroup("", "name"); + std::vector> groups; + groups.push_back(group); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleOption_, groups), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID); } +/** + * @tc.number : AddNotificationSlotGroups_00500 + * @tc.name : + * @tc.desc : Add a notification groups into disturbe DB when add group exceed max num, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM + */ +HWTEST_F(NotificationPreferencesTest, AddNotificationSlotGroups_00500, Function | SmallTest | Level1) +{ + sptr group1 = new NotificationSlotGroup("id1", "name1"); + sptr group2 = new NotificationSlotGroup("id2", "name1"); + sptr group3 = new NotificationSlotGroup("id3", "name1"); + sptr group4 = new NotificationSlotGroup("id4", "name1"); + sptr group5 = new NotificationSlotGroup("id5", "name1"); + std::vector> groups; + groups.push_back(group1); + groups.push_back(group2); + groups.push_back(group3); + groups.push_back(group4); + groups.push_back(group5); + + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleOption_, groups), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM); +} /** - * @tc.number : NotificationPreferencesTest_01700 - * @tc.name : AMS_ANS_GetNotificationAllSlots_0100 - * @tc.desc : Test GetNotificationAllSlots function + * @tc.number : RemoveNotificationSlot_00100 + * @tc.name : + * @tc.desc : Remove a notification slot from disturbe DB , return is ERR_OK */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01700, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, RemoveNotificationSlot_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); - std::vector> spSlots; - spSlots.push_back(spSlot); - NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); - std::vector> slotsResult; - EXPECT_EQ( - (int)NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleName, slotsResult), (int)ERR_OK); - EXPECT_EQ((int)slotsResult.size(), 5); + TestAddNotificationSlot(); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlot( + bundleOption_, NotificationConstant::SlotType::OTHER), + (int)ERR_OK); } /** - * @tc.number : NotificationPreferencesTest_01800 - * @tc.name : AMS_ANS_GetNotificationSlotGroup_0100 - * @tc.desc : Test GetNotificationSlotGroup function + * @tc.number : RemoveNotificationSlot_00200 + * @tc.name : + * @tc.desc : Remove a notification slot from disturbe DB when bundle name is null, return is ERR_OK */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01800, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, RemoveNotificationSlot_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - sptr spGroup = new NotificationSlotGroup("id", "name"); - spGroup->SetDescription("Description"); - std::vector> groups; - groups.push_back(spGroup); - NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, groups); - sptr groupResult; + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlot( + bundleEmptyOption_, NotificationConstant::SlotType::OTHER), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : RemoveNotificationSlot_00300 + * @tc.name : + * @tc.desc : Remove a notification slot from disturbe DB when bundle name does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST + */ +HWTEST_F(NotificationPreferencesTest, RemoveNotificationSlot_00300, Function | SmallTest | Level1) +{ + TestAddNotificationSlot(); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlot( + noExsitbundleOption_, NotificationConstant::SlotType::OTHER), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : RemoveNotificationSlot_00400 + * @tc.name : + * @tc.desc : Remove a notification slot from disturbe DB when slot type does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST + */ +HWTEST_F(NotificationPreferencesTest, RemoveNotificationSlot_00400, Function | SmallTest | Level1) +{ + TestAddNotificationSlot(); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlot( + bundleOption_, NotificationConstant::SlotType::SERVICE_REMINDER), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST); +} + +/** + * @tc.number : RemoveNotificationSlotGroups_00100 + * @tc.name : + * @tc.desc : Remove a notification group from disturbe DB , return is ERR_OK + */ +HWTEST_F(NotificationPreferencesTest, RemoveNotificationSlotGroups_00100, Function | SmallTest | Level1) +{ + TestAddNotificationSlotGroup(); + std::string groupId = "id"; + std::vector groupIds; + groupIds.push_back(groupId); EXPECT_EQ( - (int)NotificationPreferences::GetInstance().GetNotificationSlotGroup(bundleName, spGroup->GetId(), groupResult), - (int)ERR_OK); - EXPECT_EQ(groupResult->GetDescription(), spGroup->GetDescription()); + (int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleOption_, groupIds), (int)ERR_OK); +} + +/** + * @tc.number : RemoveNotificationSlotGroups_00200 + * @tc.name : + * @tc.desc : Remove a notification group from disturbe DB when bundleName is null, return is ERR_ANS_INVALID_PARAM + */ +HWTEST_F(NotificationPreferencesTest, RemoveNotificationSlotGroups_00200, Function | SmallTest | Level1) +{ + TestAddNotificationSlotGroup(); + std::string groupId("id"); + std::vector groupIds; + groupIds.push_back(groupId); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleEmptyOption_, groupIds), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : RemoveNotificationSlotGroups_00300 + * @tc.name : + * @tc.desc : Remove a notification group from disturbe DB when group id is null, return is ERR_ANS_INVALID_PARAM + */ +HWTEST_F(NotificationPreferencesTest, RemoveNotificationSlotGroups_00300, Function | SmallTest | Level1) +{ + TestAddNotificationSlotGroup(); + std::vector groupIds; + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleOption_, groupIds), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : RemoveNotificationSlotGroups_00400 + * @tc.name : + * @tc.desc : Remove a notification group from disturbe DB when bundle name does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST + */ +HWTEST_F(NotificationPreferencesTest, RemoveNotificationSlotGroups_00400, Function | SmallTest | Level1) +{ + TestAddNotificationSlotGroup(); + std::vector groupIds; + groupIds.push_back("id"); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(noExsitbundleOption_, groupIds), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); } /** - * @tc.number : NotificationPreferencesTest_01900 - * @tc.name : AMS_ANS_GetNotificationAllSlotGroups_0100 - * @tc.desc : Test GetNotificationAllSlotGroups function + * @tc.number : RemoveNotificationSlotGroups_00500 + * @tc.name : + * @tc.desc : Remove a notification group from disturbe DB when group id does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01900, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, RemoveNotificationSlotGroups_00500, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; TestAddNotificationSlotGroup(); + std::string groupId = "id1"; + std::vector groupIds; + groupIds.push_back(groupId); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleOption_, groupIds), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID); +} +/** + * @tc.number : RemoveNotificationForBundle_00100 + * @tc.name : + * @tc.desc : Remove notification for bundle from disturbe DB, return is ERR_OK; + */ +HWTEST_F(NotificationPreferencesTest, RemoveNotificationForBundle_00100, Function | SmallTest | Level1) +{ + TestAddNotificationSlot(); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleOption_), (int)ERR_OK); +} + +/** + * @tc.number : RemoveNotificationForBundle_00200 + * @tc.name : + * @tc.desc : Remove notification for bundle from disturbe DB when bundle name is null, return is + * ERR_ANS_INVALID_PARAM; + */ +HWTEST_F(NotificationPreferencesTest, RemoveNotificationForBundle_00200, Function | SmallTest | Level1) +{ + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleEmptyOption_), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : RemoveNotificationForBundle_00300 + * @tc.name : + * @tc.desc : Remove notification for bundle from disturbe DB when bundle name is null, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + */ +HWTEST_F(NotificationPreferencesTest, RemoveNotificationForBundle_00300, Function | SmallTest | Level1) +{ + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationForBundle(noExsitbundleOption_), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : UpdateNotificationSlots_00100 + * @tc.name : + * @tc.desc : Update notification slot into disturbe DB, return is ERR_OK + */ +HWTEST_F(NotificationPreferencesTest, UpdateNotificationSlots_00100, Function | SmallTest | Level1) +{ + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + std::vector> slots; + slots.push_back(slot); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption_, slots), (int)ERR_OK); + std::string des("This is a description."); + slot->SetDescription(des); + slots.clear(); + slots.push_back(slot); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleOption_, slots), (int)ERR_OK); +} + +/** + * @tc.number : UpdateNotificationSlots_00200 + * @tc.name : + * @tc.desc : Update notification slot into disturbe DB when bundleName is null, return is ERR_ANS_INVALID_PARAM + */ +HWTEST_F(NotificationPreferencesTest, UpdateNotificationSlots_00200, Function | SmallTest | Level1) +{ + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + std::vector> slots; + slots.push_back(slot); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleEmptyOption_, slots), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : UpdateNotificationSlots_00300 + * @tc.name : + * @tc.desc : Update notification slot into disturbe DB when slots is null, return is ERR_ANS_INVALID_PARAM + */ +HWTEST_F(NotificationPreferencesTest, UpdateNotificationSlots_00300, Function | SmallTest | Level1) +{ + std::vector> slots; + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleOption_, slots), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : UpdateNotificationSlots_00400 + * @tc.name : + * @tc.desc : Update notification slot into disturbe DB when bundle does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST + */ +HWTEST_F(NotificationPreferencesTest, UpdateNotificationSlots_00400, Function | SmallTest | Level1) +{ + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + std::vector> slots; + slots.push_back(slot); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(noExsitbundleOption_, slots), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : UpdateNotificationSlots_00500 + * @tc.name : + * @tc.desc : Update notification slot into disturbe DB when slot type does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST + */ +HWTEST_F(NotificationPreferencesTest, UpdateNotificationSlots_00500, Function | SmallTest | Level1) +{ + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + std::vector> slots; + slots.push_back(slot); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(noExsitbundleOption_, slots), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : UpdateNotificationSlotGroups_00100 + * @tc.name : + * @tc.desc : Update notification slot group into disturbe DB return is ERR_OK. + */ +HWTEST_F(NotificationPreferencesTest, UpdateNotificationSlotGroups_00100, Function | SmallTest | Level1) +{ + sptr group = new NotificationSlotGroup("id", "name"); std::vector> groups; + groups.push_back(group); EXPECT_EQ( - (int)NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundleName, groups), (int)ERR_OK); - EXPECT_EQ((int)groups.size(), 3); + (int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleOption_, groups), (int)ERR_OK); + std::string des("This is a group description."); + group->SetDescription(des); + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleOption_, groups), (int)ERR_OK); } /** - * @tc.number : NotificationPreferencesTest_02000 - * @tc.name : AMS_ANS_GetNotificationAllSlotInSlotGroup_0100 - * @tc.desc : Test GetNotificationAllSlotInSlotGroup function + * @tc.number : UpdateNotificationSlotGroups_00200 + * @tc.name : + * @tc.desc : Update notification slot group into disturbe DB when bundle name is null, return is + * ERR_ANS_INVALID_PARAM. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02000, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, UpdateNotificationSlotGroups_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - std::string groupId = "groupId"; - sptr spGroup = new NotificationSlotGroup("groupId", "name"); + sptr group = new NotificationSlotGroup("id", "name"); std::vector> groups; - groups.push_back(spGroup); - NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, groups); - sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); - spSlot->SetSlotGroup(groupId); - std::vector> spSlots; - spSlots.push_back(spSlot); - NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); - std::vector> slotsReuslt; - EXPECT_EQ( - (int)NotificationPreferences::GetInstance().GetNotificationAllSlotInSlotGroup(bundleName, groupId, slotsReuslt), - (int)ERR_OK); - EXPECT_EQ((int)slotsReuslt.size(), 1); + groups.push_back(group); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleEmptyOption_, groups), + (int)ERR_ANS_INVALID_PARAM); } /** - * @tc.number : NotificationPreferencesTest_02100 - * @tc.name : AMS_ANS_IsShowBadge_0100 - * @tc.desc : Test IsShowBadge function + * @tc.number : UpdateNotificationSlotGroups_00300 + * @tc.name : + * @tc.desc : Update notification slot group into disturbe DB when groups is null, return is ERR_ANS_INVALID_PARAM. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, UpdateNotificationSlotGroups_00300, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - bool enable; - TestAddNotificationSlot(); - NotificationPreferences::GetInstance().SetShowBadge(bundleName, true); - EXPECT_EQ((int)NotificationPreferences::GetInstance().IsShowBadge(bundleName, enable), (int)ERR_OK); - EXPECT_TRUE(enable); + std::vector> groups; + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleOption_, groups), + (int)ERR_ANS_INVALID_PARAM); } /** - * @tc.number : NotificationPreferencesTest_02200 - * @tc.name : AMS_ANS_SetShowBadge_0100 - * @tc.desc : Test SetShowBadge function + * @tc.number : UpdateNotificationSlotGroups_00400 + * @tc.name : + * @tc.desc : Update notification slot group into disturbe DB when bundle does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02200, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, UpdateNotificationSlotGroups_00400, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - TestAddNotificationSlot(); - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetShowBadge(bundleName, false), (int)ERR_OK); + sptr group = new NotificationSlotGroup("id", "name"); + std::vector> groups; + groups.push_back(group); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(noExsitbundleOption_, groups), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); } /** - * @tc.number : NotificationPreferencesTest_02400 - * @tc.name : AMS_ANS_IsShowBadge_0200 - * @tc.desc : Test IsShowBadge function when the parameter is wrong + * @tc.number : UpdateNotificationSlotGroups_00500 + * @tc.name : + * @tc.desc : Update notification slot group into disturbe DB when groupid is null, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02400, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, UpdateNotificationSlotGroups_00500, Function | SmallTest | Level1) { - std::string bundleName = ""; - bool enable; - EXPECT_EQ((int)NotificationPreferences::GetInstance().IsShowBadge(bundleName, enable), (int)ERR_ANS_INVALID_PARAM); + TestAddNotificationSlotGroup(); + sptr spGroup = new NotificationSlotGroup("", "name"); + std::vector> groups; + groups.push_back(spGroup); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleOption_, groups), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST); } /** - * @tc.number : NotificationPreferencesTest_02600 - * @tc.name : AMS_ANS_GetImportance_0200 - * @tc.desc : Test GetImportance function + * @tc.number : GetNotificationSlot_00100 + * @tc.name : + * @tc.desc : Update notification slot group into disturbe DB, return is ERR_OK */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02600, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationSlot_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; TestAddNotificationSlot(); - const int importance = 1; - NotificationPreferences::GetInstance().SetImportance(bundleName, importance); - int importanceResult; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetImportance(bundleName, importanceResult), (int)ERR_OK); - EXPECT_EQ(importanceResult, importance); + sptr slot; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationSlot( + bundleOption_, NotificationConstant::SlotType::OTHER, slot), + (int)ERR_OK); } /** - * @tc.number : NotificationPreferencesTest_02700 - * @tc.name : AMS_ANS_GetTotalBadgeNums_0100 - * @tc.desc : Test GetTotalBadgeNums function + * @tc.number : GetNotificationSlot_00200 + * @tc.name : + * @tc.desc : Update notification slot group into disturbe DB when bundle name is null, return is + * ERR_ANS_INVALID_PARAM */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02700, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationSlot_00200, Function | SmallTest | Level1) +{ + sptr slot; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationSlot( + bundleEmptyOption_, NotificationConstant::SlotType::OTHER, slot), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : GetNotificationSlot_00300 + * @tc.name : + * @tc.desc : Update notification slot group into disturbe DB when slot type does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST + */ +HWTEST_F(NotificationPreferencesTest, GetNotificationSlot_00300, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - int num = 1; TestAddNotificationSlot(); - NotificationPreferences::GetInstance().SetTotalBadgeNums(bundleName, num); - int totalBadgeNum; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetTotalBadgeNums(bundleName, totalBadgeNum), (int)ERR_OK); - EXPECT_EQ(totalBadgeNum, num); + sptr slot; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationSlot( + bundleOption_, NotificationConstant::SlotType::CONTENT_INFORMATION, slot), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST); } /** - * @tc.number : NotificationPreferencesTest_02800 - * @tc.name : AMS_ANS_GetPrivateNotificationsAllowed_0100 - * @tc.desc : Test GetPrivateNotificationsAllowed function + * @tc.number : GetNotificationSlot_00400 + * @tc.name : + * @tc.desc : Update notification slot group into disturbe DB when bundle name does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02800, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationSlot_00400, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; TestAddNotificationSlot(); - NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundleName, true); - bool allow; - NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleName, allow); - EXPECT_EQ(allow, true); + sptr slot; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationSlot( + noExsitbundleOption_, NotificationConstant::SlotType::OTHER, slot), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); } /** - * @tc.number : NotificationPreferencesTest_02900 - * @tc.name : AMS_ANS_GetNotificationsEnabledForBundle_0100 - * @tc.desc : Test GetNotificationsEnabledForBundle function + * @tc.number : GetNotificationAllSlots_00100 + * @tc.name : + * @tc.desc : Get all notification slots from disturbe DB after add a notification slot, return is ERR_OK, get all + * notifications size is 1. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02900, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlots_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; TestAddNotificationSlot(); - NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleName, false); - bool enabled; - NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleName, enabled); - EXPECT_FALSE(enabled); + std::vector> slotsResult; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleOption_, slotsResult), (int)ERR_OK); + EXPECT_EQ((int)slotsResult.size(), 1); } /** - * @tc.number : NotificationPreferencesTest_03100 - * @tc.name : AMS_ANS_RemoveNotificationForBundle_0100 - * @tc.desc : Test RemoveNotificationForBundle function when bundleName is not set + * @tc.number : GetNotificationAllSlots_00200 + * @tc.name : + * @tc.desc : Get all notification slots from disturbe DB after add some notification slot, return is ERR_OK, get + * all notifications size is the same of adding notifications size. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlots_00200, Function | SmallTest | Level1) { - std::string bundleName = ""; - EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleName), + sptr slot1 = new NotificationSlot(NotificationConstant::SlotType::OTHER); + sptr slot2 = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::vector> slots; + slots.push_back(slot1); + slots.push_back(slot2); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption_, slots); + + std::vector> slotsResult; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleOption_, slotsResult), (int)ERR_OK); + EXPECT_EQ((int)slotsResult.size(), 2); +} + +/** + * @tc.number : GetNotificationAllSlots_00300 + * @tc.name : + * @tc.desc : Get all notification slots from disturbe DB when bundle name is null, return is + * ERR_ANS_INVALID_PARAM + */ +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlots_00300, Function | SmallTest | Level1) +{ + std::vector> slotsResult; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleEmptyOption_, slotsResult), (int)ERR_ANS_INVALID_PARAM); + EXPECT_EQ((int)slotsResult.size(), 0); } /** - * @tc.number : NotificationPreferencesTest_03300 - * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0200 - * @tc.desc : Test RemoveNotificationSlotGroups function + * @tc.number : GetNotificationAllSlots_00400 + * @tc.name : + * @tc.desc : Get all notification slots from disturbe DB when bundle name does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03300, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlots_00400, Function | SmallTest | Level1) +{ + std::vector> slotsResult; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationAllSlots(noExsitbundleOption_, slotsResult), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + EXPECT_EQ((int)slotsResult.size(), 0); +} + +/** + * @tc.number : GetNotificationAllSlotGroups_00100 + * @tc.name : + * @tc.desc : Get all notification slots from disturbe DB, return is ERR_OK. + */ +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlotGroups_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; TestAddNotificationSlotGroup(); - std::string groupId = "id"; - std::vector groupIds; - groupIds.push_back(groupId); + std::vector> groups; EXPECT_EQ( - (int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), (int)ERR_OK); + (int)NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundleOption_, groups), (int)ERR_OK); + EXPECT_EQ((int)groups.size(), 1); } /** - * @tc.number : NotificationPreferencesTest_03400 - * @tc.name : AMS_ANS_UpdateNotificationSlots_0200 - * @tc.desc : Test UpdateNotificationSlots function when bundleName not exist + * @tc.number : GetNotificationAllSlotGroups_00200 + * @tc.name : + * @tc.desc : Get all notification slots from disturbe DB when bundle name is null, return is + * ERR_ANS_INVALID_PARAM */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03400, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlotGroups_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName1"; - TestAddNotificationSlot(); - sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); - std::vector> spSlots; - spSlots.push_back(spSlot); - EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleName, spSlots), + std::vector> groups; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundleEmptyOption_, groups), + (int)ERR_ANS_INVALID_PARAM); + EXPECT_EQ((int)groups.size(), 0); +} + +/** + * @tc.number : GetNotificationAllSlotGroups_00300 + * @tc.name : + * @tc.desc : Get all notification slots from disturbe DB when bundle name does not exsit, return is + * ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST + */ +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlotGroups_00300, Function | SmallTest | Level1) +{ + std::vector> groups; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(noExsitbundleOption_, groups), (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + EXPECT_EQ((int)groups.size(), 0); } /** - * @tc.number : NotificationPreferencesTest_03500 - * @tc.name : AMS_ANS_GetNotificationSlot_0200 - * @tc.desc : Test UpdateNotificationSlots function + * @tc.number : GetNotificationAllSlotInSlotGroup_00100 + * @tc.name : + * @tc.desc : Get all notification slots in the same group from disturbe DB , return is ERR_OK. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03500, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlotInSlotGroup_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - TestAddNotificationSlot(); - sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); - spSlot->SetLevel(NotificationSlot::NotificationLevel::LEVEL_HIGH); - std::vector> spSlots; - spSlots.push_back(spSlot); - EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleName, spSlots), (int)ERR_OK); - sptr updateSpSlot; - NotificationPreferences::GetInstance().GetNotificationSlot(bundleName, NotificationConstant::OTHER, updateSpSlot); - EXPECT_EQ(updateSpSlot->GetLevel(), spSlot->GetLevel()); + std::string groupId = "groupId"; + sptr group = new NotificationSlotGroup("groupId", "name"); + std::vector> groups; + groups.push_back(group); + NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleOption_, groups); + + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slot->SetSlotGroup(groupId); + std::vector> slots; + slots.push_back(slot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption_, slots); + std::vector> slotsReuslt; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationAllSlotInSlotGroup( + bundleOption_, groupId, slotsReuslt), + (int)ERR_OK); + EXPECT_EQ((int)slotsReuslt.size(), 1); } /** - * @tc.number : NotificationPreferencesTest_03600 - * @tc.name : AMS_ANS_UpdateNotificationSlots_0300 - * @tc.desc : Test UpdateNotificationSlots function when the parameter is wrong + * @tc.number : GetNotificationAllSlotInSlotGroup_00200 + * @tc.name : + * @tc.desc : Get all notification slots in the same group from disturbe DB when bundle name is null, return is + * ERR_ANS_INVALID_PARAM. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03600, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlotInSlotGroup_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - TestAddNotificationSlot(); - std::vector> spSlots; - EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleName, spSlots), + std::string groupId = "groupId"; + std::vector> slotsReuslt; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationAllSlotInSlotGroup( + bundleEmptyOption_, groupId, slotsReuslt), (int)ERR_ANS_INVALID_PARAM); + EXPECT_EQ((int)slotsReuslt.size(), 0); } /** - * @tc.number : NotificationPreferencesTest_03700 - * @tc.name : AMS_ANS_UpdateNotificationSlotGroups_0300 - * @tc.desc : Test UpdateNotificationSlotGroups function when groupid invalid + * @tc.number : GetNotificationAllSlotInSlotGroup_00300 + * @tc.name : + * @tc.desc : Get all notification slots in the same group from disturbe DB when group id is null, return is + * ERR_ANS_INVALID_PARAM. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03700, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlotInSlotGroup_00300, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - TestAddNotificationSlotGroup(); - sptr spGroup = new NotificationSlotGroup("", "name"); - std::vector> groups; - groups.push_back(spGroup); - EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleName, groups), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST); + std::vector> slotsReuslt; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().GetNotificationAllSlotInSlotGroup(bundleOption_, "", slotsReuslt), + (int)ERR_ANS_INVALID_PARAM); + EXPECT_EQ((int)slotsReuslt.size(), 0); } /** - * @tc.number : NotificationPreferencesTest_03800 - * @tc.name : AMS_ANS_SetImportance_0200 - * @tc.desc : Test SetImportance function when the parameter is wrong + * @tc.number : GetNotificationAllSlotInSlotGroup_00400 + * @tc.name : + * @tc.desc : Get all notification slots in the same group from disturbe DB when bundle name does not exsit, return + * is ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03800, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetNotificationAllSlotInSlotGroup_00400, Function | SmallTest | Level1) +{ + std::string groupId = "groupId"; + std::vector> slotsReuslt; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationAllSlotInSlotGroup( + noExsitbundleOption_, groupId, slotsReuslt), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + EXPECT_EQ((int)slotsReuslt.size(), 0); +} + +/** + * @tc.number : SetShowBadge_00100 + * @tc.name : + * @tc.desc : Set bundle show badge into disturbe DB, return is ERR_OK. + */ +HWTEST_F(NotificationPreferencesTest, SetShowBadge_00100, Function | SmallTest | Level1) +{ + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetShowBadge(bundleOption_, true), (int)ERR_OK); +} + +/** + * @tc.number : SetShowBadge_00200 + * @tc.name : + * @tc.desc : Set bundle show badge into disturbe DB when bundle name is null, return is ERR_ANS_INVALID_PARAM. + */ +HWTEST_F(NotificationPreferencesTest, SetShowBadge_00200, Function | SmallTest | Level1) { - std::string bundleName = ""; - int importance = 1; EXPECT_EQ( - (int)NotificationPreferences::GetInstance().SetImportance(bundleName, importance), (int)ERR_ANS_INVALID_PARAM); + (int)NotificationPreferences::GetInstance().SetShowBadge(bundleEmptyOption_, true), (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : IsShowBadge_00100 + * @tc.name : + * @tc.desc : Get bunlde show badge from disturbe DB , return is ERR_OK and show badge is true. + */ +HWTEST_F(NotificationPreferencesTest, IsShowBadge_00100, Function | SmallTest | Level1) +{ + bool enable = false; + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetShowBadge(bundleOption_, true), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().IsShowBadge(bundleOption_, enable), (int)ERR_OK); + EXPECT_TRUE(enable); } /** - * @tc.number : NotificationPreferencesTest_03900 - * @tc.name : AMS_ANS_SetImportance_0300 - * @tc.desc : Test SetImportance function + * @tc.number : IsShowBadge_00200 + * @tc.name : + * @tc.desc : Get bunlde show badge from disturbe DB when bundle name is null, return is ERR_OK and show badge is + * true. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03900, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, IsShowBadge_00200, Function | SmallTest | Level1) +{ + bool enable = false; + EXPECT_EQ((int)NotificationPreferences::GetInstance().IsShowBadge(bundleEmptyOption_, enable), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : SetImportance_00100 + * @tc.name : + * @tc.desc : Set bundle importance into disturbe DB, return is ERR_OK. + */ +HWTEST_F(NotificationPreferencesTest, SetImportance_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; int importance = 1; - TestAddNotificationSlot(); - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetImportance(bundleName, importance), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetImportance(bundleOption_, importance), (int)ERR_OK); } /** - * @tc.number : NotificationPreferencesTest_04000 - * @tc.name : AMS_ANS_GetImportance_0300 - * @tc.desc : Test GetImportance function when file is null + * @tc.number : SetImportance_00200 + * @tc.name : + * @tc.desc : Set bundle importance into disturbe DB when bundle name is null, return is ERR_ANS_INVALID_PARAM. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04000, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, SetImportance_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - int importanceResult; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetImportance(bundleName, importanceResult), - (int)ERR_OK); + int importance = 1; + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetImportance(bundleEmptyOption_, importance), + (int)ERR_ANS_INVALID_PARAM); } /** - * @tc.number : NotificationPreferencesTest_04100 - * @tc.name : AMS_ANS_SetTotalBadgeNums_0200 - * @tc.desc : Test SetTotalBadgeNums function when the parameter is wrong + * @tc.number : GetImportance_00100 + * @tc.name : + * @tc.desc : Get bundle importance from disturbe DB, return is ERR_OK. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetImportance_00100, Function | SmallTest | Level1) +{ + int importance = 1; + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetImportance(bundleOption_, importance), (int)ERR_OK); + int getImportance; + + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetImportance(bundleOption_, getImportance), (int)ERR_OK); + EXPECT_EQ(getImportance, 1); +} + +/** + * @tc.number : GetImportance_00200 + * @tc.name : + * @tc.desc : Get bundle importance from disturbe DB when bundle name is null, return is ERR_ANS_INVALID_PARAM. + */ +HWTEST_F(NotificationPreferencesTest, GetImportance_00200, Function | SmallTest | Level1) +{ + int getImportance; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetImportance(bundleEmptyOption_, getImportance), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : SetTotalBadgeNums_00100 + * @tc.name : + * @tc.desc : Set total badge nums into disturbe DB, return is ERR_OK. + */ +HWTEST_F(NotificationPreferencesTest, SetTotalBadgeNums_00100, Function | SmallTest | Level1) { - std::string bundleName = ""; int num = 1; - EXPECT_EQ( - (int)NotificationPreferences::GetInstance().SetTotalBadgeNums(bundleName, num), (int)ERR_ANS_INVALID_PARAM); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetTotalBadgeNums(bundleOption_, num), (int)ERR_OK); +} + +/** + * @tc.number : SetTotalBadgeNums_00200 + * @tc.name : + * @tc.desc : Set total badge nums into disturbe DB when bundle name is null, return is ERR_ANS_INVALID_PARAM. + */ +HWTEST_F(NotificationPreferencesTest, SetTotalBadgeNums_00200, Function | SmallTest | Level1) +{ + int num = 1; + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetTotalBadgeNums(bundleEmptyOption_, num), + (int)ERR_ANS_INVALID_PARAM); } /** - * @tc.number : NotificationPreferencesTest_04200 - * @tc.name : AMS_ANS_GetTotalBadgeNums_0300 - * @tc.desc : Test GetTotalBadgeNums function when file is null + * @tc.number : GetTotalBadgeNums_00100 + * @tc.name : + * @tc.desc : Get total badge nums from disturbe DB, return is ERR_OK. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04200, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetTotalBadgeNums_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; + int num = 1; + NotificationPreferences::GetInstance().SetTotalBadgeNums(bundleOption_, num); int totalBadgeNum; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetTotalBadgeNums(bundleName, totalBadgeNum), - 0); + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetTotalBadgeNums(bundleOption_, totalBadgeNum), (int)ERR_OK); + EXPECT_EQ(totalBadgeNum, num); } /** - * @tc.number : NotificationPreferencesTest_04300 - * @tc.name : AMS_ANS_SetPrivateNotificationsAllowed_0200 - * @tc.desc : Test SetPrivateNotificationsAllowed function when the parameter is wrong + * @tc.number : GetTotalBadgeNums_00200 + * @tc.name : + * @tc.desc : Get total badge nums from disturbe DB when bundle name is null, return is ERR_ANS_INVALID_PARAM. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04300, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetTotalBadgeNums_00200, Function | SmallTest | Level1) { - std::string bundleName = ""; - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundleName, false), + int totalBadgeNum; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetTotalBadgeNums(bundleEmptyOption_, totalBadgeNum), (int)ERR_ANS_INVALID_PARAM); } /** - * @tc.number : NotificationPreferencesTest_04400 - * @tc.name : AMS_ANS_GetPrivateNotificationsAllowed_0200 - * @tc.desc : Test GetPrivateNotificationsAllowed function when file is null + * @tc.number : SetPrivateNotificationsAllowed_00100 + * @tc.name : + * @tc.desc : Set private notification allowed badge nums into disturbe DB , return is ERR_OK. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04400, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, SetPrivateNotificationsAllowed_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - bool allow; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleName, allow),0); + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundleOption_, true), (int)ERR_OK); } /** - * @tc.number : NotificationPreferencesTest_04500 - * @tc.name : AMS_ANS_SetNotificationsEnabledForBundle_0200 - * @tc.desc : Test SetNotificationsEnabledForBundle function when bundleName not exist + * @tc.number : SetPrivateNotificationsAllowed_00200 + * @tc.name : + * @tc.desc : Set private notification allowed badge nums into disturbe DB when bundle name is null, return is + * ERR_ANS_INVALID_PARAM. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04500, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, SetPrivateNotificationsAllowed_00200, Function | SmallTest | Level1) { - std::string bundleName = ""; - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleName, false), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundleEmptyOption_, true), + (int)ERR_ANS_INVALID_PARAM); } /** - * @tc.number : NotificationPreferencesTest_04600 - * @tc.name : AMS_ANS_SetNotificationsEnabledForBundle_0300 - * @tc.desc : Test GetNotificationsEnabledForBundle function when file is null + * @tc.number : GetPrivateNotificationsAllowed_00100 + * @tc.name : + * @tc.desc : Get private notification allowed badge nums from disturbe DB, return is ERR_OK. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04600, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetPrivateNotificationsAllowed_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - bool enabled; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleName, enabled),0); + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundleOption_, true), (int)ERR_OK); + bool allow = false; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleOption_, allow), (int)ERR_OK); + EXPECT_EQ(allow, true); } /** - * @tc.number : NotificationPreferencesTest_04700 - * @tc.name : AMS_ANS_RemoveNotificationForBundle_0200 - * @tc.desc : Test RemoveNotificationForBundle function + * @tc.number : GetPrivateNotificationsAllowed_00200 + * @tc.name : + * @tc.desc : Get private notification allowed badge nums from disturbe DB when bundle is null, return is + * ERR_ANS_INVALID_PARAM. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04700, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetPrivateNotificationsAllowed_00200, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - TestAddNotificationSlot(); - EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleName), (int)ERR_OK); + bool allow = false; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleEmptyOption_, allow), + (int)ERR_ANS_INVALID_PARAM); } /** - * @tc.number : NotificationPreferencesTest_04800 - * @tc.name : AMS_ANS_AddNotificationSlotGroups_0400 - * @tc.desc : Test AddNotificationSlotGroups function when group size more than the max + * @tc.number : SetNotificationsEnabledForBundle_00100 + * @tc.name : + * @tc.desc : Set notification enable for bundle into disturbe DB, return is ERR_OK. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04800, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, SetNotificationsEnabledForBundle_00100, Function | SmallTest | Level1) { - std::string bundleName = "bundleName"; - sptr spGroup0 = new NotificationSlotGroup("id1", "name1"); - sptr spGroup1 = new NotificationSlotGroup("id2", "name2"); - sptr spGroup2 = new NotificationSlotGroup("id3", "name3"); - sptr spGroup3 = new NotificationSlotGroup("id4", "name4"); - sptr spGroup4 = new NotificationSlotGroup("id5", "name5"); - std::vector> groups; - groups.push_back(spGroup0); - groups.push_back(spGroup1); - groups.push_back(spGroup2); - groups.push_back(spGroup3); - groups.push_back(spGroup4); - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, groups), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleOption_, false), + (int)ERR_OK); } /** - * @tc.number : NotificationPreferencesTest_05000 - * @tc.name : AMS_ANS_SetDisturbMode_0100 - * @tc.desc : Test SetDisturbMode function + * @tc.number : SetNotificationsEnabledForBundle_00200 + * @tc.name : + * @tc.desc : Set notification enable for bundle into disturbe DB when bundle name is null, return is + * ERR_ANS_INVALID_PARAM. */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_05000, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, SetNotificationsEnabledForBundle_00200, Function | SmallTest | Level1) +{ + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleEmptyOption_, false), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : GetNotificationsEnabledForBundle_00100 + * @tc.name : + * @tc.desc : Get notification enable for bundle from disturbe DB, return is ERR_OK. + */ +HWTEST_F(NotificationPreferencesTest, GetNotificationsEnabledForBundle_02900, Function | SmallTest | Level1) +{ + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleOption_, false), + (int)ERR_OK); + bool enabled = false; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleOption_, enabled), + (int)ERR_OK); + EXPECT_FALSE(enabled); +} + +/** + * @tc.number : GetNotificationsEnabledForBundle_00100 + * @tc.name : + * @tc.desc : Get notification enable for bundle from disturbe DB when bundle name is null, return is + * ERR_ANS_INVALID_PARAM. + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02900, Function | SmallTest | Level1) +{ + bool enabled = false; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleEmptyOption_, enabled), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : SetNotificationsEnabled_00100 + * @tc.name : + * @tc.desc : Set enable notification into disturbe DB, return is ERR_OK + */ +HWTEST_F(NotificationPreferencesTest, SetNotificationsEnabled_00100, Function | SmallTest | Level1) +{ + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(true), (int)ERR_OK); +} + +/** + * @tc.number : GetNotificationsEnabled + * @tc.name : + * @tc.desc : Get enable notification from disturbe DB, return is ERR_OK + */ +HWTEST_F(NotificationPreferencesTest, GetNotificationsEnabled_00100, Function | SmallTest | Level1) +{ + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(true), (int)ERR_OK); + bool enable = false; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(enable), (int)ERR_OK); + EXPECT_TRUE(enable); +} + +/** + * @tc.number : SetDisturbMode_00100 + * @tc.name : + * @tc.desc : Set disturbe mode into disturbe DB, return is ERR_OK + */ +HWTEST_F(NotificationPreferencesTest, SetDisturbMode_00100, Function | SmallTest | Level1) { - TestAddNotificationSlot(); EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_ALL), (int)ERR_OK); } /** - * @tc.number : NotificationPreferencesTest_05200 - * @tc.name : AMS_ANS_GetDisturbMode_0200 - * @tc.desc : Test GetDisturbMode function + * @tc.number : GetDisturbMode_00100 + * @tc.name : + * @tc.desc : Get disturbe mode from disturbe DB, return is ERR_OK */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_05200, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetDisturbMode_00100, Function | SmallTest | Level1) { - TestAddNotificationSlot(); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_ALL), + (int)ERR_OK); NotificationConstant::DisturbMode mode; EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDisturbMode(mode), (int)ERR_OK); + EXPECT_EQ((int)NotificationConstant::DisturbMode::ALLOW_ALL, mode); } + } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/notification_slot_filter_test.cpp b/services/ans/test/unittest/notification_slot_filter_test.cpp index 376adab031ae2c3834c15ebe7131319f5434c6f2..1d8582a23e6c8eca63451a03f117f48042c1b5f1 100644 --- a/services/ans/test/unittest/notification_slot_filter_test.cpp +++ b/services/ans/test/unittest/notification_slot_filter_test.cpp @@ -24,24 +24,12 @@ namespace Notification { class NotificationSlotFilterTest : public testing::Test { public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); + static void SetUpTestCase(){}; + static void TearDownTestCase(){}; + void SetUp(){}; + void TearDown(){}; }; -void NotificationSlotFilterTest::SetUpTestCase() -{} - -void NotificationSlotFilterTest::TearDownTestCase() -{} - -void NotificationSlotFilterTest::SetUp() -{} - -void NotificationSlotFilterTest::TearDown() -{} - /** * @tc.number : NotificationSlotFilterTest_00100 * @tc.name : AMS_ANS_OnStart_0100 diff --git a/services/ans/test/unittest/notification_subscriber_manager_test.cpp b/services/ans/test/unittest/notification_subscriber_manager_test.cpp index d5a6b3cd52891458352d425f15bd6cae223254cf..c4367df55e131d86e90d4a5f0ab93c08de3cca4e 100644 --- a/services/ans/test/unittest/notification_subscriber_manager_test.cpp +++ b/services/ans/test/unittest/notification_subscriber_manager_test.cpp @@ -20,85 +20,103 @@ #include "notification_subscriber.h" #include "notification_subscriber_manager.h" +#include "ans_inner_errors.h" + using namespace testing::ext; namespace OHOS { namespace Notification { -std::shared_ptr g_notificationSubscriberManager; class NotificationSubscriberManagerTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); void SetUp(); void TearDown(); + +private: + class TestAnsSubscriber : public NotificationSubscriber { + public: + virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override + {} + virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override + {} + virtual void OnDied() override + {} + virtual void OnUpdate(const std::shared_ptr &sortingMap) override + {} + virtual void OnDisturbModeChanged(int disturbMode) override + {} + virtual void OnCanceled(const std::shared_ptr &request) override + {} + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override + {} + virtual void OnConsumed(const std::shared_ptr &request) override + {} + virtual void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override + {} + }; + + static std::shared_ptr notificationSubscriberManager_; + static TestAnsSubscriber testAnsSubscriber_; + static sptr subscriber_; }; +std::shared_ptr NotificationSubscriberManagerTest::notificationSubscriberManager_ = + nullptr; +NotificationSubscriberManagerTest::TestAnsSubscriber NotificationSubscriberManagerTest::testAnsSubscriber_; +sptr NotificationSubscriberManagerTest::subscriber_ = nullptr; + void NotificationSubscriberManagerTest::SetUpTestCase() { - g_notificationSubscriberManager = NotificationSubscriberManager::GetInstance(); + notificationSubscriberManager_ = NotificationSubscriberManager::GetInstance(); + subscriber_ = testAnsSubscriber_.GetImpl(); } void NotificationSubscriberManagerTest::TearDownTestCase() { - g_notificationSubscriberManager = nullptr; + subscriber_ = nullptr; + notificationSubscriberManager_ = nullptr; } void NotificationSubscriberManagerTest::SetUp() -{} +{ + notificationSubscriberManager_->AddSubscriber(subscriber_, nullptr); +} void NotificationSubscriberManagerTest::TearDown() -{} -class TestAnsSubscriber : public NotificationSubscriber { -public: - virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override - {} - virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override - {} - virtual void OnDied() override - {} - virtual void OnUpdate(const std::shared_ptr &sortingMap) override - {} - virtual void OnDisturbModeChanged(int disturbMode) override - {} - virtual void OnCanceled(const std::shared_ptr &request) override - {} - virtual void OnCanceled(const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason) override - {} - virtual void OnConsumed(const std::shared_ptr &request) override - {} - virtual void OnConsumed(const std::shared_ptr &request, - const std::shared_ptr &sortingMap) override - {} -}; +{ + notificationSubscriberManager_->RemoveSubscriber(subscriber_, nullptr); +} /** * @tc.number : NotificationSubscriberManagerTest_001 * @tc.name : AMS_ANS_NotifyUpdated_0100 - * @tc.desc : Test NotifyUpdated function + * @tc.desc : Test NotifyUpdated function. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_001, Function | SmallTest | Level1) { const std::vector sortingList; sptr map = new NotificationSortingMap(sortingList); - g_notificationSubscriberManager->NotifyUpdated(map); + notificationSubscriberManager_->NotifyUpdated(map); } /** * @tc.number : NotificationSubscriberManagerTest_002 * @tc.name : AMS_ANS_NotifyDisturbModeChanged_0100 - * @tc.desc : Test NotifyDisturbModeChanged function + * @tc.desc : Test NotifyDisturbModeChanged function. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_002, Function | SmallTest | Level1) { NotificationConstant::DisturbMode mode; - g_notificationSubscriberManager->NotifyDisturbModeChanged(mode); + notificationSubscriberManager_->NotifyDisturbModeChanged(mode); } /** * @tc.number : NotificationSubscriberManagerTest_003 * @tc.name : AMS_ANS_NotifyConsumed_0100 - * @tc.desc : Test NotifyConsumed function + * @tc.desc : Test NotifyConsumed function. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_003, Function | SmallTest | Level1) { @@ -106,13 +124,13 @@ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_00 sptr request = new NotificationRequest(); sptr notification = new Notification(request); sptr notificationMap = new NotificationSortingMap(sortingList); - g_notificationSubscriberManager->NotifyConsumed(notification, notificationMap); + notificationSubscriberManager_->NotifyConsumed(notification, notificationMap); } /** * @tc.number : NotificationSubscriberManagerTest_004 * @tc.name : AMS_ANS_NotifyCanceled_0100 - * @tc.desc : Test NotifyCanceled function + * @tc.desc : Test NotifyCanceled function. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_004, Function | SmallTest | Level1) { @@ -121,31 +139,54 @@ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_00 sptr notification = new Notification(request); sptr notificationMap = new NotificationSortingMap(sortingList); int deleteReason = 0; - g_notificationSubscriberManager->NotifyCanceled(notification, notificationMap, deleteReason); + notificationSubscriberManager_->NotifyCanceled(notification, notificationMap, deleteReason); } /** * @tc.number : NotificationSubscriberManagerTest_005 * @tc.name : AMS_ANS_AddSubscriber_0100 - * @tc.desc : Test AddSubscriber function + * @tc.desc : Test AddSubscriber function, return is ERR_OK. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_005, Function | SmallTest | Level1) { - auto subscriber = new TestAnsSubscriber(); sptr info = new NotificationSubscribeInfo(); - EXPECT_EQ(g_notificationSubscriberManager->AddSubscriber(subscriber->GetImpl(), info), (int)ERR_OK); + info->AddAppName("test_bundle"); + EXPECT_EQ(notificationSubscriberManager_->AddSubscriber(subscriber_, info), (int)ERR_OK); + EXPECT_EQ(notificationSubscriberManager_->AddSubscriber(subscriber_, nullptr), (int)ERR_OK); } /** * @tc.number : NotificationSubscriberManagerTest_006 - * @tc.name : AMS_ANS_RemoveSubscriber_0100 - * @tc.desc : Test RemoveSubscriber function + * @tc.name : AMS_ANS_AddSubscriber_0100 + * @tc.desc : Test AddSubscriber function when subscriber is nullptr, return is ERR_ANS_INVALID_PARAM. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_006, Function | SmallTest | Level1) { - auto subscriber = new TestAnsSubscriber(); sptr info = new NotificationSubscribeInfo(); - EXPECT_EQ(g_notificationSubscriberManager->RemoveSubscriber(subscriber->GetImpl(), info), (int)ERR_OK); + EXPECT_EQ(notificationSubscriberManager_->AddSubscriber(nullptr, info), (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationSubscriberManagerTest_007 + * @tc.name : AMS_ANS_RemoveSubscriber_0100 + * @tc.desc : Test RemoveSubscriber function, return is ERR_OK. + */ +HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_007, Function | SmallTest | Level1) +{ + sptr info = new NotificationSubscribeInfo(); + info->AddAppName("test_bundle"); + EXPECT_EQ(notificationSubscriberManager_->RemoveSubscriber(subscriber_, info), (int)ERR_OK); +} + +/** + * @tc.number : NotificationSubscriberManagerTest_006 + * @tc.name : AMS_ANS_AddSubscriber_0100 + * @tc.desc : Test RemoveSubscriber function when subscriber is nullptr, return is ERR_ANS_INVALID_PARAM. + */ +HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_008, Function | SmallTest | Level1) +{ + sptr info = new NotificationSubscribeInfo(); + EXPECT_EQ(notificationSubscriberManager_->RemoveSubscriber(nullptr, info), (int)ERR_ANS_INVALID_PARAM); } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/permission_filter_test.cpp b/services/ans/test/unittest/permission_filter_test.cpp index e984e5df6f5be22f1f5cc6501e0a78778e531999..6472f51756f1afe51ebbc294500c466261d2b4d3 100644 --- a/services/ans/test/unittest/permission_filter_test.cpp +++ b/services/ans/test/unittest/permission_filter_test.cpp @@ -17,6 +17,7 @@ #include #include "ans_inner_errors.h" +#include "ans_ut_constant.h" #include "notification_preferences.h" #include "notification_slot.h" #include "permission_filter.h" @@ -28,18 +29,12 @@ namespace Notification { class PermissionFilterTest : public testing::Test { public: - static void SetUpTestCase(); - static void TearDownTestCase(); + static void SetUpTestCase(){}; + static void TearDownTestCase(){}; void SetUp(); void TearDown(); }; -void PermissionFilterTest::SetUpTestCase() -{} - -void PermissionFilterTest::TearDownTestCase() -{} - void PermissionFilterTest::SetUp() { NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); @@ -72,37 +67,23 @@ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00200, Function | SmallTest permissionFilter.OnStop(); } -/** - * @tc.number : PermissionFilterTest_00300 - * @tc.name : AMS_ANS_OnPublish_0100 - * @tc.desc : Test OnPublish function when the param is wrong - */ -HWTEST_F(PermissionFilterTest, PermissionFilterTest_00300, Function | SmallTest | Level1) -{ - PermissionFilter permissionFilter; - std::shared_ptr record = std::make_shared(); - record->request = new NotificationRequest(); - record->notification = new Notification(record->request); - record->slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - EXPECT_EQ(permissionFilter.OnPublish(record), (int)ERR_ANS_INVALID_PARAM); -} - /** * @tc.number : PermissionFilterTest_00400 - * @tc.name : AMS_ANS_OnPublish_0200 - * @tc.desc : Test OnPublish function + * @tc.name : + * @tc.desc : Test OnPublish function.Expect return ERR_OK */ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00400, Function | SmallTest | Level1) { PermissionFilter permissionFilter; - std::string bundleName = "bundleName"; sptr slot = new NotificationSlot(NotificationConstant::OTHER); std::vector> slots; slots.push_back(slot); - NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots); + NotificationPreferences::GetInstance().AddNotificationSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots); std::shared_ptr record = std::make_shared(); + record->bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); record->request = new NotificationRequest(); - record->request->SetOwnerBundleName(bundleName); + record->request->SetOwnerBundleName(TEST_DEFUALT_BUNDLE); record->notification = new Notification(record->request); record->slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); EXPECT_EQ(permissionFilter.OnPublish(record), ERR_OK); @@ -110,44 +91,25 @@ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00400, Function | SmallTest /** * @tc.number : PermissionFilterTest_00500 - * @tc.name : AMS_ANS_OnPublish_0300 - * @tc.desc : Test OnPublish function when file is null + * @tc.name : + * @tc.desc : Test OnPublish function when NotificationsEnabled is false.Expect return ERR_ANS_NOT_ALLOWED */ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00500, Function | SmallTest | Level1) { PermissionFilter permissionFilter; - std::string bundleName = "bundleName"; - sptr slot = new NotificationSlot(NotificationConstant::OTHER); - std::vector> slots; - slots.push_back(slot); - NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots); - std::shared_ptr record = std::make_shared(); - record->request = new NotificationRequest(); - record->request->SetOwnerBundleName("bundleName1"); - record->notification = new Notification(record->request); - record->slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - EXPECT_EQ((int)permissionFilter.OnPublish(record), (int)ERR_OK); -} - -/** - * @tc.number : PermissionFilterTest_00600 - * @tc.name : AMS_ANS_OnPublish_0400 - * @tc.desc : Test OnPublish function when NotificationsEnabled is false - */ -HWTEST_F(PermissionFilterTest, PermissionFilterTest_00600, Function | SmallTest | Level1) -{ - PermissionFilter permissionFilter; - std::string bundleName = "bundleName"; sptr slot = new NotificationSlot(NotificationConstant::OTHER); std::vector> slots; slots.push_back(slot); - NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots); - NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleName, false); + NotificationPreferences::GetInstance().AddNotificationSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots); + NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), false); std::shared_ptr record = std::make_shared(); + record->bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); record->request = new NotificationRequest(); - record->request->SetOwnerBundleName(bundleName); + record->request->SetOwnerBundleName(TEST_DEFUALT_BUNDLE); record->notification = new Notification(record->request); - record->slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + record->slot = slot; EXPECT_EQ((int)permissionFilter.OnPublish(record), (int)ERR_ANS_NOT_ALLOWED); } diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp index bc99a3773f1abb48f81e44ec1a8297f79aee9a1d..b9a2f35358202ad6ba830e7893287fcc520a6924 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 @@ -1146,7 +1160,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0054, Function | SmallTest | Level1) { // add slot std::vector> slots; - sptr group = new NotificationSlotGroup(); + sptr group = new NotificationSlotGroup("id", "name"); sptr socialSlot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); sptr reminderSlot = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); sptr contentSlot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); @@ -1178,7 +1192,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0055, Function | SmallTest | Level1) { // add slot std::vector> slots; - sptr group = new NotificationSlotGroup(); + sptr group = new NotificationSlotGroup("id", "name"); sptr socialSlot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); socialSlot->SetSlotGroup(group->GetId()); slots.push_back(socialSlot); @@ -1244,7 +1258,9 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0058, Function | SmallTest | Level1) req->SetBadgeNumber(1); // SetShowBadgeEnabledForBundle true - g_advancedNotificationService->SetShowBadgeEnabledForBundle("bundleName", true); + sptr bundleOption; + bundleOption->SetBundleName("bundleName"); + g_advancedNotificationService->SetShowBadgeEnabledForBundle(bundleOption, true); g_advancedNotificationService->Publish(label, req); EXPECT_EQ(true, passed); @@ -2605,54 +2621,47 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0130, Function | SmallTest | Level1) auto subscriber = new TestAnsSubscriber(); g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr); subscriber->consumedCb_ = []( - const std::shared_ptr notification, + const std::shared_ptr notification, const std::shared_ptr sortingMap) { EXPECT_EQ(false, notification->EnableVibrate()); - EXPECT_EQ(NotificationConstant::VisiblenessType::PUBLIC,notification->GetLockscreenVisibleness()); + EXPECT_EQ(NotificationConstant::VisiblenessType::PUBLIC, notification->GetLockscreenVisibleness()); }; // add slot std::vector> slots; - sptr slot=new NotificationSlot(NotificationConstant::SlotType::OTHER); + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); slots.push_back(slot); slot->SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PUBLIC); slot->SetEnableVibration(true); // create request - std::string label="testLabel"; - sptr req=new NotificationRequest(0); + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); req->SetSlotType(NotificationConstant::SlotType::OTHER); req->SetLabel(label); // publish g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); - } - /** * @tc.number : AnsModuleTest_0131 * @tc.name : AMS_ANS_GetActiveNotifications_13100 * @tc.desc : Test publish notification when cancel a notification. */ -HWTEST_F(AnsModuleTest,AnsModuleTest_0131,Function | SmallTest|Level1){ - //subscriber +HWTEST_F(AnsModuleTest, AnsModuleTest_0131, Function | SmallTest | Level1) +{ + // subscriber auto subscriber = new TestAnsSubscriber(); - g_advancedNotificationService->Subscribe(subscriber->GetImpl(),nullptr); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr); subscriber->canceledCb_ = [](const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason) { passed = true; }; // g_advancedNotificationService->Cancel(1, "1"); - EXPECT_EQ(false,passed); - + EXPECT_EQ(false, passed); } - - - - } // namespace Notification } // namespace OHOS - diff --git a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp index 5df99fa52d095ed5f9e4c51929afd1931fe6ca57..5fef8d274b4e69d4419e24f95d9771b499194d06 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 1acbe4a3fd7b60e0a044d5f21d3fdfa60c25f879..6a93d95c4fb403e104c9312a49881a7cfc957b7b 100644 --- a/services/test/moduletest/mock/mock_ipc.cpp +++ b/services/test/moduletest/mock/mock_ipc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,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 diff --git a/test/BUILD.gn b/test/BUILD.gn index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..ab4862fc3c51a76b96f8dd6ba000c2fb3cc299b1 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -0,0 +1,28 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +config("system_test_config") { + include_dirs = [ "//third_party/json/include" ] + + configs = [] +} + +group("systemtest") { + testonly = true + + deps = [ "resource\ansSTSlotGroupTest:ansSTSlotGroupTest" ] +} diff --git a/test/resource/ansSTSlotGroupTest/BUILD.gn b/test/resource/ansSTSlotGroupTest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0018e05b840f2547a2eb17956731e8261e8eb40c --- /dev/null +++ b/test/resource/ansSTSlotGroupTest/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +SUBDEMOSYSTEM_DIR = "${ans_standard_path}/test/resource/ansSTSlotGroupTest" + +group("ansSTSlotGroupTest") { + deps = [ ":libraryAnsSTSlotGroupTest" ] +} + +config("ansSTSlotGroupTestConfig") { + visibility = [ ":*" ] + + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${interfaces_path}/innerkits/ans/native/include", + ] + + defines = [ + "APP_LOG_TAG = \"ansSTSlotGroupTest\"", + "LOG_DOMAIN = 0xD002200", + ] +} + +ohos_shared_library("libraryAnsSTSlotGroupTest") { + sources = [ "${SUBDEMOSYSTEM_DIR}/src/ans_slotgroup_test.cpp" ] + + configs = [ ":ansSTSlotGroupTestConfig" ] + + deps = [ + "${core_path}:ans_core", + "${frameworks_path}/ans/native:ans_innerkits", + "${frameworks_path}/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//utils/native/base:utilsbase", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + subsystem_name = "notification" + part_name = "ans_standard" +} diff --git a/test/resource/ansSTSlotGroupTest/config.json b/test/resource/ansSTSlotGroupTest/config.json new file mode 100644 index 0000000000000000000000000000000000000000..bc9a6fa50b65f0b256ddc25fa1a567dc449810d1 --- /dev/null +++ b/test/resource/ansSTSlotGroupTest/config.json @@ -0,0 +1,40 @@ +{ + "app":{ + "bundleName": "com.ohos.ansst.ansSTSlotGroup", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AnsSlotGroupSystemTest.src", + "name":"AnsSlotGroupSystemTest", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AnsSlotGroupSystemTest", + "icon": "$media:snowball", + "label": "AnsSlotGroupSystemTest Ability zofa label", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h b/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h new file mode 100644 index 0000000000000000000000000000000000000000..d745fbf319a844956e178d4015a37f3e81cfd8e6 --- /dev/null +++ b/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h @@ -0,0 +1,51 @@ +/* + * 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_st_slotgroup_ +#define _ans_st_slotgroup_ + +#include +#include "ability_loader.h" +#include +#ifdef PRINT_LOG +#undef PRINT_LOG +#endif +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { + +class AnsSlotGroupSystemTest : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif \ No newline at end of file diff --git a/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f798c041785be6d22d2b1b595d31806fde27f4f --- /dev/null +++ b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp @@ -0,0 +1,129 @@ +/* + * 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 "ans_slotgroup_test.h" +#include + +namespace OHOS { +namespace AppExecFwk { +void AnsSlotGroupSystemTest::OnStart(const Want &want) +{ + APP_LOGI("====> ans SlotGroup test start:====>"); + Notification::NotificationSlotGroup notificationSlotGroupTest("id_test", "name_test"); + if (notificationSlotGroupTest.GetId().empty()) { + ANS_LOGI("====> Notification slot group id is invalid====>"); + } else { + ANS_LOGI("====> Notification slot group id is====> %{public}s", notificationSlotGroupTest.GetId().c_str()); + } + ErrCode errcodeAdd = Notification::NotificationHelper::AddNotificationSlotGroup(notificationSlotGroupTest); + printf("====> ErrCode Add:====> %d\n", errcodeAdd); + APP_LOGI("====> ansSlotGroupTest add add add add add add:====> %{public}d", errcodeAdd); + + Notification::NotificationSlot notificationSlotFirst( + Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + Notification::NotificationSlot notificationSlotSecond( + Notification::NotificationConstant::SlotType::SERVICE_REMINDER); + + notificationSlotFirst.SetSlotGroup("id_test"); + notificationSlotSecond.SetSlotGroup("id_test"); + + ErrCode errcodeAddSlotFirst = Notification::NotificationHelper::AddNotificationSlot(notificationSlotFirst); + ErrCode errcodeAddSlotSecond = Notification::NotificationHelper::AddNotificationSlot(notificationSlotSecond); + + APP_LOGI("====> ansSlotGroupTest:: errcodeAddSlotFirst :" + "====> %{public}d", + errcodeAddSlotFirst); + APP_LOGI("====> ansSlotGroupTest:: errcodeAddSlotSecond :" + "====> %{public}d", + errcodeAddSlotSecond); + sptr group; + ErrCode errcodeGet = Notification::NotificationHelper::GetNotificationSlotGroup("id_test", group); + APP_LOGI("====> ansSlotGroupTest:: get get get get get get :" + "====> %{public}d", + errcodeGet); + std::string dumpGroupStr = group->Dump(); + APP_LOGI("====> ansSlotGroupTest:: dump dump dump dump dump :" + "====> %{public}s", + dumpGroupStr.c_str()); + APP_LOGI("====> ansSlotGroupTest:: the size of slots :" + "====> %{public}zu", + group->GetSlots().size()); + + ErrCode errcodeRem = Notification::NotificationHelper::RemoveNotificationSlotGroup("id_test"); + APP_LOGI("====> ansSlotGroupTest:: remove remove remove remove :" + "====> %{public}d", + errcodeRem); + sptr groupTwo; + ErrCode errcodeGetTwo = Notification::NotificationHelper::GetNotificationSlotGroup("id_test", groupTwo); + APP_LOGI("====> ansSlotGroupTest:: get get get get get get :" + "====> %{public}d", + errcodeGetTwo); + Ability::OnStart(want); +} + +void AnsSlotGroupSystemTest::OnNewWant(const Want &want) +{ + GetWantInfo(want); + Ability::OnNewWant(want); +} + +void AnsSlotGroupSystemTest::OnForeground(const Want &want) +{ + GetWantInfo(want); + Ability::OnForeground(want); +} + +void AnsSlotGroupSystemTest::OnStop() +{ + Ability::OnStop(); +} + +void AnsSlotGroupSystemTest::OnActive() +{ + Ability::OnActive(); + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); +} + +void AnsSlotGroupSystemTest::OnInactive() +{ + Ability::OnInactive(); +} + +void AnsSlotGroupSystemTest::OnBackground() +{ + Ability::OnBackground(); +} + +void AnsSlotGroupSystemTest::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AnsSlotGroupSystemTest::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AnsSlotGroupSystemTest) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/ansSlotGroupHap/AnsSTSlotGroupTest.hap b/test/resource/ansSlotGroupHap/AnsSTSlotGroupTest.hap new file mode 100755 index 0000000000000000000000000000000000000000..62a810190d1093a65ae99d6b7e729b3e20a3cecb Binary files /dev/null and b/test/resource/ansSlotGroupHap/AnsSTSlotGroupTest.hap differ diff --git a/tools/dump/src/notification_shell_command.cpp b/tools/dump/src/notification_shell_command.cpp index 54fa0f5125744134ec7542c3d125c7b451e93d3e..a4c1056996029d93ad9488f78b83f880c4d0a315 100644 --- a/tools/dump/src/notification_shell_command.cpp +++ b/tools/dump/src/notification_shell_command.cpp @@ -90,7 +90,7 @@ ErrCode NotificationShellCommand::RunAsDumpCommand() {0, 0, 0, 0}, }; - int ind; + int ind = 0; int option = getopt_long(argc_, argv_, "hAR", options, &ind); ErrCode ret = ERR_OK; @@ -137,7 +137,7 @@ ErrCode NotificationShellCommand::RunAsDumpCommand() resultReceiver_.append(info); } - return ERR_OK; + return ret; } } // namespace Notification