From 94556d67af5bea05e164e7b6b3475815c72cefb1 Mon Sep 17 00:00:00 2001 From: zhaoyuan Date: Fri, 10 Sep 2021 13:58:11 +0000 Subject: [PATCH 1/2] test static check Signed-off-by: zhaoyuan --- README_zh.md | 44 +- frameworks/ans/core/BUILD.gn | 3 + .../include/ans_manager_death_recipient.h | 4 +- .../ans/core/include/ans_manager_interface.h | 41 +- .../ans/core/include/ans_manager_proxy.h | 39 +- .../ans/core/include/ans_manager_stub.h | 42 +- .../ans/core/include/ans_notification.h | 109 +- .../core/include/ans_subscriber_interface.h | 2 +- .../ans/core/include/ans_subscriber_proxy.h | 2 +- .../ans/core/include/ans_subscriber_stub.h | 2 +- frameworks/ans/core/src/ans_manager_proxy.cpp | 250 ++- frameworks/ans/core/src/ans_manager_stub.cpp | 318 ++- frameworks/ans/core/src/ans_notification.cpp | 140 +- .../ans/core/src/ans_subscriber_stub.cpp | 4 +- frameworks/ans/native/BUILD.gn | 3 + frameworks/ans/native/src/message_user.cpp | 4 +- frameworks/ans/native/src/notification.cpp | 46 +- .../native/src/notification_action_button.cpp | 69 +- .../native/src/notification_basic_content.cpp | 4 +- .../native/src/notification_bundle_option.cpp | 90 + .../ans/native/src/notification_constant.cpp | 4 +- .../ans/native/src/notification_content.cpp | 4 +- .../notification_conversational_content.cpp | 4 +- .../notification_conversational_message.cpp | 4 +- .../ans/native/src/notification_helper.cpp | 69 +- .../src/notification_long_text_content.cpp | 4 +- .../native/src/notification_media_content.cpp | 4 +- .../src/notification_multiline_content.cpp | 4 +- .../src/notification_normal_content.cpp | 4 +- .../src/notification_picture_content.cpp | 4 +- .../ans/native/src/notification_request.cpp | 131 +- .../ans/native/src/notification_slot.cpp | 14 +- .../native/src/notification_slot_group.cpp | 30 +- .../ans/native/src/notification_sorting.cpp | 4 +- .../native/src/notification_sorting_map.cpp | 8 +- .../native/src/notification_subscriber.cpp | 8 + .../native/src/notification_user_input.cpp | 20 +- frameworks/ans/test/moduletest/BUILD.gn | 252 ++- .../test/moduletest/ans_fw_module_test.cpp | 1599 ++++++++------ .../ans_innerkits_module_publish_test.cpp | 1130 ++++++++++ .../ans_innerkits_module_setting_test.cpp | 139 ++ .../ans_innerkits_module_slot_test.cpp | 420 ++++ .../ans/test/moduletest/ans_mt_constant.h | 41 + frameworks/ans/test/moduletest/mock/blob.cpp | 211 ++ .../mock/distributed_kv_data_manager.cpp | 65 + .../mock/include/mock_bundle_manager.h | 129 ++ .../mock/include/mock_ipc_skeleton.h | 61 + .../mock/include/mock_single_kv_store.h | 250 +++ .../ans/test/moduletest/mock/mock_ipc.cpp | 23 +- .../moduletest/mock/mock_ipc_object_proxy.cpp | 369 ---- .../moduletest/mock/mock_message_parcel.cpp | 2 +- .../moduletest/mock/mock_single_kv_store.cpp | 311 +++ frameworks/wantagent/src/pending_want.cpp | 3 +- frameworks/wantagent/src/trigger_info.cpp | 14 + frameworks/wantagent/src/want_agent.cpp | 3 +- .../wantagent/src/want_agent_helper.cpp | 2 +- frameworks/wantagent/src/want_agent_info.cpp | 4 +- .../completed_dispatcher_test.cpp | 1 + .../pending_want_test/pending_want_test.cpp | 48 +- .../trigger_Info_test/trigger_Info_test.cpp | 1 + .../want_agent_helper_test.cpp | 1 + .../want_agent_info_test.cpp | 1 + .../ans/native/include/message_user.h | 10 +- .../ans/native/include/notification.h | 11 +- .../include/notification_action_button.h | 52 +- .../include/notification_basic_content.h | 4 +- .../include/notification_bundle_option.h | 100 + .../native/include/notification_constant.h | 20 +- .../ans/native/include/notification_content.h | 4 +- .../notification_conversational_content.h | 4 +- .../notification_conversational_message.h | 4 +- .../ans/native/include/notification_helper.h | 108 +- .../include/notification_long_text_content.h | 4 +- .../include/notification_media_content.h | 4 +- .../include/notification_multiline_content.h | 4 +- .../include/notification_normal_content.h | 4 +- .../include/notification_picture_content.h | 4 +- .../ans/native/include/notification_request.h | 67 +- .../ans/native/include/notification_slot.h | 24 +- .../native/include/notification_slot_group.h | 28 +- .../native/include/notification_subscriber.h | 12 +- .../native/include/notification_user_input.h | 4 +- .../wantagent/include/trigger_info.h | 10 + .../innerkits/wantagent/include/want_agent.h | 1 + .../wantagent/include/want_agent_constant.h | 1 + .../wantagent/include/want_agent_helper.h | 21 +- .../wantagent/include/want_agent_info.h | 2 +- interfaces/kits/js/@ohos.notification.d.ts | 406 ++++ interfaces/kits/js/@ohos.wantAgent.d.ts | 154 ++ .../notification/notificationActionButton.ts | 31 + .../js/notification/notificationContent.d.ts | 77 + .../js/notification/notificationRequest.d.ts | 74 + .../js/notification/notificationSlot.d.ts | 104 + .../js/notification/notificationSorting.d.ts | 31 + .../notification/notificationSortingMap.d.ts | 30 + .../notification/notificationSubscribeInfo.ts | 28 + .../notification/notificationSubscriber.d.ts | 58 + interfaces/kits/js/wantAgent/triggerInfo.d.ts | 32 + .../kits/js/wantAgent/wantAgentInfo.d.ts | 34 + interfaces/kits/napi/ans/BUILD.gn | 4 +- interfaces/kits/napi/ans/include/common.h | 42 +- interfaces/kits/napi/ans/include/constant.h | 3 +- .../kits/napi/ans/include/create_subscriber.h | 116 - .../kits/napi/ans/include/display_badge.h | 34 +- .../kits/napi/ans/include/disturb_mode.h | 28 + .../napi/ans/include/enable_notification.h | 29 + interfaces/kits/napi/ans/include/slot.h | 4 + interfaces/kits/napi/ans/include/subscribe.h | 73 +- .../kits/napi/ans/include/unsubscribe.h | 1 - interfaces/kits/napi/ans/src/cancel.cpp | 157 +- interfaces/kits/napi/ans/src/common.cpp | 1939 ++++++++++------- interfaces/kits/napi/ans/src/constant.cpp | 28 +- .../kits/napi/ans/src/create_subscriber.cpp | 892 -------- .../kits/napi/ans/src/display_badge.cpp | 265 +++ interfaces/kits/napi/ans/src/disturb_mode.cpp | 126 ++ .../kits/napi/ans/src/enable_notification.cpp | 262 +++ interfaces/kits/napi/ans/src/get_active.cpp | 276 ++- interfaces/kits/napi/ans/src/init.cpp | 19 +- interfaces/kits/napi/ans/src/publish.cpp | 155 +- interfaces/kits/napi/ans/src/remove.cpp | 313 +-- interfaces/kits/napi/ans/src/slot.cpp | 948 +++++--- interfaces/kits/napi/ans/src/subscribe.cpp | 948 +++++++- interfaces/kits/napi/ans/src/unsubscribe.cpp | 98 +- .../kits/napi/wantagent/napi_want_agent.cpp | 13 +- ohos.build | 4 +- .../include/advanced_notification_service.h | 39 +- services/ans/include/bundle_manager_helper.h | 5 +- services/ans/include/interface_system_event.h | 4 +- .../ans/include/notification_preferences.h | 69 +- .../notification_preferences_database.h | 77 +- .../include/notification_preferences_info.h | 27 +- services/ans/include/notification_record.h | 2 + services/ans/include/preferences_constant.h | 82 +- .../ans/include/system_event_subscriber.h | 3 + .../ans/src/advanced_notification_service.cpp | 632 ++++-- services/ans/src/bundle_manager_helper.cpp | 22 +- services/ans/src/disturb_filter.cpp | 3 + services/ans/src/notification_preferences.cpp | 379 ++-- .../src/notification_preferences_database.cpp | 685 +++--- .../ans/src/notification_preferences_info.cpp | 67 +- services/ans/src/notification_slot_filter.cpp | 18 +- .../src/notification_subscriber_manager.cpp | 4 +- services/ans/src/permission_filter.cpp | 4 +- services/ans/src/system_event_observer.cpp | 7 +- services/ans/test/unittest/BUILD.gn | 6 +- ...nced_notification_service_ability_test.cpp | 26 +- .../advanced_notification_service_test.cpp | 901 ++++++-- services/ans/test/unittest/ans_ut_constant.h | 35 + .../unittest/bundle_manager_helper_test.cpp | 26 +- .../ans/test/unittest/disturb_filter_test.cpp | 20 +- .../mock/distributed_kv_data_manager.cpp | 9 +- .../mock/include/mock_bundle_manager.h | 412 ---- .../unittest/mock/include/mock_ipc_skeleton.h | 2 +- .../mock/mock_bundle_manager_helper.cpp | 14 +- .../unittest/mock/mock_bundle_mgr_proxy.cpp | 280 --- services/ans/test/unittest/mock/mock_ipc.cpp | 5 +- .../unittest/mock/mock_single_kv_store.cpp | 33 +- ...notification_preferences_database_test.cpp | 405 ++-- .../notification_preferences_test.cpp | 1129 +++++++--- .../notification_slot_filter_test.cpp | 20 +- .../notification_subscriber_manager_test.cpp | 127 +- .../test/unittest/permission_filter_test.cpp | 74 +- services/test/moduletest/ans_module_test.cpp | 49 +- .../mock/mock_bundle_manager_helper.cpp | 4 +- services/test/moduletest/mock/mock_ipc.cpp | 6 +- test/BUILD.gn | 28 + test/resource/ansSTSlotGroupTest/BUILD.gn | 72 + test/resource/ansSTSlotGroupTest/config.json | 40 + .../include/ans_slotgroup_test.h | 51 + .../src/ans_slotgroup_test.cpp | 132 ++ .../ansSlotGroupHap/AnsSTSlotGroupTest.hap | Bin 0 -> 102831 bytes tools/dump/src/notification_shell_command.cpp | 4 +- 172 files changed, 14083 insertions(+), 6915 deletions(-) mode change 100644 => 100755 frameworks/ans/native/BUILD.gn create mode 100644 frameworks/ans/native/src/notification_bundle_option.cpp mode change 100644 => 100755 frameworks/ans/test/moduletest/BUILD.gn create mode 100644 frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp create mode 100644 frameworks/ans/test/moduletest/ans_innerkits_module_setting_test.cpp create mode 100644 frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp create mode 100644 frameworks/ans/test/moduletest/ans_mt_constant.h create mode 100644 frameworks/ans/test/moduletest/mock/blob.cpp create mode 100644 frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp create mode 100755 frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h create mode 100644 frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h delete mode 100644 frameworks/ans/test/moduletest/mock/mock_ipc_object_proxy.cpp create mode 100644 frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp create mode 100644 interfaces/innerkits/ans/native/include/notification_bundle_option.h create mode 100644 interfaces/kits/js/@ohos.notification.d.ts create mode 100644 interfaces/kits/js/@ohos.wantAgent.d.ts create mode 100644 interfaces/kits/js/notification/notificationActionButton.ts create mode 100644 interfaces/kits/js/notification/notificationContent.d.ts create mode 100644 interfaces/kits/js/notification/notificationRequest.d.ts create mode 100644 interfaces/kits/js/notification/notificationSlot.d.ts create mode 100644 interfaces/kits/js/notification/notificationSorting.d.ts create mode 100644 interfaces/kits/js/notification/notificationSortingMap.d.ts create mode 100644 interfaces/kits/js/notification/notificationSubscribeInfo.ts create mode 100644 interfaces/kits/js/notification/notificationSubscriber.d.ts create mode 100644 interfaces/kits/js/wantAgent/triggerInfo.d.ts create mode 100644 interfaces/kits/js/wantAgent/wantAgentInfo.d.ts mode change 100644 => 100755 interfaces/kits/napi/ans/BUILD.gn delete mode 100644 interfaces/kits/napi/ans/include/create_subscriber.h rename services/ans/test/unittest/mock/mock_bundle_manager.cpp => interfaces/kits/napi/ans/include/display_badge.h (50%) create mode 100644 interfaces/kits/napi/ans/include/disturb_mode.h create mode 100644 interfaces/kits/napi/ans/include/enable_notification.h delete mode 100644 interfaces/kits/napi/ans/src/create_subscriber.cpp create mode 100644 interfaces/kits/napi/ans/src/display_badge.cpp create mode 100644 interfaces/kits/napi/ans/src/disturb_mode.cpp create mode 100644 interfaces/kits/napi/ans/src/enable_notification.cpp create mode 100644 services/ans/test/unittest/ans_ut_constant.h delete mode 100644 services/ans/test/unittest/mock/include/mock_bundle_manager.h delete mode 100644 services/ans/test/unittest/mock/mock_bundle_mgr_proxy.cpp create mode 100644 test/resource/ansSTSlotGroupTest/BUILD.gn create mode 100644 test/resource/ansSTSlotGroupTest/config.json create mode 100644 test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h create mode 100644 test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp create mode 100755 test/resource/ansSlotGroupHap/AnsSTSlotGroupTest.hap diff --git a/README_zh.md b/README_zh.md index 740832be1..4004597ce 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 4f52df4d5..f630d47e4 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 f46e8df6f..a726115e9 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 136bf8cd1..c6fe562d8 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 d3221d4a0..b90bc8e95 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 bc9f3b356..4bf53b386 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 bea2c2c7f..c21ec347b 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 68808a23b..539f22a60 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 b4561feef..1774567c2 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 415074d7c..4d60ccfc0 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 c113a2589..bbfa3b448 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 484dd0a49..1185b647f 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 57abd5718..5bf4a26c3 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 31850df90..8ecb57219 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 cc0cb3825..e8c5dae33 --- 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 d91769912..161d72387 100644 --- a/frameworks/ans/native/src/message_user.cpp +++ b/frameworks/ans/native/src/message_user.cpp @@ -91,8 +91,8 @@ std::string MessageUser::Dump() const ", name = " + name_ + ", pixelMap = " + (pixelMap_ ? "not null" : "null") + ", uri = " + uri_.ToString() + - ", isMachine = " + std::to_string(isMachine_) + - ", isUserImportant = " + std::to_string(isUserImportant_) + "]"; + ", isMachine = " + (isMachine_ ? "true" : "false") + + ", isUserImportant = " + (isUserImportant_ ? "true" : "false") + "]"; } bool MessageUser::Marshalling(Parcel &parcel) const diff --git a/frameworks/ans/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp index 31b376365..c69e0864c 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 80f7e40c9..62cf80e18 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 718ecd0f3..4942104e2 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 000000000..acdfc939c --- /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 7fff8410e..744dc11f6 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 26106dea4..1accb1daa 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 51ce80bf6..2b1925d84 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 e2f3b9e3a..9274ef8aa 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 2570e4d09..86ea093d9 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 e7dc470b2..f17afa07b 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 daf3ace8b..f6d3e65b3 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 495c25715..4d0df649d 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 dec172656..e9e253789 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 d155eb4a6..385e3c467 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 1b850292c..809de5494 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 05223bd1c..cf83dbca4 100644 --- a/frameworks/ans/native/src/notification_slot.cpp +++ b/frameworks/ans/native/src/notification_slot.cpp @@ -196,15 +196,19 @@ void NotificationSlot::EnableBadge(bool isShowBadge) std::string NotificationSlot::Dump() const { - return "NotificationSlot[id = " + id_ + ", name = " + name_ + ", description = " + description_ + + return "NotificationSlot[ id = " + id_ + + ", name = " + name_ + + ", description = " + description_ + ", type = " + std::to_string(static_cast(type_)) + ", level = " + std::to_string(static_cast(level_)) + - ", isBypassDnd = " + std::to_string(isBypassDnd_) + + ", isBypassDnd = " + (isBypassDnd_ ? "true" : "false") + ", visibleness = " + std::to_string(static_cast(lockScreenVisibleness_)) + - ", sound = " + sound_.ToString() + ", isLightEnabled = " + std::to_string(isLightEnabled_) + - ", lightColor = " + std::to_string(lightColor_) + ", isVibrate = " + std::to_string(isVibrationEnabled_) + + ", sound = " + sound_.ToString() + + ", isLightEnabled = " + (isLightEnabled_ ? "true" : "false") + + ", lightColor = " + std::to_string(lightColor_) + + ", isVibrate = " + (isVibrationEnabled_ ? "true" : "false") + ", vibration = " + MergeVectorToString(vibrationValues_) + - ", isShowBadge = " + std::to_string(isShowBadge_) + ", groupId = " + groupId_ + "]"; + ", isShowBadge = " + (isShowBadge_ ? "true" : "false") + ", groupId = " + groupId_ + "]"; } bool NotificationSlot::Marshalling(Parcel &parcel) const diff --git a/frameworks/ans/native/src/notification_slot_group.cpp b/frameworks/ans/native/src/notification_slot_group.cpp index 6de656121..8146d3435 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 22fbba79b..6315d338d 100644 --- a/frameworks/ans/native/src/notification_sorting.cpp +++ b/frameworks/ans/native/src/notification_sorting.cpp @@ -58,8 +58,8 @@ std::string NotificationSorting::Dump() const return "NotificationSorting[key =" + key_ + ", ranking =" + std::to_string(ranking_) + ", importance =" + std::to_string(importance_) + ", visiblenessOverride =" + std::to_string(visiblenessOverride_) + - ", isDisplayBadge =" + std::to_string(isDisplayBadge_) + - ", isHiddenNotification =" + std::to_string(isHiddenNotification_) + + ", isDisplayBadge =" + (isDisplayBadge_ ? "true" : "false") + + ", isHiddenNotification =" + (isHiddenNotification_ ? "true" : "false") + ", groupKeyOverride =" + groupKeyOverride_ + ", slot_ =" + contents + "]"; } diff --git a/frameworks/ans/native/src/notification_sorting_map.cpp b/frameworks/ans/native/src/notification_sorting_map.cpp index 6fa30aae2..8e32c8bfe 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 cc16b2845..4220ea0ec 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 5c6e96027..e14dd2f75 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 cc524695c..db73e3179 --- 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 6a33dab28..04e1b237e 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,253 @@ 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: + SubscriberEventType GetType() + { + return type_; + } + +protected: + SubscriberEvent(SubscriberEventType type) : type_(type) + {} + + SubscriberEventType type_; +}; + +class OnSubscribeResultEvent : public SubscriberEvent { +public: + 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 +294,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(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); -} - -/** - * @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(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(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); - 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 000000000..fbf6f3116 --- /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 000000000..98a38c06f --- /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 000000000..99d2a2796 --- /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 000000000..93d2c3470 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/blob.cpp @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "Blob" + +#include "blob.h" +#include +#include "log_print.h" + +namespace OHOS { +namespace DistributedKv { +Blob::Blob() { } + +Blob::Blob(const Blob &blob) +{ + blob_ = blob.Data(); +} + +Blob::Blob(Blob &&blob) +{ + blob_.swap(blob.blob_); +} + +Blob &Blob::operator=(const Blob &blob) +{ + // Self-assignment detection + if (&blob == this) { + return *this; + } + + blob_ = blob.Data(); + + return *this; +} + +Blob &Blob::operator=(Blob &&blob) +{ + // Self-assignment detection + if (&blob == this) { + return *this; + } + + blob_.swap(blob.blob_); + + return *this; +} + +Blob::Blob(const char *str, size_t n) + : blob_() +{ + if (str != nullptr) { + blob_ = std::vector(str, str + n); + } +} + +Blob::Blob(const std::string &str) + : blob_(str.begin(), str.end()) +{ +} + +Blob::Blob(const char *str) + : blob_() +{ + if (str != nullptr) { + blob_ = std::vector(str, str + strlen(str)); + } +} + +Blob::Blob(const std::vector &bytes) + : blob_(bytes) +{ +} + +Blob::Blob(std::vector &&bytes) + : blob_(std::move(bytes)) +{ +} + +const std::vector &Blob::Data() const +{ + return blob_; +} + +size_t Blob::Size() const +{ + return blob_.size(); +} + +int Blob::RawSize() const +{ + return sizeof(int) + blob_.size(); +} + +bool Blob::Empty() const +{ + return blob_.empty(); +} + +uint8_t Blob::operator[](size_t n) const +{ + if (n >= Size()) { + ZLOGE("Trying to get a out-of-range Blob member."); + return 0; + } + return blob_[n]; +} + +bool Blob::operator==(const Blob &blob) const +{ + return blob_ == blob.blob_; +} + +void Blob::Clear() +{ + blob_.clear(); +} + +std::string Blob::ToString() const +{ + std::string str(blob_.begin(), blob_.end()); + return str; +} + +int Blob::Compare(const Blob &blob) const +{ + if (blob_ < blob.blob_) { + return -1; + } + if (blob_ == blob.blob_) { + return 0; + } + return 1; +} + +bool Blob::StartsWith(const Blob &blob) const +{ + size_t len = blob.Size(); + if (Size() < len) { + return false; + } + + for (size_t i = 0; i < len; ++i) { + if (blob_[i] != blob.blob_[i]) { + return false; + } + } + return true; +} + +bool Blob::Marshalling(Parcel &parcel) const +{ + return parcel.WriteUInt8Vector(this->blob_); +} + +Blob *Blob::Unmarshalling(Parcel &parcel) +{ + std::vector blobData; + if (!parcel.ReadUInt8Vector(&blobData)) { + return nullptr; + } + return new Blob(blobData); +} + +/* write blob size and data to memory buffer. return error when bufferLeftSize not enough. */ +bool Blob::WriteToBuffer(uint8_t *&cursorPtr, int &bufferLeftSize) const +{ + if (cursorPtr == nullptr || bufferLeftSize < static_cast(blob_.size() + sizeof(int))) { + return false; + } + *reinterpret_cast(cursorPtr) = static_cast(blob_.size()); + bufferLeftSize -= sizeof(int32_t); + cursorPtr += sizeof(int32_t); + errno_t err = memcpy_s(cursorPtr, bufferLeftSize, blob_.data(), blob_.size()); + if (err != EOK) { + return false; + } + cursorPtr += blob_.size(); + bufferLeftSize -= blob_.size(); + return true; +} + +/* read a blob from memory buffer. */ +bool Blob::ReadFromBuffer(const uint8_t *&cursorPtr, int &bufferLeftSize) +{ + if (cursorPtr == nullptr || bufferLeftSize < static_cast(sizeof(int))) { + return false; + } + int blobSize = *reinterpret_cast(cursorPtr); + bufferLeftSize -= sizeof(int) + blobSize; + if (blobSize < 0 || bufferLeftSize < 0) { + return false; + } + cursorPtr += sizeof(int); + blob_ = std::vector(cursorPtr, cursorPtr + blobSize); + cursorPtr += blobSize; + return true; +} +} // namespace DistributedKv +} // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp b/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp new file mode 100644 index 000000000..656932c20 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "DistributedKvDataManager" + +#include "distributed_kv_data_manager.h" +#include "constant.h" +//#include "ikvstore.h" +#include "mock_single_kv_store.h" +#include "types.h" + +namespace OHOS { +namespace DistributedKv { +DistributedKvDataManager::DistributedKvDataManager() +{} + +DistributedKvDataManager::~DistributedKvDataManager() +{} + +void DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, + std::function)> callback) +{ + std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); + Status status = Status::SUCCESS; + std::unique_ptr proxyTmp = std::make_unique(); + callback(status, std::move(proxyTmp)); +} + +Status DistributedKvDataManager::CloseKvStore( + const AppId &appId, const StoreId &storeId, std::unique_ptr kvStorePtr) +{ + return Status::SUCCESS; +} + +Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::unique_ptr kvStorePtr) +{ + return Status::SUCCESS; +} + +Status DistributedKvDataManager::DeleteKvStore(const AppId &appId, const StoreId &storeId) +{ + return Status::SUCCESS; +} + +void DistributedKvDataManager::RegisterKvStoreServiceDeathRecipient( + std::shared_ptr kvStoreDeathRecipient) +{} + +void DistributedKvDataManager::UnRegisterKvStoreServiceDeathRecipient( + std::shared_ptr kvStoreDeathRecipient) +{} +} // namespace DistributedKv +} // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h index 960b2aa7b..de0de2d65 100644 --- a/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h +++ b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h @@ -95,6 +95,16 @@ public: { return 0; } + /** + * @brief Obtains the application ID based on the given bundle name and user ID. + * @param bundleName Indicates the bundle name of the application. + * @param userId Indicates the user ID. + * @return Returns the application ID if successfully obtained; returns empty string otherwise. + */ + virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override + { + return "bundlename"; + } /** * @brief Obtains the bundle name of a specified application based on the given UID. * @param uid Indicates the uid. @@ -106,6 +116,26 @@ public: bundleName = "hello"; return true; } + /** + * @brief Obtains all bundle names of a specified application based on the given application UID. + * @param uid Indicates the uid. + * @param bundleNames Indicates the obtained bundle names. + * @return Returns true if the bundle names is successfully obtained; returns false otherwise. + */ + virtual bool GetBundlesForUid(const int uid, std::vector &bundleNames) override + { + return true; + } + + /* @brief Obtains the formal name associated with the given UID. + * @param uid Indicates the uid. + * @param name Indicates the obtained formal name. + * @return Returns true if the formal name is successfully obtained; returns false otherwise. + */ + virtual bool GetNameForUid(const int uid, std::string &name) override + { + return true; + } /** * @brief Obtains an array of all group IDs associated with a specified bundle. * @param bundleName Indicates the bundle name. @@ -289,6 +319,70 @@ public: { return true; } + /** + * @brief Registers a callback for listening for permission changes of all UIDs. + * @param callback Indicates the callback method to register. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool RegisterAllPermissionsChanged(const sptr &callback) override + { + return true; + } + /** + * @brief Registers a callback for listening for permission changes of specified UIDs. + * @param uids Indicates the list of UIDs whose permission changes will be monitored. + * @param callback Indicates the callback method to register. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool RegisterPermissionsChanged( + const std::vector &uids, const sptr &callback) override + { + return true; + } + /** + * @brief Unregisters a specified callback for listening for permission changes. + * @param callback Indicates the callback method to register. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool UnregisterPermissionsChanged(const sptr &callback) override + { + return true; + } + /** + * @brief Obtains the FormInfo objects provided by all applications on the device. + * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the + * device. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetAllFormsInfo(std::vector &formInfos) override + { + return true; + } + /** + * @brief Obtains the FormInfo objects provided by a specified application on the device. + * @param bundleName Indicates the bundle name of the application. + * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the + * device. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfos) override + { + return true; + } + + /** + * @brief Obtains the FormInfo objects provided by a specified. + * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the + * device. + * @param moduleName Indicates the module name of the application. + * @param bundleName Indicates the bundle name of the application. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetFormsInfoByModule( + const std::string &bundleName, const std::string &moduleName, std::vector &formInfos) override + { + return true; + } /** * @brief Checks whether the system has a specified capability. * @param capName Indicates the name of the system feature to check. @@ -392,6 +486,36 @@ public: { return true; } + /** + * @brief Sets whether to enable a specified ability. + * @param abilityInfo Indicates information about the ability to check. + * @return Returns true if the ability is enabled; returns false otherwise. + */ + virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) override + { + return true; + } + /** + * @brief Obtains the icon of a specified ability. + * @param bundleName Indicates the bundle name. + * @param className Indicates the ability class name. + * @return Returns the icon resource string of the ability if exist; returns empty string otherwise. + */ + virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override + { + return "abilityicon"; + } + /** + * @brief Sets whether to enable a specified ability. + * @param abilityInfo Indicates information about the ability. + * @param isEnabled Specifies whether to enable the ability. + * The value true means to enable it, and the value false means to disable it. + * @return Returns true if the ability is enabled; returns false otherwise. + */ + virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) override + { + return true; + } /** * @brief Obtains the interface used to install and uninstall bundles. * @return Returns a pointer to IBundleInstaller class if exist; returns nullptr otherwise. @@ -403,6 +527,11 @@ public: void MockSetIsSystemApp(bool isSystemApp); + std::string GetBundleNameByUid(pid_t uid) + { + return "bundle"; + } + private: bool isSystemApp_ = false; bool isSystemAppMock_ = false; diff --git a/frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h b/frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h new file mode 100755 index 000000000..7881f108a --- /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 000000000..8a777ea02 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANS_MOCK_SINGLE_KV_STORE_H +#define ANS_MOCK_SINGLE_KV_STORE_H + +#include +#include + +#include "kvstore.h" +#include "kvstore_observer.h" +#include "kvstore_result_set.h" +#include "kvstore_sync_callback.h" +#include "types.h" +#include "data_query.h" +#include "single_kvstore.h" + +namespace OHOS { +namespace DistributedKv { +// This is a public interface. Implementation of this class is in AppKvStoreImpl. +// This class provides put, delete, search, sync and subscribe functions of a key-value store. +class AnsTestSingleKvStore : public SingleKvStore { +public: + + // Get all entries in this store which key start with prefixKey. + // Parameters: + // perfixkey: the prefix to be searched. + // entries: entries will be returned in this parameter. + // Return: + // Status of this GetEntries operation. + virtual Status GetEntries(const Key &prefixKey, std::vector &entries) const override; + + // Get all entries in this store by query. + // Parameters: + // query: the query string. + // entries: entries will be returned in this parameter. + // Return: + // Status of this GetEntries operation. + virtual Status GetEntriesWithQuery(const std::string &query, std::vector &entries) const override; + + // Get all entries in this store by query. + // Parameters: + // query: the query object. + // entries: entries will be returned in this parameter. + // Return: + // Status of this GetEntries operation. + virtual Status GetEntriesWithQuery(const DataQuery &query, std::vector &entries) const override; + + // Get ResultSet in this store which key start with prefixKey. + // Parameters: + // perfixkey: the prefix to be searched. + // resultSet: resultSet will be returned in this parameter. + // Return: + // Status of this GetResultSet operation. + virtual void GetResultSet(const Key &prefixKey, + std::function)> callback) const override; + + // Get ResultSet in this store by Query. + // Parameters: + // query: the query string. + // resultSet: resultSet will be returned in this parameter. + // Return: + // Status of this GetResultSet operation. + virtual void GetResultSetWithQuery(const std::string &query, + std::function)> callback) const override; + + // Get ResultSet in this store by Query. + // Parameters: + // query: the query object. + // resultSet: resultSet will be returned in this parameter. + // Return: + // Status of this GetResultSet operation. + virtual void GetResultSetWithQuery(const DataQuery &query, + std::function)> callback) const override; + + // Close the ResultSet returned by GetResultSet. + // Parameters: + // resultSet: resultSet will be returned in this parameter. + // Return: + // Status of this CloseResultSet operation. + virtual Status CloseResultSet(std::unique_ptr resultSet) override; + + // Get the number of result by query. + // Parameters: + // query: the query string. + // result: result will be returned in this parameter. + // Return: + // Status of this CloseResultSet operation. + virtual Status GetCountWithQuery(const std::string &query, int &result) const override; + + // Get the number of result by query. + // Parameters: + // query: the query object. + // result: result will be returned in this parameter. + // Return: + // Status of this CloseResultSet operation. + virtual Status GetCountWithQuery(const DataQuery &query, int &result) const override; + + // Sync store with other devices. This is an asynchronous method, + // sync will fail if there is a syncing operation in progress. + // Parameters: + // deviceIdList: device list to sync. + // mode: mode can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. PUSH_PULL will firstly + // push all not-local store to listed devices, then pull these stores back. + // allowedDelayMs: allowed delay milli-second to sync. default value is 0 for compatibility. + // Return: + // Status of this Sync operation. + virtual Status Sync(const std::vector &deviceIdList, const SyncMode &mode, + uint32_t allowedDelayMs = 0) override; + + // Remove the device data synced from remote. + // Parameters: + // device: device id. + // Return: + // Status of this remove operation. + virtual Status RemoveDeviceData(const std::string &device) override; + + // Get id of this SingleKvStore. + virtual StoreId GetStoreId() const override; + + // Delete an entry by its key. + // Parameters: + // key: key of the entry to be deleted. + // Return: + // Status of this delete operation. + virtual Status Delete(const Key &key) override; + + // Write a pair of key and value to this store. + // Parameters: + // key: key of this entry. Should be less than 1024 bytes. key will be trimmed before store. + // value: value of this entry. Should be less than (4 * 1024 * 1024) bytes. + // Return: + // Status of this put operation. + virtual Status Put(const Key &key, const Value &value) override; + + // Get value from AppKvStore by its key. + // Parameters: + // key: key of this entry. + // value: value will be returned in this parameter. + // Return: + // Status of this get operation. + virtual Status Get(const Key &key, Value &value) override; + + // subscribe change of this kvstore to a client-defined observer. observer->OnChange method will be called when store + // changes. + // Parameters: + // subscribeType: SUBSCRIBE_TYPE_LOCAL means local changes of syncable kv store, + // : SUBSCRIBE_TYPE_REMOTE means synced data changes from remote devices, + // : SUBSCRIBE_TYPE_ALL means both local changes and synced data changes. + // observer: observer to subscribe changes. + // Return: + // Status of this subscribe operation. + virtual Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + + // un-subscribe change of this kvstore to a client-defined observer. + // Parameters: + // subscribeType: SUBSCRIBE_TYPE_LOCAL means local changes of syncable kv store, + // : SUBSCRIBE_TYPE_REMOTE means synced data changes from remote devices, + // : SUBSCRIBE_TYPE_ALL means both local changes and synced data changes. + // observer: observer to subscribe changes. + // Return: + // Status of this subscribe operation. + virtual Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + + // register message for sync operation. + // Parameters: + // callback: callback to register. + // Return: + // Status of this register operation. + virtual Status RegisterSyncCallback(std::shared_ptr callback) override; + + // un-register message for sync operation. + // Parameters: + // callback: callback to register. + // Return: + // Status of this register operation. + virtual Status UnRegisterSyncCallback() override; + + // see Put, PutBatch put a list of entries to kvstore, + // all entries will be put in a transaction, + // if entries contains invalid entry, PutBatch will all fail. + // entries's size should be less than 128 and memory size must be less than IPC transport limit. + virtual Status PutBatch(const std::vector &entries) override; + + // delete a list of entries in the kvstore, + // delete key not exist still return success, + // key length should not be greater than 256, and can not be empty. + // if keys contains invalid key, all delete will fail. + // keys memory size should not be greater than IPC transport limit, and can not be empty. + virtual Status DeleteBatch(const std::vector &keys) override; + + // start transaction. + // all changes to this kvstore will be in a same transaction and will not change the store until Commit() or + // Rollback() is called. + // before this transaction is committed or rollbacked, all attemption to close this store will fail. + virtual Status StartTransaction() override; + + // commit current transaction. all changes to this store will be done after calling this method. + // any calling of this method outside a transaction will fail. + virtual Status Commit() override; + + // rollback current transaction. + // all changes to this store during this transaction will be rollback after calling this method. + // any calling of this method outside a transaction will fail. + virtual Status Rollback() override; + + // set synchronization parameters of this store. + // Parameters: + // syncParam: sync policy parameter. + // Return: + // Status of this operation. + virtual Status SetSyncParam(const KvSyncParam &syncParam) override; + + // get synchronization parameters of this store. + // Parameters: + // syncParam: sync policy parameter. + // Return: + // Status of this operation. + virtual Status GetSyncParam(KvSyncParam &syncParam) override; + + virtual Status SetCapabilityEnabled(bool enabled) const override; + + virtual Status SetCapabilityRange(const std::vector &localLabels, + const std::vector &remoteSupportLabels) const override; + + virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const override; +protected: + // control this store. + // Parameters: + // inputParam: input parameter. + // output: output data, nullptr if no data is returned. + // Return: + // Status of this control operation. + KVSTORE_API virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, sptr &output) override; +}; +} // namespace AppDistributedKv +} // namespace OHOS +#endif // SINGLE_KV_STORE_H diff --git a/frameworks/ans/test/moduletest/mock/mock_ipc.cpp b/frameworks/ans/test/moduletest/mock/mock_ipc.cpp index 1acbe4a3f..35f5b7b31 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 4c184d7eb..000000000 --- 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 0e4751f1c..26b6304c7 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 000000000..4b580d297 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mock_single_kv_store.h" +#include "types.h" + +namespace OHOS { +namespace DistributedKv { +// Get all entries in this store which key start with prefixKey. +// Parameters: +// perfixkey: the prefix to be searched. +// entries: entries will be returned in this parameter. +// Return: +// Status of this GetEntries operation. +Status AnsTestSingleKvStore::GetEntries(const Key &prefixKey, std::vector &entries) const +{ + return Status::SUCCESS; +} + +// Get all entries in this store by query. +// Parameters: +// query: the query string. +// entries: entries will be returned in this parameter. +// Return: +// Status of this GetEntries operation. +Status AnsTestSingleKvStore::GetEntriesWithQuery(const std::string &query, std::vector &entries) const +{ + return Status::SUCCESS; +} + +// Get all entries in this store by query. +// Parameters: +// query: the query object. +// entries: entries will be returned in this parameter. +// Return: +// Status of this GetEntries operation. +Status AnsTestSingleKvStore::GetEntriesWithQuery(const DataQuery &query, std::vector &entries) const +{ + return Status::SUCCESS; +} + +// Get ResultSet in this store which key start with prefixKey. +// Parameters: +// perfixkey: the prefix to be searched. +// resultSet: resultSet will be returned in this parameter. +// Return: +// Status of this GetResultSet operation. +void AnsTestSingleKvStore::GetResultSet(const Key &prefixKey, + std::function)> callback) const +{ + +} + +// Get ResultSet in this store by Query. +// Parameters: +// query: the query string. +// resultSet: resultSet will be returned in this parameter. +// Return: +// Status of this GetResultSet operation. +void AnsTestSingleKvStore::GetResultSetWithQuery(const std::string &query, + std::function)> callback) const +{ + +} + +// Get ResultSet in this store by Query. +// Parameters: +// query: the query object. +// resultSet: resultSet will be returned in this parameter. +// Return: +// Status of this GetResultSet operation. +void AnsTestSingleKvStore::GetResultSetWithQuery(const DataQuery &query, + std::function)> callback) const +{ + +} + +// Close the ResultSet returned by GetResultSet. +// Parameters: +// resultSet: resultSet will be returned in this parameter. +// Return: +// Status of this CloseResultSet operation. +Status AnsTestSingleKvStore::CloseResultSet(std::unique_ptr resultSet) +{ + return Status::SUCCESS; +} + +// Get the number of result by query. +// Parameters: +// query: the query string. +// result: result will be returned in this parameter. +// Return: +// Status of this CloseResultSet operation. +Status AnsTestSingleKvStore::GetCountWithQuery(const std::string &query, int &result) const +{ + return Status::SUCCESS; +} + +// Get the number of result by query. +// Parameters: +// query: the query object. +// result: result will be returned in this parameter. +// Return: +// Status of this CloseResultSet operation. +Status AnsTestSingleKvStore::GetCountWithQuery(const DataQuery &query, int &result) const +{ + return Status::SUCCESS; +} + +// Sync store with other devices. This is an asynchronous method, +// sync will fail if there is a syncing operation in progress. +// Parameters: +// deviceIdList: device list to sync. +// mode: mode can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. PUSH_PULL will firstly +// push all not-local store to listed devices, then pull these stores back. +// allowedDelayMs: allowed delay milli-second to sync. default value is 0 for compatibility. +// Return: +// Status of this Sync operation. +Status AnsTestSingleKvStore::Sync(const std::vector &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs) +{ + return Status::SUCCESS; +} + +// Remove the device data synced from remote. +// Parameters: +// device: device id. +// Return: +// Status of this remove operation. +Status AnsTestSingleKvStore::RemoveDeviceData(const std::string &device) +{ + return Status::SUCCESS; +} + +// Get id of this SingleKvStore. +StoreId AnsTestSingleKvStore::GetStoreId() const +{ + StoreId storeId; + storeId.storeId = ""; + return storeId; +} + +// Delete an entry by its key. +// Parameters: +// key: key of the entry to be deleted. +// Return: +// Status of this delete operation. +Status AnsTestSingleKvStore::Delete(const Key &key) +{ + return Status::SUCCESS; +} + +// Write a pair of key and value to this store. +// Parameters: +// key: key of this entry. Should be less than 1024 bytes. key will be trimmed before store. +// value: value of this entry. Should be less than (4 * 1024 * 1024) bytes. +// Return: +// Status of this put operation. +Status AnsTestSingleKvStore::Put(const Key &key, const Value &value) +{ + return Status::SUCCESS; +} + +// Get value from AppKvStore by its key. +// Parameters: +// key: key of this entry. +// value: value will be returned in this parameter. +// Return: +// Status of this get operation. +Status AnsTestSingleKvStore::Get(const Key &key, Value &value) +{ + return Status::SUCCESS; +} + +// subscribe change of this kvstore to a client-defined observer. observer->OnChange method will be called when store +// changes. +// Parameters: +// subscribeType: SUBSCRIBE_TYPE_LOCAL means local changes of syncable kv store, +// : SUBSCRIBE_TYPE_REMOTE means synced data changes from remote devices, +// : SUBSCRIBE_TYPE_ALL means both local changes and synced data changes. +// observer: observer to subscribe changes. +// Return: +// Status of this subscribe operation. +Status AnsTestSingleKvStore::SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) +{ + return Status::SUCCESS; +} + +// un-subscribe change of this kvstore to a client-defined observer. +// Parameters: +// subscribeType: SUBSCRIBE_TYPE_LOCAL means local changes of syncable kv store, +// : SUBSCRIBE_TYPE_REMOTE means synced data changes from remote devices, +// : SUBSCRIBE_TYPE_ALL means both local changes and synced data changes. +// observer: observer to subscribe changes. +// Return: +// Status of this subscribe operation. +Status AnsTestSingleKvStore::UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) +{ + return Status::SUCCESS; +} + +// register message for sync operation. +// Parameters: +// callback: callback to register. +// Return: +// Status of this register operation. +Status AnsTestSingleKvStore::RegisterSyncCallback(std::shared_ptr callback) +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::UnRegisterSyncCallback() +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::PutBatch(const std::vector &entries) +{ + return Status::SUCCESS; +} + + +// delete a list of entries in the kvstore, +// delete key not exist still return success, +// key length should not be greater than 256, and can not be empty. +// if keys contains invalid key, all delete will fail. +// keys memory size should not be greater than IPC transport limit, and can not be empty. +Status AnsTestSingleKvStore::DeleteBatch(const std::vector &keys) +{ + return Status::SUCCESS; +} + +// start transaction. +// all changes to this kvstore will be in a same transaction and will not change the store until Commit() or +// Rollback() is called. +// before this transaction is committed or rollbacked, all attemption to close this store will fail. +Status AnsTestSingleKvStore::StartTransaction() +{ + return Status::SUCCESS; +} + +// commit current transaction. all changes to this store will be done after calling this method. +// any calling of this method outside a transaction will fail. +Status AnsTestSingleKvStore::Commit() +{ + return Status::SUCCESS; +} + +// rollback current transaction. +// all changes to this store during this transaction will be rollback after calling this method. +// any calling of this method outside a transaction will fail. +Status AnsTestSingleKvStore::Rollback() +{ + return Status::SUCCESS; +} + +// set synchronization parameters of this store. +// Parameters: +// syncParam: sync policy parameter. +// Return: +// Status of this operation. +Status AnsTestSingleKvStore::SetSyncParam(const KvSyncParam &syncParam) +{ + return Status::SUCCESS; +} + +// get synchronization parameters of this store. +// Parameters: +// syncParam: sync policy parameter. +// Return: +// Status of this operation. +Status AnsTestSingleKvStore::GetSyncParam(KvSyncParam &syncParam) +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::SetCapabilityEnabled(bool enabled) const +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::SetCapabilityRange(const std::vector &localLabels, + const std::vector &remoteSupportLabels) const +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::GetSecurityLevel(SecurityLevel &securityLevel) const +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam, sptr &output) +{ + return Status::SUCCESS; +} + + +} // namespace DistributedKv +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/wantagent/src/pending_want.cpp b/frameworks/wantagent/src/pending_want.cpp index a65cc57b9..d5d86db34 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 1e5763b34..aec2c92a9 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 0cf03073a..d0d529d45 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 3c59c41a8..5b3c49c1b 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 4d66a12ae..b0fe01159 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 2dfb828e1..9cb6c4d32 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; diff --git a/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp b/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp index 1fd7b5c73..ce840740f 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; @@ -159,7 +169,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 +186,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 +204,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 +226,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 +249,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 +273,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 +301,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 +318,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 +336,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 +352,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 +368,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 +385,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 +401,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 +418,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 +434,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 +453,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 = @@ -462,7 +472,7 @@ HWTEST_F(PendingWantTest, PendingWant_1900, Function | MediumTest | Level1) std::shared_ptr pendingWant = std::make_shared(target); sptr target2(nullptr); std::shared_ptr pendingWant2 = std::make_shared(target2); - EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), true); + EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), false); } /* @@ -495,7 +505,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 +528,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)); 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 0fb2e984f..08c195f16 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 957123078..3b1ebfdda 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 bdf8d1384..03e10f936 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 3cb50e7cd..0ceb44f49 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 ab91f6690..9a338eaea 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 adda5ae95..42f8af582 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 c99a1cad9..f96de434b 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 000000000..7c2fa9171 --- /dev/null +++ b/interfaces/innerkits/ans/native/include/notification_bundle_option.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BUNDLE_OPTION_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BUNDLE_OPTION_H + +#include +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationBundleOption : public Parcelable { +public: + /** + * A default constructor used to create a NotificationBundleOption instance. + */ + NotificationBundleOption() = default; + + /** + * A constructor used to create a NotificationBundleOption instance based on the creator bundle name and uid. + * @param bundleName Indicates the creator bundle name. + * @param uid Indicates the creator uid. + */ + NotificationBundleOption(const std::string &bundleName, const int32_t uid); + + /** + * Default deconstructor used to deconstruct. + */ + virtual ~NotificationBundleOption(); + + /** + * Sets the creator bundle name. + * @param bundleName Indicates the creator bundle name. + */ + void SetBundleName(const std::string &bundleName); + + /** + * Obtains the creator bundle name. + * @return the creator bundle name. + */ + std::string GetBundleName() const; + + /** + * Sets the creator uid. + * @param uid Indicates the creator uid. + */ + void SetUid(const int32_t uid); + + /** + * Obtains the creator uid. + * @return the creator uid. + */ + int32_t GetUid() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationBundleOption + */ + static NotificationBundleOption *Unmarshalling(Parcel &parcel); + +private: + /** + * Read data from a Parcel. + * @param parcel the parcel + * @return true if read success; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + +private: + std::string bundleName_{}; + int32_t uid_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONTENT_H diff --git a/interfaces/innerkits/ans/native/include/notification_constant.h b/interfaces/innerkits/ans/native/include/notification_constant.h index 64bbddccd..554699724 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 01fc7fe8c..6a3733897 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 894db4116..9e274ed77 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 e18b103f1..acd2c31ec 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 236b4a41f..b6b5fbf65 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 c01757c78..f0a7ffb15 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 00d29f750..cfc7b3be2 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 db0f4db89..1bbfe05ea 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 b9145ceb7..4bb177e95 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 45dda0608..1fdd92f7e 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 c6e677199..0f52f5bf6 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 c5cce6553..5a82654de 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 ba95b6af4..f979cdd93 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 24b1c4ac3..7cbac600d 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 97b34ed89..41b548076 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 9e6eff4e1..ce60016a4 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 6b8251f14..06d6cd36b 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 867be3a99..461b023c1 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 e217e5bdb..cf775dde2 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 168443c26..15c411dc9 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 000000000..c7b4b87c5 --- /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 000000000..23f8c861f --- /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 000000000..21690e602 --- /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 000000000..f89526b33 --- /dev/null +++ b/interfaces/kits/js/notification/notificationContent.d.ts @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import notification from '../@ohos.notification'; + +/** + * Constructs basic notifications. + * + * @name NotificationBasicContent + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationBasicContent { + title: string; + text: string; + additionalText?: string; +} + +/** + * Constructs notifications that include long text. The long text contains a maximum of 1024 characters. + * + * @name NotificationLongTextContent + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationLongTextContent extends NotificationBasicContent { + longText: string; + briefText: string; + expandedTitle: string; +} + +/** + * Constructs a notification that includes multiple lines of text. + * + * @name NotificationMultiLineContent + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationMultiLineContent extends NotificationBasicContent { + briefText: string; + longTitle: string; + lines: Array; +} + +/** + * Constructs a notification that includes multiple lines of text. + * + * @name NotificationMultiLineContent + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface NotificationContent { + contentType: notification.ContentType; + normal?: NotificationBasicContent; + longText?: NotificationLongTextContent; + multiLine?: NotificationMultiLineContent; +} diff --git a/interfaces/kits/js/notification/notificationRequest.d.ts b/interfaces/kits/js/notification/notificationRequest.d.ts new file mode 100644 index 000000000..5fd0fc9e6 --- /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 000000000..e91e8c0eb --- /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 000000000..73fbae19b --- /dev/null +++ b/interfaces/kits/js/notification/notificationSorting.d.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NotificationSlot } from './notificationSlot'; + +/** + * Provides sorting information about an active notification. + * + * @name NotificationSorting + * @sysCap ans + * @devices phone, tablet + * @permission N/A + * @since 7 + */ +export interface NotificationSorting { + readonly slot: NotificationSlot; + readonly hashCode: string; + readonly ranking: number; +} \ No newline at end of file diff --git a/interfaces/kits/js/notification/notificationSortingMap.d.ts b/interfaces/kits/js/notification/notificationSortingMap.d.ts new file mode 100644 index 000000000..f632189de --- /dev/null +++ b/interfaces/kits/js/notification/notificationSortingMap.d.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NotificationSorting } from './notificationSorting'; + +/** + * Provides sorting information about the active notifications among all the notifications that have been subscribed to + * + * @name NotificationSortingMap + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +interface NotificationSortingMap { + readonly sortings: {[key: string]: NotificationSorting}; + readonly sortedHashCode: Array; +} \ No newline at end of file diff --git a/interfaces/kits/js/notification/notificationSubscribeInfo.ts b/interfaces/kits/js/notification/notificationSubscribeInfo.ts new file mode 100644 index 000000000..4d9afb649 --- /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 000000000..309c15bb3 --- /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 000000000..f12ac8ebe --- /dev/null +++ b/interfaces/kits/js/wantAgent/triggerInfo.d.ts @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Want } from '../ability/want'; + +/** + * the info when object of WantAgent trigger + * + * @name TriggerInfo + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface TriggerInfo { + code: number; + want?: Want; + permission?: string; + extraInfo?: {[key: string]: any}; +} \ No newline at end of file diff --git a/interfaces/kits/js/wantAgent/wantAgentInfo.d.ts b/interfaces/kits/js/wantAgent/wantAgentInfo.d.ts new file mode 100644 index 000000000..675ba97d1 --- /dev/null +++ b/interfaces/kits/js/wantAgent/wantAgentInfo.d.ts @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Want } from '../ability/want'; +import wantAgent from '../@ohos.wantAgent' + +/** + * the info of WantAgent + * + * @name WantAgentInfo + * @since 7 + * @sysCap ans + * @devices phone, tablet + * @permission N/A + */ +export interface WantAgentInfo { + wants: Array; + operationType: wantAgent.OperationType; + requestCode: number; + wantAgentFlags?: Array; + extraInfo?: {[key: string]: any}; +} \ No newline at end of file diff --git a/interfaces/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn old mode 100644 new mode 100755 index 2c1ca3a90..d7d886beb --- 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 9b427c4d4..92a08e74b 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 516b4422f..249864af9 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 a5f0055c4..000000000 --- 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 d026341ec..945543193 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 000000000..9a199f9a7 --- /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 000000000..e7ae30648 --- /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 1f851d501..789bc5376 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 80b0faffe..5046928a0 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 ac6c6d8c4..595de743b 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 24fb59675..5264e984f 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 174867b4e..09531dac6 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 7744cfa77..3b16f7734 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 28360ea0a..000000000 --- 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 000000000..52d895636 --- /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 000000000..34040e313 --- /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 000000000..014c6c3e6 --- /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 0ae881ec3..cf9bab8a6 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 14eb5ce8c..64869c224 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 eda71be1a..8dd5e880c 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 a3f01f924..a2c4f62ba 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 c3967c3b4..ef4f6893c 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}d", 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 af36a9452..0cf6e5e64 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}d", 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}d", 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}d", 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 babc54fbf..659c9e59d 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 411937c4c..1369b64e9 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.cpp +++ b/interfaces/kits/napi/wantagent/napi_want_agent.cpp @@ -58,6 +58,11 @@ void TriggerCompleteCallBack::OnSendFinished( #if NAPI_VERSION >= 2 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; @@ -604,8 +611,8 @@ 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) { @@ -651,8 +658,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) { @@ -962,7 +969,7 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info) asyncCallbackInfo->wantAgentSecond = std::make_shared(*pWantAgentSecond); if (callBackMode) { - napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + napi_create_reference(env, argv[2], 1, &asyncCallbackInfo->callback[0]); } napi_value ret = NAPI_EqualWrap(env, info, callBackMode, asyncCallbackInfo); if (ret == nullptr) { diff --git a/ohos.build b/ohos.build index c19654580..747cde429 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 8bd0738df..60cfff6ba 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 0e8936727..bb8dc8169 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 52075fded..b4aba38fc 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 c2d476978..bfd654130 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 411098a4a..2425af407 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 611a9d713..55ef82b58 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 5fd3f4ee7..f41e65faf 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 1923774ba..30702e8fe 100644 --- a/services/ans/include/preferences_constant.h +++ b/services/ans/include/preferences_constant.h @@ -19,62 +19,58 @@ namespace OHOS { namespace Notification { -const static std::string kDisturbMode = "ans_disturbMode"; -const static std::string kEnable = "ans_notificationAll"; -const static std::string kBundleLabel = "label_ans_bundle_"; -const static std::string kUnderLine = "_"; -const static std::string kAnsBundle = "ans_bundle"; +const static std::string KEY_DISTURB_MODE = "ans_disturbMode"; +const static std::string KEY_ENABLE_ALL_NOTIFICATION = "ans_notificationAll"; +const static std::string KEY_BUNDLE_LABEL = "label_ans_bundle_"; +const static std::string KEY_UNDER_LINE = "_"; +const static std::string KEY_ANS_BUNDLE = "ans_bundle"; -const static std::string kBundleName = "name"; -const static std::string kBundleImportance = "importance"; -const static std::string kBundleShowBadge = "showBadge"; -const static std::string kBundleBadgeTotalNum = "badgeTotalNum"; -const static std::string kBundlePrivateAllowed = "privateAllowed"; -const static std::string kBundleEnableNotification = "enabledNotification"; +const static std::string KEY_BUNDLE_NAME = "name"; +const static std::string KEY_BUNDLE_IMPORTANCE = "importance"; +const static std::string KEY_BUNDLE_SHOW_BADGE = "showBadge"; +const static std::string KEY_BUNDLE_BADGE_TOTAL_NUM = "badgeTotalNum"; +const static std::string KEY_BUNDLE_PRIVATE_ALLOWED = "privateAllowed"; +const static std::string KEY_BUNDLE_ENABLE_NOTIFICATION = "enabledNotification"; -const static std::string kGroup = "group"; -const static std::string kGroupSize = "group_size"; -const static std::string kGroupId = "id"; -const static std::string kGroupName = "name"; -const static std::string kGroupDescription = "groupDescription"; -const static std::string kGroupDisable = "isDisable"; +const static std::string KEY_GROUP = "group"; +const static std::string KEY_GROUP_ID = "id"; +const static std::string KEY_GROUP_NAME = "name"; +const static std::string KEY_GROUP_DESCRIPTION = "groupDescription"; +const static std::string KEY_GROUP_DISABLE = "isDisable"; -const static std::string kSlot = "slot"; -const static std::string kSlotType = "type"; -const static std::string kSlotId = "id"; -const static std::string kSlotGroupId = "groupId"; -const static std::string kSlotName = "name"; -const static std::string kSlotDescription = "description"; -const static std::string kSlotLevel = "level"; -const static std::string kSlotShowBadge = "showBadge"; -const static std::string kSlotEnableLight = "enableLight"; -const static std::string kSlotEnableVrbration = "enableVibration"; -const static std::string kSlotLedLightColor = "ledLightColor"; -const static std::string kSlotLockscreenVisibleness = "lockscreenVisibleness"; -const static std::string kSlotSound = "sound"; -const static std::string kSlotVibrationSytle = "vibrationSytle"; -const static std::string kSlotEnableBypassDnd = "enableBypassDnd"; - -const static int32_t MAX_TIMES = 5; // 500ms -const static int32_t SLEEP_INTERVAL = 100 * 1000; // 100ms +const static std::string KEY_SLOT = "slot"; +const static std::string KEY_SLOT_TYPE = "type"; +const static std::string KEY_SLOT_ID = "id"; +const static std::string KEY_SLOT_GROUPID = "groupId"; +const static std::string KEY_SLOT_NAME = "name"; +const static std::string KEY_SLOT_DESCRIPTION = "description"; +const static std::string KEY_SLOT_LEVEL = "level"; +const static std::string KEY_SLOT_SHOW_BADGE = "showBadge"; +const static std::string KEY_SLOT_ENABLE_LIGHT = "enableLight"; +const static std::string KEY_SLOT_ENABLE_VRBRATION = "enableVibration"; +const static std::string KEY_SLOT_LED_LIGHT_COLOR = "ledLightColor"; +const static std::string KEY_SLOT_LOCKSCREEN_VISIBLENESS = "lockscreenVisibleness"; +const static std::string KEY_SLOT_SOUND = "sound"; +const static std::string KEY_SLOT_VIBRATION_STYLE = "vibrationSytle"; +const static std::string KEY_SLOT_ENABLE_BYPASS_DND = "enableBypassDnd"; // distributed database const std::string APP_ID = "advanced_notification_service"; const std::string STORE_ID = "local_db"; const static int BUNDLE_IMPORTANCE = 3; -const static bool BUNDLE_SHOW_BADGE = true; const static int BUNDLE_BADGE_TOTAL_NUM = 0; -const static int BUNDLE_PRIVATE_ALLOWED = true; +const static int BUNDLE_PRIVATE_ALLOWED = false; const static int BUNDLE_ENABLE_NOTIFICATION = true; +const static bool BUNDLE_SHOW_BADGE = false; enum class BundleType { - kBundleNameType = 1, - kBundleImportanceType, - kBundleShowBadgeType, - kBundleBadgeTotalNumType, - kBundlePrivateAllowedType, - kBundleEnableNotificationType, + BUNDLE_NAME_TYPE = 1, + BUNDLE_IMPORTANCE_TYPE, + BUNDLE_SHOW_BADGE_TYPE, + BUNDLE_BADGE_TOTAL_NUM_TYPE, + BUNDLE_PRIVATE_ALLOWED_TYPE, + BUNDLE_ENABLE_NOTIFICATION_TYPE, }; } // namespace Notification diff --git a/services/ans/include/system_event_subscriber.h b/services/ans/include/system_event_subscriber.h index 6b9a7a2ec..41b58c48d 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 12c76f049..878f46991 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -69,7 +69,7 @@ inline std::string GetClientBundleName() { std::string bundle; - uid_t callingUid = IPCSkeleton::GetCallingUid(); + int callingUid = IPCSkeleton::GetCallingUid(); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { @@ -83,11 +83,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 +97,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 +129,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 +168,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 +207,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 +321,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 +350,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 +377,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 +407,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 +526,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 +548,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 +569,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 +653,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 +711,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 +719,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 +759,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 +782,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 +799,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 +807,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 +819,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 +827,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 +839,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 +847,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 +872,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 +892,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 +991,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 +1029,7 @@ ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vectorPostSyncTask(std::bind([&]() { + notifications.clear(); for (auto record : notificationList_) { notifications.push_back(record->notification); } @@ -979,7 +1094,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 +1102,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 +1123,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 +1169,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; @@ -1116,6 +1254,9 @@ ErrCode AdvancedNotificationService::SetRecentNotificationCount(const std::strin } recentInfo_->recentCount = count; + while (recentInfo_->list.size() > recentInfo_->recentCount) { + recentInfo_->list.pop_back(); + } return ERR_OK; } @@ -1158,7 +1299,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 +1369,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 +1388,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 fca92739b..a02c7f20a 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 c6547f081..d5ebca7ba 100644 --- a/services/ans/src/disturb_filter.cpp +++ b/services/ans/src/disturb_filter.cpp @@ -61,6 +61,9 @@ ErrCode DisturbFilter::OnPublish(const std::shared_ptr &reco break; case NotificationConstant::DisturbMode::ALLOW_PRIORITY: break; + case NotificationConstant::DisturbMode::ALLOW_UNKNOWN: + // DO NOTHING + break; default: break; } diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 04d67ccf9..94175a711 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 98c595654..5cfc88b31 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 1202b2870..b77906aaa 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 6231cccb2..d59d1d181 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 f39e953f5..fedc523f8 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 9f368e08d..d66946c6c 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 2130524d9..959e85f80 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 a2288126e..8da3be02e 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 553e8fcbe..a13769aa9 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 b483171c2..90d0cbc84 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 000000000..147379994 --- /dev/null +++ b/services/ans/test/unittest/ans_ut_constant.h @@ -0,0 +1,35 @@ +/* + * 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 { + +namespace { +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 + +} // 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 b64140c3f..69f6b11f2 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 4c00d8a28..7ef21bb50 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 33a1c730b..d755b0151 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 4b7875b33..000000000 --- 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 39c56acab..aafcb8637 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 b7aa3f474..efde9364a 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 6c9526322..000000000 --- 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 3c2bc08da..42687ac92 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 4b580d297..4f9c78aa8 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 b2ad8c94a..36f044d30 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 5c3e5b45d..79f406980 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 376adab03..1d8582a23 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 d5a6b3cd5..c4367df55 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 e984e5df6..6472f5175 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 bc99a3773..b9a2f3535 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 5df99fa52..5fef8d274 100644 --- a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp @@ -30,12 +30,12 @@ BundleManagerHelper::~BundleManagerHelper() void BundleManagerHelper::OnRemoteDied(const wptr &object) {} -std::string BundleManagerHelper::GetBundleNameByUid(uid_t uid) +std::string BundleManagerHelper::GetBundleNameByUid(int uid) { return "bundleName"; } -bool BundleManagerHelper::IsSystemApp(uid_t uid) +bool BundleManagerHelper::IsSystemApp(int uid) { return true; } diff --git a/services/test/moduletest/mock/mock_ipc.cpp b/services/test/moduletest/mock/mock_ipc.cpp index 1acbe4a3f..6a93d95c4 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 e69de29bb..ab4862fc3 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 000000000..0018e05b8 --- /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 000000000..bc9a6fa50 --- /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 000000000..d745fbf31 --- /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 000000000..c54f270f7 --- /dev/null +++ b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp @@ -0,0 +1,132 @@ +/* + * 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}d", + 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); + APP_LOGI("====> ansSlotGroupTest:: the size of slots :" + "====> %{public}d", + groupTwo->GetSlots().size()); + 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 GIT binary patch literal 102831 zcmZ^qXEYqn_y5W2HHa2nM2+6-20;)ZL6oS`OVsG>+Gr8Ix3ENus6m1#tM}f!)mvC? zS!?b7KHn$*Xa9LHXYM?id*;6GId{(cj)5+K;1M1P2?-t^9+$#@)BhXfcm#NMo*s@a zP9mM z;^q26@y6%obgexg!0hR!?W*~o*2aw!u(@jmJc_Z?pOmg_F}vZMrKY_crNT-*Jeek0 z>TvwtjL`fsqwbm8;{f&qs@V5QGF8Jn`7%nPmXvN zcg5L)LOHdw8AWlKO1g>6E;}39vtNIHo!`x>{#+b2>{=TenaL(nmcI;zwf(pSA7%l)UQI@B~2I1K@dr<;Ex{>biE6CR)66W>#)XyGjTuA-d~ z!uwuZ4K}N=G7YZtnLlm;Q~Nxnz$unl6 zj@nn5p=bNuU6m3xu7FomY2O>;9#jiULYV{k09wBd zyJd*5iIDfJWs$_!XC~> zfe``(9QRKW17PEwKTmasV)c)r@bMw8W zP9O(>`ioI_lGqs)kw=9s8VW&7N?>9kA)4YCMRQVMUuUi4S(NG1RjJpc0Z#BfiqJ?1 zORvx-4^amc5+HF_OR=h~N}A*VFK0p>wq|%i@n7L2&e(}+0;qdDiFL$8`iO{BMmiH_ zGQ79|6E<*d=HUw~Tlgh~lFvhRYYGfG;D)&>GLC6+xKo6vps!Px8D&faih}?@z&V&v zj{zIsD*i!V=ZppqcD6IgeTCdfc+mnToc=p*Q6|#NlNt34Aj>pdRZhV=(3ub|jqm$t-*j{iqpvq=GMjXnG~1?DLrV9=zym?@AQfUt!FnVR>#o>n=*`Iu13L>?+? zq|~->`Tqg9z)}%u$khB5vXEpny^qg}H6-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j!^XUOlwe_k;aU*TT9X zMW9;ELeeKT`P%x*-)Z>i1(%_rZ!gD_NkZ@Z^lNB|?+*IcBOmBh@{E86|3*&#B}V=S z82c~D?ceS&u;x%e6BwY)k}d~0#rf3l#~qisUP&)o=4R{L-WkkIAJeyT+u|y#pm@Fx4(hQc4rbm#$f^g?&aH&YF-NhUlK!z){d;#};@jWW+{@Sj1kWKWvJsBkkp`Rg z8qN`B11wqG3k;wDXh8_b_#oo|pw<6MH~xJ`{r4e9wgnLPpF<8LSP;rT69~{if`2BE z;6dnr-487fsZXHP;rwqQO2 z_|c0sa#TLn3WE450HK3xkC>go7Ni%A9_wh>+0~-J0L09Hn(=3Fg%|}9eS|3029>aRr$CN%oY z;}WcJwu#(AxmL}ZkHU|`=KeoB7^pZmE-uF}*`!UKS$;!BNbp^jPeCTWWs-AlE-;SP z*!S$7(*j{in4n-*zvi)PK5A$n9)cI|)bCGTJ&B zZJiL?U&E1vMq4M8wN8L_E29%VTPNU(l(N=|g^`INa3IUb9J6(@{B-H8ofb!zC|cF4 zm)f^{Oq9Ip(DLKv+5hT{OX@$YlR&B#m{=KDJPh2J6d8U=b;g}MJz4tx=^u%`=6~NL z7qLoJ1l^R2w>y3NZH-_TP|59;h6=@#7Du=poUz63- zP%Fb+3`hWhhhu<3aAvxKQ%-(zwt|TfNG`yekx7I>gn@$tI9|-4X!YxA{$k*WGQ(|V z1_o{h7LYb1ker{FmYJ@XRh*yq?-ZtHtD*+5#DfUpxt3rqwxjsQz)=O+LF literal 0 HcmV?d00001 diff --git a/tools/dump/src/notification_shell_command.cpp b/tools/dump/src/notification_shell_command.cpp index 54fa0f512..a4c105699 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 -- Gitee From 154541043564acb6d365fe0553c6a6d23fc10e8e Mon Sep 17 00:00:00 2001 From: zhaoyuan Date: Wed, 15 Sep 2021 21:42:21 +0000 Subject: [PATCH 2/2] update pixelmap and test code Signed-off-by: zhaoyuan --- frameworks/ans/core/BUILD.gn | 2 + .../core/common/include/ans_const_define.h | 2 + .../core/common/include/ans_inner_errors.h | 3 +- .../ans/core/include/ans_manager_proxy.h | 4 +- .../ans/core/include/ans_manager_stub.h | 4 +- .../ans/core/include/ans_notification.h | 7 + frameworks/ans/core/src/ans_manager_proxy.cpp | 4 +- frameworks/ans/core/src/ans_manager_stub.cpp | 4 +- frameworks/ans/core/src/ans_notification.cpp | 106 +++ frameworks/ans/native/BUILD.gn | 2 + frameworks/ans/native/src/message_user.cpp | 35 +- .../native/src/notification_action_button.cpp | 61 +- .../src/notification_picture_content.cpp | 42 +- .../ans/native/src/notification_request.cpp | 92 +-- frameworks/ans/test/moduletest/BUILD.gn | 3 + .../test/moduletest/ans_fw_module_test.cpp | 120 ++++ .../ans_innerkits_module_publish_test.cpp | 60 +- .../ans_innerkits_module_slot_test.cpp | 1 - .../moduletest/mock/mock_bundle_manager.cpp | 7 +- .../moduletest/mock/mock_event_handler.cpp | 194 +++-- .../completed_dispatcher_test.cpp | 6 +- .../pending_want_test/pending_want_test.cpp | 36 +- .../ans/native/include/message_user.h | 9 +- .../include/notification_action_button.h | 11 +- .../include/notification_picture_content.h | 9 +- .../ans/native/include/notification_request.h | 15 +- .../native/include/notification_user_input.h | 2 - interfaces/kits/js/@ohos.notification.d.ts | 84 +-- interfaces/kits/js/@ohos.wantAgent.d.ts | 80 +-- .../notification/notificationActionButton.ts | 7 +- .../js/notification/notificationContent.d.ts | 18 +- .../js/notification/notificationRequest.d.ts | 11 +- .../js/notification/notificationSlot.d.ts | 4 +- .../js/notification/notificationSorting.d.ts | 4 +- .../notification/notificationSortingMap.d.ts | 4 +- .../notification/notificationSubscribeInfo.ts | 4 +- .../notification/notificationSubscriber.d.ts | 24 +- interfaces/kits/napi/ans/BUILD.gn | 2 + interfaces/kits/napi/ans/include/get_active.h | 2 +- interfaces/kits/napi/ans/include/slot.h | 6 +- interfaces/kits/napi/ans/src/common.cpp | 667 ++++++------------ .../kits/napi/ans/src/display_badge.cpp | 4 +- .../kits/napi/ans/src/enable_notification.cpp | 4 +- interfaces/kits/napi/ans/src/get_active.cpp | 10 +- interfaces/kits/napi/ans/src/init.cpp | 8 +- interfaces/kits/napi/ans/src/remove.cpp | 4 +- interfaces/kits/napi/ans/src/slot.cpp | 104 +-- interfaces/kits/napi/ans/src/subscribe.cpp | 60 +- .../kits/napi/wantagent/napi_want_agent.cpp | 99 +-- .../kits/napi/wantagent/napi_want_agent.h | 11 + services/ans/BUILD.gn | 1 + .../ans/include/notification_preferences.h | 6 +- .../notification_preferences_database.h | 2 +- .../include/notification_preferences_info.h | 10 +- .../ans/src/advanced_notification_service.cpp | 62 +- services/ans/src/notification_preferences.cpp | 17 +- .../src/notification_preferences_database.cpp | 130 ++-- services/ans/test/unittest/BUILD.gn | 1 + .../advanced_notification_service_test.cpp | 134 +++- services/ans/test/unittest/ans_ut_constant.h | 5 - .../mock/include/mock_single_kv_store.h | 178 +---- services/ans/test/unittest/mock/mock_ipc.cpp | 2 +- .../unittest/mock/mock_single_kv_store.cpp | 132 +--- services/test/moduletest/BUILD.gn | 1 + services/test/moduletest/ans_module_test.cpp | 60 +- .../mock/distributed_kv_data_manager.cpp | 1 - .../mock/include/mock_single_kv_store.h | 178 +---- .../moduletest/mock/mock_bundle_manager.cpp | 5 +- .../moduletest/mock/mock_bundle_mgr_proxy.cpp | 4 +- .../moduletest/mock/mock_event_handler.cpp | 194 +++-- .../moduletest/mock/mock_single_kv_store.cpp | 165 +---- .../include/ans_slotgroup_test.h | 2 +- .../src/ans_slotgroup_test.cpp | 48 +- tools/dump/src/notification_shell_command.cpp | 23 +- 74 files changed, 1463 insertions(+), 1960 deletions(-) diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index f630d47e4..492968520 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -27,6 +27,7 @@ config("public_ans_core_config") { "${core_path}/include", "${interfaces_path}/innerkits/ans/native/include", "${interfaces_path}/innerkits/wantAgent/include", + "//foundation/multimedia/image_standard/interfaces/innerkits/include", "//utils/native/base/include", "//third_party/jsoncpp/include", ] @@ -74,6 +75,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", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index 61e08768b..353899e52 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -25,6 +25,8 @@ constexpr uint32_t MAX_ACTIVE_NUM_PERAPP = 100; constexpr uint32_t MAX_ACTIVE_NUM_PERSECOND = 10; constexpr uint32_t MAX_SLOT_NUM = 5; constexpr uint32_t MAX_SLOT_GROUP_NUM = 4; +constexpr uint32_t MAX_ICON_SIZE = 50 * 1024; +constexpr uint32_t MAX_PICTURE_SIZE = 2 * 1024 * 1024; } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/common/include/ans_inner_errors.h b/frameworks/ans/core/common/include/ans_inner_errors.h index 1c59b864a..3552497d1 100644 --- a/frameworks/ans/core/common/include/ans_inner_errors.h +++ b/frameworks/ans/core/common/include/ans_inner_errors.h @@ -58,7 +58,8 @@ enum ErrorCode : uint32_t { ERR_ANS_NOTIFICATION_NOT_EXISTS, ERR_ANS_NOTIFICATION_IS_UNREMOVABLE, ERR_ANS_OVER_MAX_ACITVE_PERSECOND, - + ERR_ANS_ICON_OVER_SIZE, + ERR_ANS_PICTURE_OVER_SIZE, ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED, ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST, ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST, diff --git a/frameworks/ans/core/include/ans_manager_proxy.h b/frameworks/ans/core/include/ans_manager_proxy.h index b90bc8e95..c09e7b818 100644 --- a/frameworks/ans/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -98,10 +98,10 @@ public: private: ErrCode InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); - template + template bool WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &data); - template + template bool ReadParcelableVector(std::vector> &parcelableInfos, MessageParcel &reply, ErrCode &result); static inline BrokerDelegator delegator_; }; diff --git a/frameworks/ans/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h index 4bf53b386..45006dc32 100644 --- a/frameworks/ans/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -155,10 +155,10 @@ private: ErrCode HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleShellDump(MessageParcel &data, MessageParcel &reply); - template + template bool WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result); - template + template bool ReadParcelableVector(std::vector> &parcelableInfos, MessageParcel &data); }; } // namespace Notification diff --git a/frameworks/ans/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h index c21ec347b..100bb3894 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -618,6 +618,13 @@ private: */ bool CanPublishMediaContent(const NotificationRequest &request) const; + /** + * Check whether the picture size exceeds the limit + * + * @return the ErrCode. + */ + ErrCode CheckImageSize(const NotificationRequest &request); + private: std::mutex mutex_; sptr ansManagerProxy_; diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index bbfa3b448..c4e3742a9 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -1797,7 +1797,7 @@ ErrCode AnsManagerProxy::InnerTransact(uint32_t code, MessageOption &flags, Mess } } -template +template bool AnsManagerProxy::WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &data) { if (!data.WriteInt32(parcelableVector.size())) { @@ -1814,7 +1814,7 @@ bool AnsManagerProxy::WriteParcelableVector(const std::vector> &parcelab return true; } -template +template bool AnsManagerProxy::ReadParcelableVector(std::vector> &parcelableInfos, MessageParcel &reply, ErrCode &result) { if (!reply.ReadInt32(result)) { diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 1185b647f..7f97ff1db 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -1160,7 +1160,7 @@ ErrCode AnsManagerStub::HandleShellDump(MessageParcel &data, MessageParcel &repl return ERR_OK; } -template +template bool AnsManagerStub::WriteParcelableVector( const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result) { @@ -1183,7 +1183,7 @@ bool AnsManagerStub::WriteParcelableVector( return true; } -template +template bool AnsManagerStub::ReadParcelableVector(std::vector> &parcelableInfos, MessageParcel &data) { int32_t infoSize = 0; diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index 5bf4a26c3..fd203213c 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -14,6 +14,8 @@ */ #include "ans_notification.h" +#include +#include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" #include "iservice_registry.h" @@ -188,6 +190,12 @@ ErrCode AnsNotification::PublishNotification(const std::string &label, const Not return ERR_ANS_INVALID_PARAM; } + ErrCode checkErr = CheckImageSize(request); + if (checkErr != ERR_OK) { + ANS_LOGE("The size of one picture exceeds the limit"); + return checkErr; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; @@ -214,6 +222,12 @@ ErrCode AnsNotification::PublishNotification(const NotificationRequest &request, return ERR_ANS_INVALID_PARAM; } + ErrCode checkErr = CheckImageSize(request); + if (checkErr != ERR_OK) { + ANS_LOGE("The size of one picture exceeds the limit"); + return checkErr; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; @@ -328,6 +342,12 @@ ErrCode AnsNotification::PublishNotificationAsBundle( return ERR_ANS_INVALID_PARAM; } + ErrCode checkErr = CheckImageSize(request); + if (checkErr != ERR_OK) { + ANS_LOGE("The size of one picture exceeds the limit"); + return checkErr; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; @@ -777,5 +797,91 @@ bool AnsNotification::CanPublishMediaContent(const NotificationRequest &request) return true; } + +ErrCode AnsNotification::CheckImageSize(const NotificationRequest &request) +{ + auto littleIcon = request.GetLittleIcon(); + if (littleIcon && (static_cast(littleIcon->GetByteCount()) > MAX_ICON_SIZE)) { + ANS_LOGE("The size of little icon exceeds limit"); + return ERR_ANS_ICON_OVER_SIZE; + } + + auto bigIcon = request.GetBigIcon(); + if (bigIcon && (static_cast(bigIcon->GetByteCount()) > MAX_ICON_SIZE)) { + ANS_LOGE("The size of big icon exceeds limit"); + return ERR_ANS_ICON_OVER_SIZE; + } + + auto content = request.GetContent(); + if (content) { + auto basicContent = request.GetContent()->GetNotificationContent(); + if (basicContent) { + auto contentType = request.GetNotificationType(); + switch (contentType) { + case NotificationContent::Type::CONVERSATION: { + auto conversationalContent = std::static_pointer_cast(basicContent); + + auto picture = conversationalContent->GetMessageUser().GetPixelMap(); + if (picture && (static_cast(picture->GetByteCount()) > MAX_ICON_SIZE)) { + ANS_LOGE("The size of picture in conversationalContent exceeds limit"); + return ERR_ANS_ICON_OVER_SIZE; + } + + auto messages = conversationalContent->GetAllConversationalMessages(); + for (auto &msg : messages) { + if (!msg) { + continue; + } + + auto img = msg->GetSender().GetPixelMap(); + if (img && (static_cast(img->GetByteCount()) > MAX_ICON_SIZE)) { + ANS_LOGE("The size of picture in conversationalMessage exceeds limit"); + return ERR_ANS_ICON_OVER_SIZE; + } + } + } break; + case NotificationContent::Type::PICTURE: { + auto pictureContent = std::static_pointer_cast(basicContent); + + auto bigPicture = pictureContent->GetBigPicture(); + if (bigPicture && (static_cast(bigPicture->GetByteCount()) > MAX_PICTURE_SIZE)) { + ANS_LOGE("The size of big picture exceeds limit"); + return ERR_ANS_PICTURE_OVER_SIZE; + } + } break; + default: + break; + } + } + } + + auto buttons = request.GetActionButtons(); + for (auto &btn : buttons) { + if (!btn) { + continue; + } + + auto icon = btn->GetIcon(); + if (icon && (static_cast(icon->GetByteCount()) > MAX_ICON_SIZE)) { + ANS_LOGE("The size of icon in actionButton exceeds limit"); + return ERR_ANS_ICON_OVER_SIZE; + } + } + + auto users = request.GetMessageUsers(); + for (auto &user : users) { + if (!user) { + continue; + } + + auto icon = user->GetPixelMap(); + if (icon && (static_cast(icon->GetByteCount()) > MAX_ICON_SIZE)) { + ANS_LOGE("The size of picture in messageUser exceeds limit"); + return ERR_ANS_ICON_OVER_SIZE; + } + } + + return ERR_OK; +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn index e8c5dae33..502edd929 100755 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -33,6 +33,7 @@ ohos_shared_library("ans_innerkits") { include_dirs = [ "${interfaces_path}/ans/native/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/multimedia/image_standard/interfaces/innerkits/include", "//utils/system/safwk/native/include", "//third_party/jsoncpp/include", ] @@ -75,6 +76,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", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//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 161d72387..4e1632abd 100644 --- a/frameworks/ans/native/src/message_user.cpp +++ b/frameworks/ans/native/src/message_user.cpp @@ -14,6 +14,7 @@ */ #include "message_user.h" +#include "ans_log_wrapper.h" namespace OHOS { namespace Notification { @@ -45,12 +46,12 @@ std::string MessageUser::GetName() const return name_; } -void MessageUser::SetPixelMap(const std::shared_ptr &pixelMap) +void MessageUser::SetPixelMap(const std::shared_ptr &pixelMap) { pixelMap_ = pixelMap; } -const std::shared_ptr MessageUser::GetPixelMap() const +const std::shared_ptr MessageUser::GetPixelMap() const { return pixelMap_; } @@ -98,30 +99,50 @@ std::string MessageUser::Dump() const bool MessageUser::Marshalling(Parcel &parcel) const { if (!parcel.WriteString(key_)) { + ANS_LOGE("Failed to write key"); return false; } if (!parcel.WriteString(name_)) { + ANS_LOGE("Failed to write name"); return false; } if (!parcel.WriteBool(isMachine_)) { + ANS_LOGE("Failed to write isMachine"); return false; } if (!parcel.WriteBool(isUserImportant_)) { + ANS_LOGE("Failed to write isUserImportant"); return false; } if (uri_.ToString().empty()) { if (!parcel.WriteInt32(VALUE_NULL)) { + ANS_LOGE("Failed to write VALUE_NULL"); return false; } } else { if (!parcel.WriteInt32(VALUE_OBJECT)) { + ANS_LOGE("Failed to write VALUE_OBJECT"); return false; } if (!parcel.WriteString((uri_.ToString()))) { + ANS_LOGE("Failed to write uri"); + return false; + } + } + + bool valid = pixelMap_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether pixelMap is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(pixelMap_.get())) { + ANS_LOGE("Failed to write pixelMap"); return false; } } @@ -138,6 +159,7 @@ bool MessageUser::ReadFromParcel(Parcel &parcel) int empty = VALUE_NULL; if (!parcel.ReadInt32(empty)) { + ANS_LOGE("Failed to read VALUE"); return false; } @@ -145,6 +167,15 @@ bool MessageUser::ReadFromParcel(Parcel &parcel) uri_ = Uri((parcel.ReadString())); } + bool valid = parcel.ReadBool(); + if (valid) { + pixelMap_ = std::shared_ptr(parcel.ReadParcelable()); + if (!pixelMap_) { + ANS_LOGE("Failed to read pixelMap"); + return false; + } + } + return true; } diff --git a/frameworks/ans/native/src/notification_action_button.cpp b/frameworks/ans/native/src/notification_action_button.cpp index 62cf80e18..b0c004d71 100644 --- a/frameworks/ans/native/src/notification_action_button.cpp +++ b/frameworks/ans/native/src/notification_action_button.cpp @@ -20,7 +20,7 @@ namespace OHOS { namespace Notification { -std::shared_ptr NotificationActionButton::Create(const std::shared_ptr &icon, +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> &mimeTypeOnlyInputs, @@ -55,8 +55,15 @@ std::shared_ptr NotificationActionButton::Create(const } } - auto pActionButton = new (std::nothrow) NotificationActionButton( - icon, title, wantAgent, realExtras, semanticActionButton, autoCreatedReplies, onlyInputs, textInputs, isContextual); + auto pActionButton = new (std::nothrow) NotificationActionButton(icon, + title, + wantAgent, + realExtras, + semanticActionButton, + autoCreatedReplies, + onlyInputs, + textInputs, + isContextual); if (pActionButton == nullptr) { ANS_LOGE("create NotificationActionButton object failed"); return {}; @@ -79,10 +86,10 @@ std::shared_ptr NotificationActionButton::Create( 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, +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), @@ -95,7 +102,7 @@ NotificationActionButton::NotificationActionButton(const std::shared_ptr NotificationActionButton::GetIcon() const +const std::shared_ptr NotificationActionButton::GetIcon() const { return icon_; } @@ -217,18 +224,18 @@ bool NotificationActionButton::Marshalling(Parcel &parcel) const bool valid{false}; - // valid = icon_ ? true : false; - // if (!parcel.WriteBool(valid)) { - // ANS_LOGE("Failed to write the flag which indicate whether icon is null"); - // return false; - // } + valid = icon_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether icon is null"); + return false; + } - // if (valid) { - // if (!parcel.WriteParcelable(icon_.get())) { - // ANS_LOGE("Failed to write icon"); - // return false; - // } - // } + if (valid) { + if (!parcel.WriteParcelable(icon_.get())) { + ANS_LOGE("Failed to write icon"); + return false; + } + } valid = wantAgent_ ? true : false; if (!parcel.WriteBool(valid)) { @@ -305,14 +312,14 @@ bool NotificationActionButton::ReadFromParcel(Parcel &parcel) bool valid{false}; - // valid = parcel.ReadBool(); - // if (valid) { - // icon_ = std::shared_ptr(parcel.ReadParcelable()); - // if (!icon_) { - // ANS_LOGE("Failed to read icon"); - // return false; - // } - // } + valid = parcel.ReadBool(); + if (valid) { + icon_ = std::shared_ptr(parcel.ReadParcelable()); + if (!icon_) { + ANS_LOGE("Failed to read icon"); + return false; + } + } valid = parcel.ReadBool(); if (valid) { diff --git a/frameworks/ans/native/src/notification_picture_content.cpp b/frameworks/ans/native/src/notification_picture_content.cpp index 385e3c467..9138938cb 100644 --- a/frameworks/ans/native/src/notification_picture_content.cpp +++ b/frameworks/ans/native/src/notification_picture_content.cpp @@ -38,12 +38,12 @@ std::string NotificationPictureContent::GetBriefText() const return briefText_; } -void NotificationPictureContent::SetBigPicture(const std::shared_ptr &bigPicture) +void NotificationPictureContent::SetBigPicture(const std::shared_ptr &bigPicture) { bigPicture_ = bigPicture; } -const std::shared_ptr NotificationPictureContent::GetBigPicture() const +const std::shared_ptr NotificationPictureContent::GetBigPicture() const { return bigPicture_; } @@ -71,18 +71,18 @@ bool NotificationPictureContent::Marshalling(Parcel &parcel) const return false; } - // auto valid = bigPicture_ ? true : false; - // if (!parcel.WriteBool(valid)) { - // ANS_LOGE("Failed to write the flag which indicate whether bigPicture is null"); - // return false; - // } + auto valid = bigPicture_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether bigPicture is null"); + return false; + } - // if (valid) { - // if (!parcel.WriteParcelable(bigPicture_.get())) { - // ANS_LOGE("Failed to write bigPicture"); - // return false; - // } - // } + if (valid) { + if (!parcel.WriteParcelable(bigPicture_.get())) { + ANS_LOGE("Failed to write bigPicture"); + return false; + } + } return true; } @@ -115,14 +115,14 @@ bool NotificationPictureContent::ReadFromParcel(Parcel &parcel) return false; } - // auto valid = parcel.ReadBool(); - // if (valid) { - // bigPicture_ = std::shared_ptr(parcel.ReadParcelable()); - // if (!bigPicture_) { - // ANS_LOGE("Failed to read bigPicture"); - // return false; - // } - // } + auto valid = parcel.ReadBool(); + if (valid) { + bigPicture_ = std::shared_ptr(parcel.ReadParcelable()); + if (!bigPicture_) { + ANS_LOGE("Failed to read bigPicture"); + return false; + } + } return true; } diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index 809de5494..02c7e1e4c 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -344,22 +344,22 @@ int64_t NotificationRequest::GetAutoDeletedTime() const return autoDeletedTime_; } -void NotificationRequest::SetLittleIcon(const std::shared_ptr &littleIcon) +void NotificationRequest::SetLittleIcon(const std::shared_ptr &littleIcon) { littleIcon_ = littleIcon; } -const std::shared_ptr NotificationRequest::GetLittleIcon() const +const std::shared_ptr NotificationRequest::GetLittleIcon() const { return littleIcon_; } -void NotificationRequest::SetBigIcon(const std::shared_ptr &bigIcon) +void NotificationRequest::SetBigIcon(const std::shared_ptr &bigIcon) { bigIcon_ = bigIcon; } -const std::shared_ptr NotificationRequest::GetBigIcon() const +const std::shared_ptr NotificationRequest::GetBigIcon() const { return bigIcon_; } @@ -1002,31 +1002,31 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const } } - // valid = littleIcon_ ? true : false; - // if (!parcel.WriteBool(valid)) { - // ANS_LOGE("Failed to write the flag which indicate whether littleIcon is null"); - // return false; - // } - - // if (valid) { - // if (!parcel.WriteParcelable(littleIcon_.get())) { - // ANS_LOGE("Failed to write littleIcon"); - // return false; - // } - // } - - // valid = bigIcon_ ? true : false; - // if (!parcel.WriteBool(valid)) { - // ANS_LOGE("Failed to write the flag which indicate whether bigIcon is null"); - // return false; - // } - - // if (valid) { - // if (!parcel.WriteParcelable(bigIcon_.get())) { - // ANS_LOGE("Failed to write bigIcon"); - // return false; - // } - // } + valid = littleIcon_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether littleIcon is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(littleIcon_.get())) { + ANS_LOGE("Failed to write littleIcon"); + return false; + } + } + + valid = bigIcon_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether bigIcon is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(bigIcon_.get())) { + ANS_LOGE("Failed to write bigIcon"); + return false; + } + } valid = notificationContent_ ? true : false; if (!parcel.WriteBool(valid)) { @@ -1215,23 +1215,23 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) } } - // valid = parcel.ReadBool(); - // if (valid) { - // littleIcon_ = std::shared_ptr(parcel.ReadParcelable()); - // if (!littleIcon_) { - // ANS_LOGE("Failed to read littleIcon"); - // return false; - // } - // } - - // valid = parcel.ReadBool(); - // if (valid) { - // bigIcon_ = std::shared_ptr(parcel.ReadParcelable()); - // if (!bigIcon_) { - // ANS_LOGE("Failed to read bigIcon"); - // return false; - // } - // } + valid = parcel.ReadBool(); + if (valid) { + littleIcon_ = std::shared_ptr(parcel.ReadParcelable()); + if (!littleIcon_) { + ANS_LOGE("Failed to read littleIcon"); + return false; + } + } + + valid = parcel.ReadBool(); + if (valid) { + bigIcon_ = std::shared_ptr(parcel.ReadParcelable()); + if (!bigIcon_) { + ANS_LOGE("Failed to read bigIcon"); + return false; + } + } valid = parcel.ReadBool(); if (valid) { diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index db73e3179..8046c8d17 100755 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -102,6 +102,7 @@ ohos_moduletest("ans_fw_module_test") { "//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", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gtest_main", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", @@ -154,6 +155,7 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/dfx", + "//foundation/multimedia/image_standard/interfaces/innerkits/include", "//developtools/bytrace_standard/interfaces/innerkits/native/include", ] @@ -182,6 +184,7 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "//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", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index 04e1b237e..ba6edb7ff 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -36,6 +36,8 @@ #include "system_ability_definition.h" using namespace testing::ext; +using namespace OHOS::Media; + namespace OHOS { namespace Notification { @@ -54,6 +56,8 @@ enum class SubscriberEventType { class SubscriberEvent { public: + virtual ~SubscriberEvent() + {} SubscriberEventType GetType() { return type_; @@ -68,6 +72,8 @@ protected: class OnSubscribeResultEvent : public SubscriberEvent { public: + ~OnSubscribeResultEvent() override + {} OnSubscribeResultEvent(NotificationConstant::SubscribeResult result) : SubscriberEvent(SubscriberEventType::ON_SUBSCRIBERESULT), subscribeResult_(result) {} @@ -1060,5 +1066,119 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_PublishVibrationNotification_00100, Function SleepForFC(); } +inline std::shared_ptr MakePixelMap(int32_t width, int32_t height) +{ + const int32_t PIXEL_BYTES = 4; + std::shared_ptr pixelMap = std::make_shared(); + ImageInfo info; + info.size.width = width; + info.size.height = height; + info.pixelFormat = PixelFormat::ARGB_8888; + info.colorSpace = ColorSpace::SRGB; + pixelMap->SetImageInfo(info); + int32_t rowDataSize = width * PIXEL_BYTES; + uint32_t bufferSize = rowDataSize * height; + void *buffer = malloc(bufferSize); + EXPECT_NE(buffer, nullptr); + pixelMap->SetPixelsAddr(buffer, nullptr, bufferSize, AllocatorType::HEAP_ALLOC, nullptr); + return pixelMap; +} + +/** + * + * @tc.number : ANS_FW_MT_PublishNotificationWithPixelMap_00100 + * @tc.name : + * @tc.desc : Publish a notification with pixelMap. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_PublishNotificationWithPixelMap_00100, Function | MediumTest | Level1) +{ + const int BIG_PICTURE_WIDTH = 400; + const int BIG_PICTURE_HEIGHT = 300; + const int ICON_SIZE = 36; + + NotificationRequest req; + req.SetSlotType(NotificationConstant::SlotType::OTHER); + req.SetLabel("label"); + std::shared_ptr pictureContent = std::make_shared(); + EXPECT_NE(pictureContent, nullptr); + pictureContent->SetText("notification text"); + pictureContent->SetTitle("notification title"); + std::shared_ptr bigPicture = MakePixelMap(BIG_PICTURE_WIDTH, BIG_PICTURE_HEIGHT); + EXPECT_NE(bigPicture, nullptr); + pictureContent->SetBigPicture(bigPicture); + std::shared_ptr content = std::make_shared(pictureContent); + EXPECT_NE(content, nullptr); + req.SetContent(content); + std::shared_ptr littleIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req.SetLittleIcon(littleIcon); + std::shared_ptr bigIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req.SetBigIcon(bigIcon); + EXPECT_EQ(NotificationHelper::PublishNotification(req), ERR_OK); +} + +/** + * + * @tc.number : ANS_FW_MT_PublishNotificationWithPixelMap_00200 + * @tc.name : + * @tc.desc : Publish a notification with oversize pixelMap. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_PublishNotificationWithPixelMap_00200, Function | MediumTest | Level1) +{ + const int BIG_PICTURE_WIDTH = 1024; + const int BIG_PICTURE_HEIGHT = 1024; + const int ICON_SIZE = 36; + + NotificationRequest req; + req.SetSlotType(NotificationConstant::SlotType::OTHER); + req.SetLabel("label"); + std::shared_ptr pictureContent = std::make_shared(); + EXPECT_NE(pictureContent, nullptr); + pictureContent->SetText("notification text"); + pictureContent->SetTitle("notification title"); + std::shared_ptr bigPicture = MakePixelMap(BIG_PICTURE_WIDTH, BIG_PICTURE_HEIGHT); + EXPECT_NE(bigPicture, nullptr); + pictureContent->SetBigPicture(bigPicture); + std::shared_ptr content = std::make_shared(pictureContent); + EXPECT_NE(content, nullptr); + req.SetContent(content); + std::shared_ptr littleIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req.SetLittleIcon(littleIcon); + std::shared_ptr bigIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req.SetBigIcon(bigIcon); + EXPECT_EQ(NotificationHelper::PublishNotification(req), (int)ERR_ANS_PICTURE_OVER_SIZE); +} + +/** + * + * @tc.number : ANS_FW_MT_PublishNotificationWithPixelMap_00300 + * @tc.name : + * @tc.desc : Publish a notification with oversize pixelMap. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_PublishNotificationWithPixelMap_00300, Function | MediumTest | Level1) +{ + const int BIG_PICTURE_WIDTH = 400; + const int BIG_PICTURE_HEIGHT = 300; + const int ICON_SIZE = 256; + + NotificationRequest req; + req.SetSlotType(NotificationConstant::SlotType::OTHER); + req.SetLabel("label"); + std::shared_ptr pictureContent = std::make_shared(); + EXPECT_NE(pictureContent, nullptr); + pictureContent->SetText("notification text"); + pictureContent->SetTitle("notification title"); + std::shared_ptr bigPicture = MakePixelMap(BIG_PICTURE_WIDTH, BIG_PICTURE_HEIGHT); + EXPECT_NE(bigPicture, nullptr); + pictureContent->SetBigPicture(bigPicture); + std::shared_ptr content = std::make_shared(pictureContent); + EXPECT_NE(content, nullptr); + req.SetContent(content); + std::shared_ptr littleIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req.SetLittleIcon(littleIcon); + std::shared_ptr bigIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req.SetBigIcon(bigIcon); + EXPECT_EQ(NotificationHelper::PublishNotification(req), (int)ERR_ANS_ICON_OVER_SIZE); +} + } // namespace Notification } // 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 index fbf6f3116..85404dd1b 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -57,6 +57,10 @@ const int32_t CASE_FOURTEEN = 14; const int32_t CASE_FIFTEEN = 15; const int32_t CASE_SIXTEEN = 16; const int32_t CALLING_UID = 9999; + +const int32_t PIXEL_MAP_TEST_WIDTH = 1024; +const int32_t PIXEL_MAP_TEST_HEIGHT = 1024; + std::mutex g_subscribe_mtx; std::mutex g_consumed_mtx; std::mutex g_unsubscribe_mtx; @@ -163,8 +167,8 @@ private: } } EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); - for (auto it : notificationRequest.GetNotificationUserInputHistory()) { - EXPECT_EQ("style", it); + for (auto str : notificationRequest.GetNotificationUserInputHistory()) { + EXPECT_EQ("style", str); } EXPECT_EQ("bundleName", notificationRequest.GetOwnerBundleName()); EXPECT_EQ("bundleName", notificationRequest.GetCreatorBundleName()); @@ -173,18 +177,31 @@ private: if (NotificationRequestPtr != nullptr) { EXPECT_EQ("ANS_Interface_MT_Publish_00100_REQUEST", NotificationRequestPtr->GetLabel()); } + + // pixelmap + auto littleIcon = notificationRequest.GetLittleIcon(); + Media::ImageInfo outImageInfo; + littleIcon->GetImageInfo(outImageInfo); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00100 :: littleIcon :: width : " << outImageInfo.size.width; + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00100 :: littleIcon :: height : " << outImageInfo.size.height; + + EXPECT_EQ(outImageInfo.size.width, PIXEL_MAP_TEST_WIDTH); + EXPECT_EQ(outImageInfo.size.height, PIXEL_MAP_TEST_HEIGHT); + EXPECT_EQ(outImageInfo.pixelFormat, Media::PixelFormat::ALPHA_8); + EXPECT_EQ(outImageInfo.colorSpace, Media::ColorSpace::SRGB); + 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()); + for (auto user : messageUser) { + if (user != nullptr) { + EXPECT_EQ("ANS_Interface_MT_Publish_00100_Message_User", user->GetName()); + EXPECT_EQ("key", user->GetKey()); + EXPECT_EQ(nullptr, user->GetPixelMap()); + EXPECT_EQ(Uri("."), user->GetUri()); + EXPECT_EQ(false, user->IsMachine()); + EXPECT_EQ(false, user->IsUserImportant()); } } } @@ -352,6 +369,11 @@ class CompletedCallbackTest : public WantAgent::CompletedCallback { void OnSendFinished( const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) { + (void)want; + (void)resultCode; + (void)resultData; + (void)resultExtras; + g_send_finished_mtx.unlock(); OnWantReceived = true; } @@ -480,8 +502,22 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00100, Function std::shared_ptr requestPtr = std::make_shared(); requestPtr->SetLabel("ANS_Interface_MT_Publish_00100_REQUEST"); req.SetPublicNotification(requestPtr); - req.SetBigIcon(nullptr); - req.SetLittleIcon(nullptr); + + // pixelmap + auto pixelMap = std::make_shared(); + Media::ImageInfo imageInfo; + imageInfo.size.width = PIXEL_MAP_TEST_WIDTH; + imageInfo.size.height = PIXEL_MAP_TEST_HEIGHT; + imageInfo.pixelFormat = Media::PixelFormat::ALPHA_8; + imageInfo.colorSpace = Media::ColorSpace::SRGB; + pixelMap->SetImageInfo(imageInfo); + int32_t rowDataSize = (PIXEL_MAP_TEST_WIDTH + 3) / 4 * 4; + uint32_t bufferSize = rowDataSize * PIXEL_MAP_TEST_HEIGHT; + void *buffer = malloc(bufferSize); + pixelMap->SetPixelsAddr(buffer, nullptr, bufferSize, Media::AllocatorType::HEAP_ALLOC, nullptr); + + req.SetBigIcon(pixelMap); + req.SetLittleIcon(pixelMap); std::shared_ptr messageUserPtr = std::make_shared(); messageUserPtr->SetName("ANS_Interface_MT_Publish_00100_Message_User"); messageUserPtr->SetKey("key"); diff --git a/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp index 0433b2967..e7ced9336 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp @@ -118,7 +118,6 @@ HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00100, Fu */ 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"); diff --git a/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp b/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp index 340c592c3..98fd912f3 100644 --- a/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp @@ -13,12 +13,15 @@ * limitations under the License. */ +#include "mock_bundle_manager.h" #include "ability_info.h" #include "application_info.h" -#include "mock_bundle_manager.h" namespace OHOS { namespace AppExecFwk { + +constexpr int SYSTEM_APP_UUID = 1000; + void MockBundleMgrService::MockSetIsSystemApp(bool isSystemApp) { isSystemAppMock_ = true; @@ -30,7 +33,7 @@ bool MockBundleMgrService::CheckIsSystemAppByUid(const int uid) if (isSystemAppMock_) { return isSystemApp_; } - return (uid < 1000) ? false : true; + return (uid < SYSTEM_APP_UUID) ? false : true; } int MockBundleMgrService::CheckPermission(const std::string &bundleName, const std::string &permission) diff --git a/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp b/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp index 4fcdd4a2c..12a7f65b9 100644 --- a/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp @@ -17,108 +17,94 @@ #include "event_handler_utils.h" #include -namespace OHOS +namespace OHOS { +namespace AppExecFwk { + +std::shared_ptr EventHandler::Current() +{ + const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); + return wp.lock(); +} + +EventHandler::EventHandler(const std::shared_ptr &runner) : eventRunner_(runner) +{} + +EventHandler::~EventHandler() +{} + +bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Priority priority) +{ + std::function callback = event->GetTaskCallback(); + callback(); + return true; +} + +bool EventHandler::SendTimingEvent(InnerEvent::Pointer &event, int64_t taskTime, Priority priority) +{ + return true; +} + +bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority) +{ + std::function callback = event->GetTaskCallback(); + callback(); + return true; +} + +void EventHandler::RemoveAllEvents() +{} + +void EventHandler::RemoveEvent(uint32_t innerEventId) +{} + +void EventHandler::RemoveEvent(uint32_t innerEventId, int64_t param) +{} + +void EventHandler::RemoveTask(const std::string &name) +{} + +ErrCode EventHandler::AddFileDescriptorListener( + int32_t fileDescriptor, uint32_t events, const std::shared_ptr &listener) { - namespace AppExecFwk - { - - std::shared_ptr EventHandler::Current() - { - const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); - return wp.lock(); - } - - EventHandler::EventHandler(const std::shared_ptr &runner) : eventRunner_(runner) - { - } - - EventHandler::~EventHandler() - { - } - - bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Priority priority) - { - std::function callback = event->GetTaskCallback(); - callback(); - return true; - } - - bool EventHandler::SendTimingEvent(InnerEvent::Pointer &event, int64_t taskTime, Priority priority) - { - return true; - } - - bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority) - { - std::function callback = event->GetTaskCallback(); - callback(); - return true; - } - - void EventHandler::RemoveAllEvents() - { - } - - void EventHandler::RemoveEvent(uint32_t innerEventId) - { - } - - void EventHandler::RemoveEvent(uint32_t innerEventId, int64_t param) - { - } - - void EventHandler::RemoveTask(const std::string &name) - { - } - - ErrCode EventHandler::AddFileDescriptorListener( - int32_t fileDescriptor, uint32_t events, const std::shared_ptr &listener) - { - return EVENT_HANDLER_ERR_INVALID_PARAM; - } - - void EventHandler::RemoveAllFileDescriptorListeners() - { - } - - void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) - { - } - - void EventHandler::SetEventRunner(const std::shared_ptr &runner) - { - } - - void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) - { - } - - void EventHandler::Dump(Dumper &dumper) - { - } - - bool EventHandler::HasInnerEvent(uint32_t innerEventId) - { - return true; - } - - bool EventHandler::HasInnerEvent(int64_t param) - { - return true; - } - - std::string EventHandler::GetEventName(const InnerEvent::Pointer &event) - { - return "132123"; - } - - bool EventHandler::IsIdle() - { - return true; - } - - void EventHandler::ProcessEvent(const InnerEvent::Pointer &) - { - } - } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file + return EVENT_HANDLER_ERR_INVALID_PARAM; +} + +void EventHandler::RemoveAllFileDescriptorListeners() +{} + +void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) +{} + +void EventHandler::SetEventRunner(const std::shared_ptr &runner) +{} + +void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) +{} + +void EventHandler::Dump(Dumper &dumper) +{} + +bool EventHandler::HasInnerEvent(uint32_t innerEventId) +{ + return true; +} + +bool EventHandler::HasInnerEvent(int64_t param) +{ + return true; +} + +std::string EventHandler::GetEventName(const InnerEvent::Pointer &event) +{ + return "132123"; +} + +bool EventHandler::IsIdle() +{ + return true; +} + +void EventHandler::ProcessEvent(const InnerEvent::Pointer &) +{} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file 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 9cb6c4d32..3c6c28bba 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 @@ -54,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; }; @@ -68,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 ce840740f..b4346f668 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 @@ -72,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; @@ -98,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) {} @@ -155,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); @@ -169,7 +147,7 @@ HWTEST_F(PendingWantTest, PendingWant_0200, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_0300, Function | MediumTest | Level1) { - sptr target = nullptr; + sptr target = nullptr; PendingWant pendingWant(target); EXPECT_EQ(pendingWant.target_, target); EXPECT_EQ(pendingWant.GetType(target), WantAgentConstant::OperationType::UNKNOWN_TYPE); @@ -468,9 +446,9 @@ 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), false); } @@ -482,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); @@ -541,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); @@ -566,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/interfaces/innerkits/ans/native/include/message_user.h b/interfaces/innerkits/ans/native/include/message_user.h index 0ceb44f49..0e7717dda 100644 --- a/interfaces/innerkits/ans/native/include/message_user.h +++ b/interfaces/innerkits/ans/native/include/message_user.h @@ -16,13 +16,12 @@ #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_MESSAGE_USER_H #include - +#include "pixel_map.h" #include "parcel.h" #include "uri.h" namespace OHOS { namespace Notification { -class PixelMap; class MessageUser final : public Parcelable { public: /** @@ -67,14 +66,14 @@ public: * Sets the pixel map of this MessageUser. * @param pixelMap Indicates the pixel map to set. */ - void SetPixelMap(const std::shared_ptr &pixelMap); + void SetPixelMap(const std::shared_ptr &pixelMap); /** * Obtains the pixel map of this MessageUser. * * @return Returns the pixel map of this MessageUser. */ - const std::shared_ptr GetPixelMap() const; + const std::shared_ptr GetPixelMap() const; /** * Sets the URI of this MessageUser. @@ -153,7 +152,7 @@ private: private: std::string key_{}; std::string name_{}; - std::shared_ptr pixelMap_{nullptr}; + std::shared_ptr pixelMap_{nullptr}; Uri uri_; bool isMachine_{false}; bool isUserImportant_{false}; diff --git a/interfaces/innerkits/ans/native/include/notification_action_button.h b/interfaces/innerkits/ans/native/include/notification_action_button.h index 42f8af582..843b87753 100644 --- a/interfaces/innerkits/ans/native/include/notification_action_button.h +++ b/interfaces/innerkits/ans/native/include/notification_action_button.h @@ -23,12 +23,11 @@ #include "notification_user_input.h" #include "want_agent.h" #include "pac_map.h" +#include "pixel_map.h" #include "parcel.h" namespace OHOS { namespace Notification { -class PixelMap; - class NotificationActionButton : public Parcelable { public: /** @@ -47,7 +46,7 @@ public: * @return the shared_ptr object owns the created NotificationActionButton object otherwise return empty object if * isContextual is true but icon or wantAgent is empty. */ - static std::shared_ptr Create(const std::shared_ptr &icon, + 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 = @@ -74,7 +73,7 @@ public: * Obtains the icon of this NotificationActionButton. * @return the icon of this NotificationActionButton. */ - const std::shared_ptr GetIcon() const; + const std::shared_ptr GetIcon() const; /** * Obtains the title of this NotificationActionButton. @@ -208,7 +207,7 @@ private: * @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, + 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, @@ -221,7 +220,7 @@ private: bool ReadFromParcel(Parcel &parcel); private: - std::shared_ptr icon_{}; + std::shared_ptr icon_{}; std::string title_{}; std::shared_ptr wantAgent_{}; std::shared_ptr extras_{}; diff --git a/interfaces/innerkits/ans/native/include/notification_picture_content.h b/interfaces/innerkits/ans/native/include/notification_picture_content.h index 1fdd92f7e..c4abb2f45 100644 --- a/interfaces/innerkits/ans/native/include/notification_picture_content.h +++ b/interfaces/innerkits/ans/native/include/notification_picture_content.h @@ -19,12 +19,11 @@ #include #include #include "notification_basic_content.h" +#include "pixel_map.h" #include "parcel.h" namespace OHOS { namespace Notification { -class PixelMap; - class NotificationPictureContent : public NotificationBasicContent { public: /** @@ -71,13 +70,13 @@ public: * Sets the picture to be included in a notification. * @param bigPicture Indicates the PixelMap of the picture to be included. */ - void SetBigPicture(const std::shared_ptr &bigPicture); + void SetBigPicture(const std::shared_ptr &bigPicture); /** * Obtains the PixelMap of the picture specified by calling the setBigPicture(PixelMap) method. * @return the PixelMap of the picture included in the notification. */ - const std::shared_ptr GetBigPicture() const; + const std::shared_ptr GetBigPicture() const; /** * Returns a string representation of the object. @@ -107,7 +106,7 @@ protected: private: std::string expandedTitle_{}; std::string briefText_{}; - std::shared_ptr bigPicture_{}; + std::shared_ptr bigPicture_{}; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index 0f52f5bf6..a879f32d8 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -25,12 +25,11 @@ #include "want_agent.h" #include "context.h" #include "ohos/aafwk/content/want_params.h" +#include "pixel_map.h" #include "parcel.h" namespace OHOS { namespace Notification { -class PixelMap; - class NotificationRequest : public Parcelable { public: enum class BadgeStyle { @@ -402,25 +401,25 @@ public: * Sets the little icon of the notification. * @param littleIcon Indicates the icon of the notification. */ - void SetLittleIcon(const std::shared_ptr &littleIcon); + void SetLittleIcon(const std::shared_ptr &littleIcon); /** * Obtains the icon of the notification. * @return the notification icon. */ - const std::shared_ptr GetLittleIcon() const; + const std::shared_ptr GetLittleIcon() const; /** * Sets the large icon of this notification, which is usually displayed on the right of the notification. * @param bigIcon Indicates the large icon to set. It must be a PixelMap object. */ - void SetBigIcon(const std::shared_ptr &bigIcon); + void SetBigIcon(const std::shared_ptr &bigIcon); /** * Obtains the large icon of this notification. * @return the large icon of this notification. */ - const std::shared_ptr GetBigIcon() const; + const std::shared_ptr GetBigIcon() const; /** * Sets the classification of this notification, which describes the purpose of this notification. @@ -936,8 +935,8 @@ private: std::shared_ptr removalWantAgent_{}; std::shared_ptr maxScreenWantAgent_{}; std::shared_ptr additionalParams_{}; - std::shared_ptr littleIcon_{}; - std::shared_ptr bigIcon_{}; + std::shared_ptr littleIcon_{}; + std::shared_ptr bigIcon_{}; std::shared_ptr notificationContent_{}; std::shared_ptr publicNotification_{}; diff --git a/interfaces/innerkits/ans/native/include/notification_user_input.h b/interfaces/innerkits/ans/native/include/notification_user_input.h index 41b548076..f84d26830 100644 --- a/interfaces/innerkits/ans/native/include/notification_user_input.h +++ b/interfaces/innerkits/ans/native/include/notification_user_input.h @@ -28,8 +28,6 @@ namespace OHOS { namespace Notification { -class PixelMap; - class NotificationUserInput : public Parcelable { public: /** diff --git a/interfaces/kits/js/@ohos.notification.d.ts b/interfaces/kits/js/@ohos.notification.d.ts index c7b4b87c5..ef467ad88 100644 --- a/interfaces/kits/js/@ohos.notification.d.ts +++ b/interfaces/kits/js/@ohos.notification.d.ts @@ -32,8 +32,8 @@ import { NotificationRequest } from './notification/notificationRequest'; * * @name notification * @since 7 - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A */ declare namespace notification { @@ -86,7 +86,7 @@ declare namespace notification { * @param slot Indicates the notification slot to be created, which is set by {@link NotificationSlot}. * This parameter must be specified. * - * @SystemApi + * @systemapi Hide this for inner system use. * @since 7 */ function addSlot(slot: NotificationSlot, callback: AsyncCallback): void; @@ -109,7 +109,7 @@ declare namespace notification { * @param slots Indicates the notification slots to be created, which is set by {@link NotificationSlot}. * This parameter must be specified. * - * @SystemApi + * @systemapi Hide this for inner system use. * @since 7 */ function addSlots(slots: Array, callback: AsyncCallback): void; @@ -173,17 +173,15 @@ declare namespace notification { * * @name ContentType * @since 7 - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @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 } /** @@ -202,7 +200,7 @@ declare namespace notification { /** * subscribe * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ function subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void; @@ -212,7 +210,7 @@ declare namespace notification { /** * unsubscribe * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ function unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void; @@ -221,86 +219,79 @@ declare namespace notification { /** * enableNotification * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ function enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void; function enableNotification(bundle: BundleOption, enable: boolean): Promise; /** - * canNotify + * isNotificationEnabled * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ function isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback): void; function isNotificationEnabled(bundle: BundleOption): Promise; /** - * canNotify + * isNotificationEnabled * + * @systemapi Hide this for inner system use. * @since 7 */ function isNotificationEnabled(callback: AsyncCallback): void; function isNotificationEnabled(): Promise; -/** - * isBadgeDisplayed + /** + * displayBadge * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void; function displayBadge(bundle: BundleOption, enable: boolean): Promise; /** - * canDisplayBadge + * isBadgeDisplayed * - * @systemapi + * @systemapi Hide this for inner system use. * @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 + * setSlotByBundle * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ - function setSlotAsBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback): void; - function setSlotAsBundle(bundle: BundleOption, slot: NotificationSlot): Promise; + function setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback): void; + function setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise; /** - * getSlotsAsBundle + * getSlotsByBundle * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ - function getSlotsAsBundle(bundle: BundleOption, callback: AsyncCallback>): void; - function getSlotsAsBundle(bundle: BundleOption): Promise>; + function getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void; + function getSlotsByBundle(bundle: BundleOption): Promise>; /** - * getSlotNumAsBundle + * getSlotNumByBundle * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ - function getSlotNumAsBundle(bundle: BundleOption, callback: AsyncCallback): void; - function getSlotNumAsBundle(bundle: BundleOption): Promise; + function getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback): void; + function getSlotNumByBundle(bundle: BundleOption): Promise; /** * remove * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ function remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback): void; @@ -309,7 +300,7 @@ declare namespace notification { /** * remove * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ function remove(hashCode: string, callback: AsyncCallback): void; @@ -318,7 +309,7 @@ declare namespace notification { /** * removeAll * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ function removeAll(bundle: BundleOption, callback: AsyncCallback): void; @@ -329,7 +320,7 @@ declare namespace notification { * Obtains all active notifications in the current system. The caller must have system permissions to * call this method. * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ function getAllActiveNotifications(callback: AsyncCallback>): void; @@ -340,8 +331,8 @@ declare namespace notification { * * @since 7 */ - function getActiveNotificationNums(callback: AsyncCallback): void; - function getActiveNotificationNums(): Promise; + function getActiveNotificationCount(callback: AsyncCallback): void; + function getActiveNotificationCount(): Promise; /** * Obtains active notifications of the current application in the system. @@ -368,12 +359,13 @@ declare namespace notification { */ export interface NotificationKey { id: number; - lable?: string; + label?: string; } /** * DisturbMode * + * @systemapi Hide this for inner system use. * @since 7 */ export enum DoNotDisturbMode { diff --git a/interfaces/kits/js/@ohos.wantAgent.d.ts b/interfaces/kits/js/@ohos.wantAgent.d.ts index 23f8c861f..2bdd0a1f0 100644 --- a/interfaces/kits/js/@ohos.wantAgent.d.ts +++ b/interfaces/kits/js/@ohos.wantAgent.d.ts @@ -16,7 +16,6 @@ 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 @@ -28,68 +27,6 @@ import { TriggerInfo } from './wantAgent/triggerInfo'; * @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. * @@ -130,22 +67,7 @@ declare namespace wantAgent { 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}; + SEND_COMMON_EVENT } } diff --git a/interfaces/kits/js/notification/notificationActionButton.ts b/interfaces/kits/js/notification/notificationActionButton.ts index 21690e602..140215050 100644 --- a/interfaces/kits/js/notification/notificationActionButton.ts +++ b/interfaces/kits/js/notification/notificationActionButton.ts @@ -13,19 +13,18 @@ * 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 + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A */ export interface NotificationActionButton { title: string; wantAgent: WantAgent; + extras?: {[key: string]: any}; } diff --git a/interfaces/kits/js/notification/notificationContent.d.ts b/interfaces/kits/js/notification/notificationContent.d.ts index f89526b33..134218f5e 100644 --- a/interfaces/kits/js/notification/notificationContent.d.ts +++ b/interfaces/kits/js/notification/notificationContent.d.ts @@ -20,8 +20,8 @@ import notification from '../@ohos.notification'; * * @name NotificationBasicContent * @since 7 - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A */ export interface NotificationBasicContent { @@ -35,8 +35,8 @@ export interface NotificationBasicContent { * * @name NotificationLongTextContent * @since 7 - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A */ export interface NotificationLongTextContent extends NotificationBasicContent { @@ -50,14 +50,14 @@ export interface NotificationLongTextContent extends NotificationBasicContent { * * @name NotificationMultiLineContent * @since 7 - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A */ export interface NotificationMultiLineContent extends NotificationBasicContent { briefText: string; longTitle: string; - lines: Array; + lines: Array; } /** @@ -65,8 +65,8 @@ export interface NotificationMultiLineContent extends NotificationBasicContent { * * @name NotificationMultiLineContent * @since 7 - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A */ export interface NotificationContent { diff --git a/interfaces/kits/js/notification/notificationRequest.d.ts b/interfaces/kits/js/notification/notificationRequest.d.ts index 5fd0fc9e6..0914b648d 100644 --- a/interfaces/kits/js/notification/notificationRequest.d.ts +++ b/interfaces/kits/js/notification/notificationRequest.d.ts @@ -13,9 +13,7 @@ * 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'; @@ -25,8 +23,8 @@ import { NotificationActionButton } from './notificationActionButton'; * * @name NotificationRequest * @since 7 - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A */ export interface NotificationRequest { @@ -40,14 +38,11 @@ export interface NotificationRequest { 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; @@ -60,7 +55,7 @@ export interface NotificationRequest { /** * Obtains the classification of this notification. * - * @systemapi + * @systemapi Hide this for inner system use. * @since 7 */ classification?: string; diff --git a/interfaces/kits/js/notification/notificationSlot.d.ts b/interfaces/kits/js/notification/notificationSlot.d.ts index e91e8c0eb..56f987e69 100644 --- a/interfaces/kits/js/notification/notificationSlot.d.ts +++ b/interfaces/kits/js/notification/notificationSlot.d.ts @@ -20,8 +20,8 @@ import notification from '../@ohos.notification'; * * @name NotificationSlot * @since 7 - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A */ export interface NotificationSlot { diff --git a/interfaces/kits/js/notification/notificationSorting.d.ts b/interfaces/kits/js/notification/notificationSorting.d.ts index 73fbae19b..1a34e32fa 100644 --- a/interfaces/kits/js/notification/notificationSorting.d.ts +++ b/interfaces/kits/js/notification/notificationSorting.d.ts @@ -19,8 +19,8 @@ import { NotificationSlot } from './notificationSlot'; * Provides sorting information about an active notification. * * @name NotificationSorting - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A * @since 7 */ diff --git a/interfaces/kits/js/notification/notificationSortingMap.d.ts b/interfaces/kits/js/notification/notificationSortingMap.d.ts index f632189de..829ddaf15 100644 --- a/interfaces/kits/js/notification/notificationSortingMap.d.ts +++ b/interfaces/kits/js/notification/notificationSortingMap.d.ts @@ -20,8 +20,8 @@ import { NotificationSorting } from './notificationSorting'; * * @name NotificationSortingMap * @since 7 - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A */ interface NotificationSortingMap { diff --git a/interfaces/kits/js/notification/notificationSubscribeInfo.ts b/interfaces/kits/js/notification/notificationSubscribeInfo.ts index 4d9afb649..ea1f69fc2 100644 --- a/interfaces/kits/js/notification/notificationSubscribeInfo.ts +++ b/interfaces/kits/js/notification/notificationSubscribeInfo.ts @@ -18,8 +18,8 @@ * * @name NotificationSubscribeInfo * @since 7 - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A */ export interface NotificationSubscribeInfo { diff --git a/interfaces/kits/js/notification/notificationSubscriber.d.ts b/interfaces/kits/js/notification/notificationSubscriber.d.ts index 309c15bb3..a659a9d0f 100644 --- a/interfaces/kits/js/notification/notificationSubscriber.d.ts +++ b/interfaces/kits/js/notification/notificationSubscriber.d.ts @@ -22,20 +22,20 @@ import notification from '../@ohos.notification'; * a notification is canceled. * * @name NotificationSubscriber - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A - * @systemApi + * @systemapi Hide this for inner system use. * @since 7 */ export interface NotificationSubscriber { - onConsumed?:(data: SubscribeCallbackData) => void; - onCanceled?:(data: SubscribeCallbackData) => void; + onConsume?:(data: SubscribeCallbackData) => void; + onCancel?:(data: SubscribeCallbackData) => void; onUpdate?:(data: NotificationSortingMap) => void; - onConnected?:() => void; - onDisConnect?:() => void; - onDied?:() => void; - onDisturbModeChanged?:(mode: notification.DoNotDisturbMode) => void; + onConnect?:() => void; + onDisconnect?:() => void; + onDestroy?:() => void; + onDisturbModeChange?:(mode: notification.DoNotDisturbMode) => void; } /** @@ -43,10 +43,10 @@ export interface NotificationSubscriber { * a notification is canceled. * * @name SubscribeCallbackData - * @sysCap ans - * @devices phone, tablet + * @sysCap SystemCapability.Notification.ANS + * @devices phone, tablet, tv, wearable, car * @permission N/A - * @systemApi + * @systemapi Hide this for inner system use. * @since 7 */ export interface SubscribeCallbackData { diff --git a/interfaces/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn index d7d886beb..7592885e3 100755 --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -36,6 +36,7 @@ ohos_shared_library("notification") { "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", "//foundation/ace/napi/interfaces/kits/napi", + "//foundation/multimedia/image_standard/interfaces/kits/js/common/include/", "include", "//third_party/node/src", "//third_party/libuv/include", @@ -70,6 +71,7 @@ ohos_shared_library("notification") { "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/ace/napi:ace_napi", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/jsoncpp:jsoncpp", "//third_party/libuv:uv_static", "//utils/native/base:utils", diff --git a/interfaces/kits/napi/ans/include/get_active.h b/interfaces/kits/napi/ans/include/get_active.h index 011c3eb40..867eef8b0 100644 --- a/interfaces/kits/napi/ans/include/get_active.h +++ b/interfaces/kits/napi/ans/include/get_active.h @@ -24,7 +24,7 @@ using namespace OHOS::Notification; napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info); napi_value GetActiveNotifications(napi_env env, napi_callback_info info); -napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info); +napi_value GetActiveNotificationCount(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/include/slot.h b/interfaces/kits/napi/ans/include/slot.h index 789bc5376..e4e03749a 100644 --- a/interfaces/kits/napi/ans/include/slot.h +++ b/interfaces/kits/napi/ans/include/slot.h @@ -23,11 +23,11 @@ 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 SetSlotByBundle(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 GetSlotNumByBundle(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 GetSlotsByBundle(napi_env env, napi_callback_info info); napi_value RemoveSlot(napi_env env, napi_callback_info info); napi_value RemoveAllSlots(napi_env env, napi_callback_info info); diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 09531dac6..a2543c73c 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -19,6 +19,7 @@ #include "notification_long_text_content.h" #include "notification_multiline_content.h" #include "notification_slot.h" +#include "pixel_map_napi.h" #include "publish.h" #include "want_agent.h" @@ -40,14 +41,6 @@ static napi_value GetNotificationMaxScreenWantAgent( const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetNotificationAutoDeletedTime( const napi_env &env, const napi_value &value, NotificationRequest &request); -// static napi_value GetNotificationSettingsText( -// const napi_env &env, const napi_value &value, NotificationRequest &request); -// static napi_value GetNotificationGroupValue( -// const napi_env &env, const napi_value &value, NotificationRequest &request); -// static napi_value GetNotificationGroupAlertType( -// const napi_env &env, const napi_value &value, NotificationRequest &request); -// static napi_value GetNotificationGroupOverview( -// const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetNotificationClassification( const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetNotificationColor(const napi_env &env, const napi_value &value, NotificationRequest &request); @@ -59,25 +52,17 @@ static napi_value GetNotificationIsStopwatch( const napi_env &env, const napi_value &value, NotificationRequest &request); 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 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 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); -// static napi_value GetNotificationShortcutId( -// const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetNotificationShowDeliveryTime( const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetNotificationNotificationActionButtons( const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationSmallIcon(const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationLargeIcon(const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetNotificationContentType(const napi_env &env, const napi_value &result, int32_t &type); static napi_value GetNotificationBasicContent( const napi_env &env, const napi_value &result, NotificationRequest &request); @@ -207,11 +192,7 @@ napi_value Common::SetNotification( napi_create_string_utf8(env, notification->GetKey().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "hashCode", value); - // // ownerBundleName ?: string - // napi_create_string_utf8(env, notification->GetBundleName().c_str(), NAPI_AUTO_LENGTH, &value); - // napi_set_named_property(env, result, "ownerBundleName", value); - - // isFloatingIcon ?: boolean; + // isFloatingIcon ?: boolean napi_get_boolean(env, notification->IsFloatingIcon(), &value); napi_set_named_property(env, result, "isFloatingIcon", value); @@ -277,10 +258,6 @@ napi_value Common::SetNotificationRequest( napi_get_boolean(env, request->IsUnremovable(), &value); napi_set_named_property(env, result, "isUnremovable", value); - // // createTime?: number - // napi_create_int64(env, request->GetCreateTime(), &value); - // napi_set_named_property(env, result, "createTime", value); - // deliveryTime?: number napi_create_int64(env, request->GetDeliveryTime(), &value); napi_set_named_property(env, result, "deliveryTime", value); @@ -311,27 +288,6 @@ napi_value Common::SetNotificationRequest( napi_set_named_property(env, result, "extraInfo", extraInfo); } - // // settingsText ?: string - // napi_create_string_utf8(env, request->GetSettingsText().c_str(), NAPI_AUTO_LENGTH, &value); - // napi_set_named_property(env, result, "settingsText", value); - - // // ownerBundleName ?: string - // napi_create_string_utf8(env, notification->GetBundleName().c_str(), NAPI_AUTO_LENGTH, &value); - // napi_set_named_property(env, result, "ownerBundleName", value); - - // // groupValue ?: string - // napi_create_string_utf8(env, request->GetGroupValue().c_str(), NAPI_AUTO_LENGTH, &value); - // napi_set_named_property(env, result, "groupValue", value); - - // // groupAlertType ?: number - // int groupAlertType = (int)request->GetGroupAlertType(); - // napi_create_int32(env, groupAlertType, &value); - // napi_set_named_property(env, result, "groupAlertType", value); - - // // groupOverview ?: boolean - // napi_get_boolean(env, request->IsGroupOverview(), &value); - // napi_set_named_property(env, result, "groupOverview", value); - // removalWantAgent ?: WantAgent std::shared_ptr removalAgent = request->GetRemovalWantAgent(); if (removalAgent) { @@ -376,55 +332,14 @@ napi_value Common::SetNotificationRequest( napi_get_boolean(env, request->IsCountdownTimer(), &value); napi_set_named_property(env, result, "isCountDown", value); - // // visibleness ?: number - // int visibleness = (int)request->GetVisibleness(); - // 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); - - // // 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); - // statusBarText ?: string napi_create_string_utf8(env, request->GetStatusBarText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "statusBarText", value); - // isFloatingIcon ?: boolean; do notification + // isFloatingIcon ?: boolean napi_get_boolean(env, request->IsFloatingIcon(), &value); napi_set_named_property(env, result, "isFloatingIcon", value); - // // onlyLocal ?: boolean - // 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); - - // // messageUsers ?: Array - // napi_value arr; - // int count = 0; - // napi_create_array(env, &arr); - // for (auto vec : request->GetMessageUsers()) {notification - // if (vec) { - // napi_value messageUserResult; - // napi_create_object(env, &messageUserResult); - // if (SetMessageUser(env, vec, messageUserResult)) { - // napi_set_element(env, arr, count, messageUserResult); - // count++; - // } - // } - // } - // napi_set_named_property(env, result, "messageUsers", arr); - // label ?: string napi_create_string_utf8(env, request->GetLabel().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "label", value); @@ -434,10 +349,6 @@ napi_value Common::SetNotificationRequest( napi_create_int32(env, badgeIconStyle, &value); napi_set_named_property(env, result, "badgeIconStyle", value); - // // shortcutId ?: string - // napi_create_string_utf8(env, request->GetShortcutId().c_str(), NAPI_AUTO_LENGTH, &value); - // napi_set_named_property(env, result, "shortcutId", value); - // showDeliveryTime ?: boolean napi_get_boolean(env, request->IsShowDeliveryTime(), &value); napi_set_named_property(env, result, "showDeliveryTime", value); @@ -458,8 +369,35 @@ napi_value Common::SetNotificationRequest( } napi_set_named_property(env, result, "actionButtons", arr); - // smallIcon ?: image.PixelMap; do - // largeIcon ?: image.PixelMap; do + // smallIcon ?: image.PixelMap + std::shared_ptr littleIcon = request->GetLittleIcon(); + if (littleIcon) { + napi_value smallIconResult = nullptr; + napi_valuetype valuetype = napi_undefined; + smallIconResult = Media::PixelMapNapi::CreatePixelMap(env, littleIcon); + NAPI_CALL(env, napi_typeof(env, smallIconResult, &valuetype)); + if (valuetype == napi_undefined) { + ANS_LOGI("smallIconResult is undefined"); + napi_set_named_property(env, result, "smallIcon", NapiGetNull(env)); + } else { + napi_set_named_property(env, result, "smallIcon", smallIconResult); + } + } + + // largeIcon ?: image.PixelMap + std::shared_ptr largeIcon = request->GetBigIcon(); + if (largeIcon) { + napi_value largeIconResult = nullptr; + napi_valuetype valuetype = napi_undefined; + largeIconResult = Media::PixelMapNapi::CreatePixelMap(env, largeIcon); + NAPI_CALL(env, napi_typeof(env, largeIconResult, &valuetype)); + if (valuetype == napi_undefined) { + ANS_LOGI("largeIconResult is undefined"); + napi_set_named_property(env, result, "largeIcon", NapiGetNull(env)); + } else { + napi_set_named_property(env, result, "largeIcon", largeIconResult); + } + } // readonly creatorBundleName?: string napi_create_string_utf8(env, request->GetCreatorBundleName().c_str(), NAPI_AUTO_LENGTH, &value); @@ -552,10 +490,6 @@ napi_value Common::SetNotificationSorting(const napi_env &env, const Notificatio napi_get_boolean(env, sorting.IsHiddenNotification(), &value); napi_set_named_property(env, result, "isHiddenNotification", value); - // isSuitInterruptionFilter?: boolean ??????? do - // napi_get_boolean(env, sorting->isOrdered, &value); - // napi_set_named_property(env, result, "isSuitInterruptionFilter", value); - // importance?: number napi_create_int32(env, sorting.GetImportance(), &value); napi_set_named_property(env, result, "importance", value); @@ -576,7 +510,7 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl ANS_LOGI("enter"); napi_value value = nullptr; - // type: SlotType; + // type: SlotType enum SlotType outType = SlotType::UNKNOWN_TYPE; if (!SlotTypeCToJS(slot.GetType(), outType)) { return NapiGetboolean(env, false); @@ -649,7 +583,7 @@ napi_value Common::SetNotificationContent( } napi_value value = nullptr; - // contentType: ContentType; + // contentType: ContentType NotificationContent::Type type = content->GetContentType(); ContentType outType = ContentType::NOTIFICATION_CONTENT_BASIC_TEXT; if (!ContentTypeCToJS(type, outType)) { @@ -737,15 +671,15 @@ napi_value Common::SetNotificationBasicContent( napi_value value = nullptr; - // title: string; + // title: string napi_create_string_utf8(env, basicContent->GetTitle().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "title", value); - // text: string; + // text: string napi_create_string_utf8(env, basicContent->GetText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "text", value); - // additionalText?: string; + // additionalText?: string napi_create_string_utf8(env, basicContent->GetAdditionalText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "additionalText", value); @@ -799,8 +733,6 @@ napi_value Common::SetNotificationPictureContent( napi_value value = nullptr; - // pictureId: number //c++ no do - // briefText: string napi_create_string_utf8(env, pictureContent->GetBriefText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "briefText", value); @@ -809,8 +741,20 @@ napi_value Common::SetNotificationPictureContent( napi_create_string_utf8(env, pictureContent->GetExpandedTitle().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "expandedTitle", value); - // bigPicture: image.PixelMap //do - + // picture: image.PixelMap + std::shared_ptr picture = pictureContent->GetBigPicture(); + if (picture) { + napi_value pictureResult = nullptr; + napi_valuetype valuetype = napi_undefined; + pictureResult = Media::PixelMapNapi::CreatePixelMap(env, picture); + NAPI_CALL(env, napi_typeof(env, pictureResult, &valuetype)); + if (valuetype == napi_undefined) { + ANS_LOGI("pictureResult is undefined"); + napi_set_named_property(env, result, "picture", NapiGetNull(env)); + } else { + napi_set_named_property(env, result, "picture", pictureResult); + } + } return NapiGetboolean(env, true); } @@ -913,8 +857,6 @@ napi_value Common::SetMessageUser(const napi_env &env, const MessageUser &messag napi_create_string_utf8(env, messageUser.GetName().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "name", value); - // pixelMap: image.PixelMap //do - // uri: string napi_create_string_utf8(env, messageUser.GetUri().ToString().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "uri", value); @@ -948,19 +890,19 @@ napi_value Common::SetConversationalMessage(const napi_env &env, napi_create_string_utf8(env, conversationalMessage->GetText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "text", value); - // timestamp: number; + // timestamp: number napi_create_int64(env, conversationalMessage->GetArrivedTime(), &value); napi_set_named_property(env, result, "timestamp", value); - // mimeType: string; + // mimeType: string napi_create_string_utf8(env, conversationalMessage->GetMimeType().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "mimeType", value); - // uri: string; + // uri: string napi_create_string_utf8(env, conversationalMessage->GetUri()->ToString().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "uri", value); - // sender: MessageUser; + // sender: MessageUser napi_value messageUserResult = nullptr; napi_create_object(env, &messageUserResult); if (SetMessageUser(env, conversationalMessage->GetSender(), messageUserResult)) { @@ -988,17 +930,29 @@ napi_value Common::SetNotificationActionButton( // wantAgent: WantAgent std::shared_ptr agent = actionButton->GetWantAgent(); - if (!agent) { + if (agent == nullptr) { ANS_LOGI("wantAgent is null"); napi_set_named_property(env, result, "wantAgent", NapiGetNull(env)); - return NapiGetboolean(env, true); + return NapiGetboolean(env, false); } napi_value wantAgent = nullptr; wantAgent = CreateWantAgentByJS(env, agent); napi_set_named_property(env, result, "wantAgent", wantAgent); - // extras?: {[key: string]: any} //do - // icon?: image.PixelMap //do + // icon?: image.PixelMap + std::shared_ptr icon = actionButton->GetIcon(); + if (icon) { + napi_value iconResult = nullptr; + napi_valuetype valuetype = napi_undefined; + iconResult = Media::PixelMapNapi::CreatePixelMap(env, icon); + NAPI_CALL(env, napi_typeof(env, iconResult, &valuetype)); + if (valuetype == napi_undefined) { + ANS_LOGI("iconResult is undefined"); + napi_set_named_property(env, result, "icon", NapiGetNull(env)); + } else { + napi_set_named_property(env, result, "icon", iconResult); + } + } return NapiGetboolean(env, true); } @@ -1011,7 +965,7 @@ napi_value Common::GetNotificationSubscriberInfo( bool isArray = false; napi_valuetype valuetype = napi_undefined; - // bundleNames?: Array; + // bundleNames?: Array NAPI_CALL(env, napi_has_named_property(env, value, "bundleNames", &hasProperty)); if (hasProperty) { napi_value nBundleNames = nullptr; @@ -1032,28 +986,7 @@ napi_value Common::GetNotificationSubscriberInfo( } } - // // deviceIds?: Array; - // NAPI_CALL(env, napi_has_named_property(env, value, "deviceIds", &hasProperty)); - // if (hasProperty) { - // 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); - // 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; + // userId?: number NAPI_CALL(env, napi_has_named_property(env, value, "userId", &hasProperty)); if (hasProperty) { napi_value nUserId = nullptr; @@ -1131,26 +1064,6 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value return nullptr; } - // // settingsText?: string - // if (GetNotificationSettingsText(env, value, request) == nullptr) { - // return nullptr; - // } - - // // groupValue?: string - // if (GetNotificationGroupValue(env, value, request) == nullptr) { - // return nullptr; - // } - - // // groupAlertType?: number - // if (GetNotificationGroupAlertType(env, value, request) == nullptr) { - // return nullptr; - // } - - // // groupOverview?: boolean - // if (GetNotificationGroupOverview(env, value, request) == nullptr) { - // return nullptr; - // } - // classification?: string if (GetNotificationClassification(env, value, request) == nullptr) { return nullptr; @@ -1181,33 +1094,11 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value return nullptr; } - // // visibleness?: number - // if (GetNotificationVisibleness(env, value, request) == nullptr) { - // return nullptr; - // } - - // // progressValue?: number - // // progressMaxValue?: number - // // isIndeterminate?: boolean - // if (GetNotificationProgressBar(env, value, request) == nullptr) { - // return nullptr; - // } - // statusBarText?: string if (GetNotificationStatusBarText(env, value, request) == nullptr) { return nullptr; } - // // onlyLocal?: boolean - // if (GetNotificationOnlyLocal(env, value, request) == nullptr) { - // return nullptr; - // } - - // // sortingKey?: string - // if (GetNotificationSortingKey(env, value, request) == nullptr) { - // return nullptr; - // } - // label?: string if (GetNotificationLabel(env, value, request) == nullptr) { return nullptr; @@ -1218,11 +1109,6 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value return nullptr; } - // // shortcutId?: string - // if (GetNotificationShortcutId(env, value, request) == nullptr) { - // return nullptr; - // } - // showDeliveryTime?: boolean if (GetNotificationShowDeliveryTime(env, value, request) == nullptr) { return nullptr; @@ -1233,6 +1119,16 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value return nullptr; } + // smallIcon?: image.PixelMap + if (GetNotificationSmallIcon(env, value, request) == nullptr) { + return nullptr; + } + + // largeIcon?: image.PixelMap + if (GetNotificationLargeIcon(env, value, request) == nullptr) { + return nullptr; + } + return Common::NapiGetNull(env); } @@ -1560,98 +1456,6 @@ napi_value GetNotificationAutoDeletedTime(const napi_env &env, const napi_value return Common::NapiGetNull(env); } -// napi_value GetNotificationSettingsText( -// const napi_env &env, const napi_value &value, NotificationRequest &request) -// { -// ANS_LOGI("enter"); - -// 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, "settingsText", &hasProperty)); -// if (hasProperty) { -// napi_get_named_property(env, value, "settingsText", &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.SetSettingsText(str); -// } - -// ANS_LOGI("===============GetNotificationSettingsText====settingsText = %{public}s end", str); -// return Common::NapiGetNull(env); -// } - -// napi_value GetNotificationGroupValue( -// const napi_env &env, const napi_value &value, NotificationRequest &request) -// { -// ANS_LOGI("enter"); - -// 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, "groupValue", &hasProperty)); -// if (hasProperty) { -// napi_get_named_property(env, value, "groupValue", &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.SetGroupValue(str); -// } - -// ANS_LOGI("===============GetNotificationGroupValue====groupValue = %{public}s end", str); -// return Common::NapiGetNull(env); -// } - -// napi_value GetNotificationGroupAlertType( -// const napi_env &env, const napi_value &value, NotificationRequest &request) -// { -// ANS_LOGI("enter"); - -// napi_valuetype valuetype = napi_undefined; -// napi_value result = nullptr; -// bool hasProperty = false; -// int32_t groupAlertType = 0; - -// NAPI_CALL(env, napi_has_named_property(env, value, "groupAlertType", &hasProperty)); -// if (hasProperty) { -// napi_get_named_property(env, value, "groupAlertType", &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, &groupAlertType); -// request.SetGroupAlertType(static_cast(groupAlertType)); -// } - -// return Common::NapiGetNull(env); -// } - -// napi_value GetNotificationGroupOverview( -// const napi_env &env, const napi_value &value, NotificationRequest &request) -// { -// ANS_LOGI("enter"); - -// napi_valuetype valuetype = napi_undefined; -// napi_value result = nullptr; -// bool hasProperty = false; -// bool groupOverview = false; - -// NAPI_CALL(env, napi_has_named_property(env, value, "groupOverview", &hasProperty)); -// if (hasProperty) { -// napi_get_named_property(env, value, "groupOverview", &result); -// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); -// NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); -// napi_get_value_bool(env, result, &groupOverview); -// request.SetGroupOverview(groupOverview); -// } - -// return Common::NapiGetNull(env); -// } - napi_value GetNotificationClassification(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1780,68 +1584,6 @@ napi_value GetNotificationIsCountDown(const napi_env &env, const napi_value &val return Common::NapiGetNull(env); } -// napi_value GetNotificationVisibleness( -// const napi_env &env, const napi_value &value, NotificationRequest &request) -// { -// ANS_LOGI("enter"); - -// napi_valuetype valuetype = napi_undefined; -// napi_value result = nullptr; -// bool hasProperty = false; -// int32_t visibleness = 0; - -// NAPI_CALL(env, napi_has_named_property(env, value, "visibleness", &hasProperty)); -// if (hasProperty) { -// napi_get_named_property(env, value, "visibleness", &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, &visibleness); -// request.SetVisibleness(static_cast(visibleness)); -// } - -// return Common::NapiGetNull(env); -// } - -// napi_value GetNotificationProgressBar(const napi_env &env, const napi_value &value, NotificationRequest &request) -// { -// ANS_LOGI("enter"); - -// 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) { -// napi_get_named_property(env, value, "progressMaxValue", &result); -// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); -// NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); -// napi_get_value_int32(env, result, &progressMaxValue); -// } - -// NAPI_CALL(env, napi_has_named_property(env, value, "isIndeterminate", &hasProperty)); -// if (hasProperty) { -// napi_get_named_property(env, value, "isIndeterminate", &result); -// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); -// NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); -// napi_get_value_bool(env, result, &isIndeterminate); -// } - -// request.SetProgressBar(progressValue, progressMaxValue, isIndeterminate); - -// return Common::NapiGetNull(env); -// } - napi_value GetNotificationStatusBarText(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1864,50 +1606,6 @@ napi_value GetNotificationStatusBarText(const napi_env &env, const napi_value &v return Common::NapiGetNull(env); } -// napi_value GetNotificationOnlyLocal(const napi_env &env, const napi_value &value, NotificationRequest -// &request) -// { -// ANS_LOGI("enter"); - -// napi_valuetype valuetype = napi_undefined; -// napi_value result = nullptr; -// bool hasProperty = false; -// bool onlyLocal = false; - -// NAPI_CALL(env, napi_has_named_property(env, value, "onlyLocal", &hasProperty)); -// if (hasProperty) { -// napi_get_named_property(env, value, "onlyLocal", &result); -// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); -// NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. bool expected."); -// napi_get_value_bool(env, result, &onlyLocal); -// request.SetOnlyLocal(onlyLocal); -// } - -// return Common::NapiGetNull(env); -// } - -// napi_value GetNotificationSortingKey(const napi_env &env, const napi_value &value, NotificationRequest &request) -// { -// ANS_LOGI("enter"); - -// 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); -// } - -// return Common::NapiGetNull(env); -// } - napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1951,30 +1649,6 @@ napi_value GetNotificationBadgeIconStyle(const napi_env &env, const napi_value & return Common::NapiGetNull(env); } -// napi_value GetNotificationShortcutId( -// const napi_env &env, const napi_value &value, NotificationRequest &request) -// { -// ANS_LOGI("enter"); - -// 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, "shortcutId", &hasProperty)); -// if (hasProperty) { -// napi_get_named_property(env, value, "shortcutId", &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.SetShortcutId(str); -// } - -// ANS_LOGI("===============GetNotificationShortcutId====shortcutId = %{public}s end", str); -// return Common::NapiGetNull(env); -// } - napi_value GetNotificationShowDeliveryTime(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -2010,8 +1684,10 @@ napi_value GetNotificationNotificationActionButtons( bool hasProperty = false; napi_value titelActionButton = nullptr; napi_value wantAgentActionButton = nullptr; + napi_value iconActionButton = nullptr; std::string title; WantAgent::WantAgent *wantAgentPtr = nullptr; + std::shared_ptr pixelMap = nullptr; std::shared_ptr wantAgent; napi_has_named_property(env, value, "actionButtons", &hasProperty); @@ -2030,7 +1706,7 @@ napi_value GetNotificationNotificationActionButtons( NAPI_CALL(env, napi_typeof(env, actionButton, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - // title: string; + // title: string NAPI_CALL(env, napi_has_named_property(env, actionButton, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, actionButton, "title", &titelActionButton); @@ -2043,7 +1719,7 @@ napi_value GetNotificationNotificationActionButtons( return nullptr; } - // wantAgent: WantAgent; + // wantAgent: WantAgent NAPI_CALL(env, napi_has_named_property(env, actionButton, "wantAgent", &hasProperty)); if (hasProperty) { napi_get_named_property(env, actionButton, "wantAgent", &wantAgentActionButton); @@ -2060,16 +1736,76 @@ napi_value GetNotificationNotificationActionButtons( return nullptr; } - // extras?: {[key: string]: any}; + // icon?: image.PixelMap + NAPI_CALL(env, napi_has_named_property(env, actionButton, "icon", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, actionButton, "icon", &iconActionButton); + NAPI_CALL(env, napi_typeof(env, iconActionButton, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + pixelMap = Media::PixelMapNapi::GetPixelMap(env, iconActionButton); + if (pixelMap == nullptr) { + ANS_LOGE("Invalid object pixelMap"); + return nullptr; + } + } - std::vector> vec; - auto pActionButton = NotificationActionButton::Create(nullptr, title, wantAgent); + auto pActionButton = NotificationActionButton::Create(pixelMap, title, wantAgent); request.AddActionButton(pActionButton); } return Common::NapiGetNull(env); } +napi_value GetNotificationSmallIcon(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, value, "smallIcon", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "smallIcon", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr pixelMap = nullptr; + pixelMap = Media::PixelMapNapi::GetPixelMap(env, result); + if (pixelMap == nullptr) { + ANS_LOGE("Invalid object pixelMap"); + return nullptr; + } + request.SetLittleIcon(pixelMap); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationLargeIcon(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, value, "largeIcon", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "largeIcon", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr pixelMap = nullptr; + pixelMap = Media::PixelMapNapi::GetPixelMap(env, result); + if (pixelMap == nullptr) { + ANS_LOGE("Invalid object pixelMap"); + return nullptr; + } + request.SetBigIcon(pixelMap); + } + + return Common::NapiGetNull(env); +} + napi_value GetNotificationContentType(const napi_env &env, const napi_value &result, int32_t &type) { ANS_LOGI("enter"); @@ -2115,7 +1851,7 @@ napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &re return nullptr; } - // title: string; + // title: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "title", &basicContentResult); @@ -2129,7 +1865,7 @@ napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &re return nullptr; } - // text: string; + // text: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "text", &basicContentResult); @@ -2143,7 +1879,7 @@ napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &re return nullptr; } - // additionalText?: string; + // additionalText?: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); @@ -2185,7 +1921,7 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value return nullptr; } - // title: string; + // title: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "title", &basicContentResult); @@ -2199,7 +1935,7 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value return nullptr; } - // text: string; + // text: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "text", &basicContentResult); @@ -2213,7 +1949,7 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value return nullptr; } - // additionalText?: string; + // additionalText?: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); @@ -2224,7 +1960,7 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value ANS_LOGI("longText::additionalText = %{public}s", str); } - // longText: string; + // longText: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "longText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "longText", &longContentResult); @@ -2238,7 +1974,7 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value return nullptr; } - // briefText: string; + // briefText: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "briefText", &longContentResult); @@ -2252,7 +1988,7 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value return nullptr; } - // expandedTitle: string; + // expandedTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "expandedTitle", &longContentResult); @@ -2296,7 +2032,7 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & return nullptr; } - // title: string; + // title: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "title", &basicContentResult); @@ -2310,7 +2046,7 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & return nullptr; } - // text: string; + // text: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "text", &basicContentResult); @@ -2324,7 +2060,7 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & return nullptr; } - // additionalText?: string; + // additionalText?: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); @@ -2335,7 +2071,7 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & ANS_LOGI("pictureText::additionalText = %{public}s", str); } - // briefText: string; + // briefText: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "briefText", &pictureContentResult); @@ -2349,7 +2085,7 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & return nullptr; } - // expandedTitle: string; + // expandedTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "expandedTitle", &pictureContentResult); @@ -2363,8 +2099,23 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & return nullptr; } - // bigPicture: image.PixelMap do - + // picture: image.PixelMap + NAPI_CALL(env, napi_has_named_property(env, contentResult, "picture", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "picture", &pictureContentResult); + NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr pixelMap = nullptr; + pixelMap = Media::PixelMapNapi::GetPixelMap(env, pictureContentResult); + if (pixelMap == nullptr) { + ANS_LOGE("Invalid object pixelMap"); + return nullptr; + } + pictureContent->SetBigPicture(pixelMap); + } else { + ANS_LOGE("Property picture expected."); + return nullptr; + } request.SetContent(std::make_shared(pictureContent)); return Common::NapiGetNull(env); @@ -2393,8 +2144,6 @@ napi_value GetMessageUser(const napi_env &env, const napi_value &result, Message return nullptr; } - // pixelMap: image.PixelMap do - // uri: string NAPI_CALL(env, napi_has_named_property(env, result, "uri", &hasProperty)); if (hasProperty) { @@ -2597,7 +2346,7 @@ napi_value GetNotificationConversationalContent( return nullptr; } - // title: string; + // title: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "title", &basicContentResult); @@ -2611,7 +2360,7 @@ napi_value GetNotificationConversationalContent( return nullptr; } - // text: string; + // text: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "text", &basicContentResult); @@ -2625,7 +2374,7 @@ napi_value GetNotificationConversationalContent( return nullptr; } - // additionalText?: string; + // additionalText?: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); @@ -2636,7 +2385,7 @@ napi_value GetNotificationConversationalContent( ANS_LOGI("conversationalText::additionalText = %{public}s", str); } - // conversationTitle: string; + // conversationTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationTitle", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "conversationTitle", &conversationalContentResult); @@ -2650,7 +2399,7 @@ napi_value GetNotificationConversationalContent( return nullptr; } - // conversationGroup: boolean; + // conversationGroup: boolean NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationGroup", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "conversationGroup", &conversationalContentResult); @@ -2665,7 +2414,7 @@ napi_value GetNotificationConversationalContent( return nullptr; } - // messages: Array; + // messages: Array NAPI_CALL(env, napi_has_named_property(env, contentResult, "messages", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "messages", &conversationalContentResult); @@ -2721,7 +2470,7 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value return nullptr; } - // title: string; + // title: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "title", &basicContentResult); @@ -2735,7 +2484,7 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value return nullptr; } - // text: string; + // text: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "text", &basicContentResult); @@ -2749,7 +2498,7 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value return nullptr; } - // additionalText?: string; + // additionalText?: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); @@ -2760,7 +2509,7 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value ANS_LOGI("multiLine::additionalText = %{public}s", str); } - // briefText: string; + // briefText: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "briefText", &multiLineContentResult); @@ -2774,7 +2523,7 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value return nullptr; } - // longTitle: string; + // longTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "longTitle", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "longTitle", &multiLineContentResult); @@ -2788,7 +2537,7 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value return nullptr; } - // lines: Array; + // lines: Array NAPI_CALL(env, napi_has_named_property(env, contentResult, "lines", &hasProperty)); if (hasProperty) { if (GetNotificationMultiLineContentLines(env, contentResult, multiLineContent) == nullptr) { @@ -3010,7 +2759,7 @@ napi_value Common::GetBundleOption(const napi_env &env, const napi_value &value, char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; - // bundle: string; + // 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); @@ -3019,7 +2768,7 @@ napi_value Common::GetBundleOption(const napi_env &env, const napi_value &value, NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); option.bundle = str; - // uid?: number; + // uid?: number NAPI_CALL(env, napi_has_named_property(env, value, "uid", &hasProperty)); if (hasProperty) { napi_get_named_property(env, value, "uid", &result); @@ -3039,7 +2788,7 @@ napi_value Common::GetNotificationKey(const napi_env &env, const napi_value &val napi_valuetype valuetype = napi_undefined; napi_value result = nullptr; - // id: number; + // 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); @@ -3047,7 +2796,7 @@ napi_value Common::GetNotificationKey(const napi_env &env, const napi_value &val NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, result, &key.id); - // lable?: string; + // label?: string NAPI_CALL(env, napi_has_named_property(env, value, "label", &hasProperty)); if (hasProperty) { char str[STR_MAX_SIZE] = {0}; @@ -3071,18 +2820,9 @@ 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_MULTILINE: outType = NotificationContent::Type::MULTILINE; break; - // case ContentType::NOTIFICATION_CONTENT_MEDIA: - // outType = NotificationContent::Type::MEDIA; - // break; default: ANS_LOGE("ContentType %{public}d is an invalid value", inType); return false; @@ -3099,18 +2839,9 @@ 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::MULTILINE: outType = ContentType::NOTIFICATION_CONTENT_MULTILINE; break; - // case NotificationContent::Type::MEDIA: - // outType = ContentType::NOTIFICATION_CONTENT_MEDIA; - // break; default: ANS_LOGE("ContentType %{public}d is an invalid value", inType); return false; diff --git a/interfaces/kits/napi/ans/src/display_badge.cpp b/interfaces/kits/napi/ans/src/display_badge.cpp index 52d895636..129355a8f 100644 --- a/interfaces/kits/napi/ans/src/display_badge.cpp +++ b/interfaces/kits/napi/ans/src/display_badge.cpp @@ -75,9 +75,9 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[2]:callback if (argc >= ENABLE_BADGE_DISPLAYED_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[ENABLE_BADGE_DISPLAYED_MAX_PARA - 1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[2], 1, ¶ms.callback); + napi_create_reference(env, argv[ENABLE_BADGE_DISPLAYED_MAX_PARA - 1], 1, ¶ms.callback); } return Common::NapiGetNull(env); diff --git a/interfaces/kits/napi/ans/src/enable_notification.cpp b/interfaces/kits/napi/ans/src/enable_notification.cpp index 014c6c3e6..ae680b46b 100644 --- a/interfaces/kits/napi/ans/src/enable_notification.cpp +++ b/interfaces/kits/napi/ans/src/enable_notification.cpp @@ -75,9 +75,9 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[2]:callback if (argc >= ENABLE_NOTIFICATION_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[ENABLE_NOTIFICATION_MAX_PARA - 1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[2], 1, ¶ms.callback); + napi_create_reference(env, argv[ENABLE_NOTIFICATION_MAX_PARA - 1], 1, ¶ms.callback); } return Common::NapiGetNull(env); diff --git a/interfaces/kits/napi/ans/src/get_active.cpp b/interfaces/kits/napi/ans/src/get_active.cpp index cf9bab8a6..d763bd058 100644 --- a/interfaces/kits/napi/ans/src/get_active.cpp +++ b/interfaces/kits/napi/ans/src/get_active.cpp @@ -239,7 +239,7 @@ napi_value GetActiveNotifications(napi_env env, napi_callback_info info) } } -napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info) +napi_value GetActiveNotificationCount(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); @@ -257,19 +257,19 @@ napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info) Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); napi_value resourceName = nullptr; - napi_create_string_latin1(env, "getActiveNotificationNums", NAPI_AUTO_LENGTH, &resourceName); + napi_create_string_latin1(env, "getActiveNotificationCount", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work( env, nullptr, resourceName, [](napi_env env, void *data) { - ANS_LOGI("GetActiveNotificationNums napi_create_async_work start"); + ANS_LOGI("GetActiveNotificationCount napi_create_async_work start"); AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; int32_t num = 0; asynccallbackinfo->info.errorCode = NotificationHelper::GetActiveNotificationNums(num); - ANS_LOGI("GetActiveNotificationNums nums = %{public}d", num); + ANS_LOGI("GetActiveNotificationCount count = %{public}d", num); if (asynccallbackinfo->info.errorCode != ERR_OK) { asynccallbackinfo->result = Common::NapiGetNull(env); return; @@ -277,7 +277,7 @@ napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info) napi_create_int32(env, num, &asynccallbackinfo->result); }, [](napi_env env, napi_status status, void *data) { - ANS_LOGI("GetActiveNotificationNums napi_create_async_work end"); + ANS_LOGI("GetActiveNotificationCount napi_create_async_work end"); AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); diff --git a/interfaces/kits/napi/ans/src/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index 64869c224..864e4a775 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -44,16 +44,16 @@ napi_value NotificationInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("removeAll", RemoveAll), DECLARE_NAPI_FUNCTION("getAllActiveNotifications", GetAllActiveNotifications), DECLARE_NAPI_FUNCTION("getActiveNotifications", GetActiveNotifications), - DECLARE_NAPI_FUNCTION("getActiveNotificationNums", GetActiveNotificationNums), + DECLARE_NAPI_FUNCTION("getActiveNotificationCount", GetActiveNotificationCount), 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("setSlotByBundle", SetSlotByBundle), DECLARE_NAPI_FUNCTION("getSlot", GetSlot), - DECLARE_NAPI_FUNCTION("getSlotNumAsBundle", GetSlotNumAsBundle), + DECLARE_NAPI_FUNCTION("getSlotNumByBundle", GetSlotNumByBundle), DECLARE_NAPI_FUNCTION("getSlots", GetSlots), - DECLARE_NAPI_FUNCTION("getSlotsAsBundle", GetSlotsAsBundle), + DECLARE_NAPI_FUNCTION("getSlotsByBundle", GetSlotsByBundle), DECLARE_NAPI_FUNCTION("removeSlot", RemoveSlot), DECLARE_NAPI_FUNCTION("removeAllSlots", RemoveAllSlots), DECLARE_NAPI_FUNCTION("enableNotification", EnableNotification), diff --git a/interfaces/kits/napi/ans/src/remove.cpp b/interfaces/kits/napi/ans/src/remove.cpp index a2c4f62ba..8cae75ede 100644 --- a/interfaces/kits/napi/ans/src/remove.cpp +++ b/interfaces/kits/napi/ans/src/remove.cpp @@ -97,9 +97,9 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[2]:callback if (argc >= REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA - 1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[2], 1, ¶ms.callback); + napi_create_reference(env, argv[REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA - 1], 1, ¶ms.callback); } } diff --git a/interfaces/kits/napi/ans/src/slot.cpp b/interfaces/kits/napi/ans/src/slot.cpp index ef4f6893c..3b493f2c6 100644 --- a/interfaces/kits/napi/ans/src/slot.cpp +++ b/interfaces/kits/napi/ans/src/slot.cpp @@ -25,7 +25,7 @@ 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; +const int REMOVE_ALL_SLOTS_MAX_PARA = 1; struct ParametersInfoAddSlot { NotificationSlot slot; @@ -55,16 +55,16 @@ struct AsyncCallbackInfoAddSlots { CallbackPromiseInfo info; }; -struct ParametersInfoSetSlotAsBundle { +struct ParametersInfoSetSlotByBundle { BundleOption option; std::vector> slots; napi_ref callback = nullptr; }; -struct AsyncCallbackInfoSetSlotAsBundle { +struct AsyncCallbackInfoSetSlotByBundle { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - ParametersInfoSetSlotAsBundle params; + ParametersInfoSetSlotByBundle params; CallbackPromiseInfo info; }; @@ -81,16 +81,16 @@ struct AsyncCallbackInfoGetSlot { CallbackPromiseInfo info; }; -struct ParametersInfoGetSlotNumAsBundle { +struct ParametersInfoGetSlotNumByBundle { BundleOption option; napi_ref callback = nullptr; }; -struct AsyncCallbackInfoGetSlotNumAsBundle { +struct AsyncCallbackInfoGetSlotNumByBundle { napi_env env = nullptr; napi_async_work asyncWork = nullptr; napi_value result = nullptr; - ParametersInfoGetSlotNumAsBundle params; + ParametersInfoGetSlotNumByBundle params; CallbackPromiseInfo info; }; @@ -101,16 +101,16 @@ struct AsyncCallbackInfoGetSlots { CallbackPromiseInfo info; }; -struct ParametersInfoGetSlotsAsBundle { +struct ParametersInfoGetSlotsByBundle { BundleOption option; napi_ref callback = nullptr; }; -struct AsyncCallbackInfoGetSlotsAsBundle { +struct AsyncCallbackInfoGetSlotsByBundle { napi_env env = nullptr; napi_async_work asyncWork = nullptr; napi_value result = nullptr; - ParametersInfoGetSlotsAsBundle params; + ParametersInfoGetSlotsByBundle params; CallbackPromiseInfo info; }; @@ -207,8 +207,8 @@ napi_value ParseParametersByAddSlots(const napi_env &env, const napi_callback_in return Common::NapiGetNull(env); } -napi_value ParseParametersSetSlotAsBundle( - const napi_env &env, const napi_callback_info &info, ParametersInfoSetSlotAsBundle ¶ms) +napi_value ParseParametersSetSlotByBundle( + const napi_env &env, const napi_callback_info &info, ParametersInfoSetSlotByBundle ¶ms) { ANS_LOGI("enter"); @@ -249,9 +249,9 @@ napi_value ParseParametersSetSlotAsBundle( // argv[2]:callback if (argc >= SET_SLOT_AS_BUNDLE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[SET_SLOT_AS_BUNDLE_MAX_PARA - 1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[2], 1, ¶ms.callback); + napi_create_reference(env, argv[SET_SLOT_AS_BUNDLE_MAX_PARA - 1], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -285,8 +285,8 @@ napi_value ParseParametersByGetSlot(const napi_env &env, const napi_callback_inf return Common::NapiGetNull(env); } -napi_value ParseParametersGetSlotNumAsBundle( - const napi_env &env, const napi_callback_info &info, ParametersInfoGetSlotNumAsBundle ¶ms) +napi_value ParseParametersGetSlotNumByBundle( + const napi_env &env, const napi_callback_info &info, ParametersInfoGetSlotNumByBundle ¶ms) { ANS_LOGI("enter"); @@ -334,8 +334,8 @@ napi_value ParseParametersByGetSlots(const napi_env &env, const napi_callback_in return Common::NapiGetNull(env); } -napi_value ParseParametersGetSlotsAsBundle( - const napi_env &env, const napi_callback_info &info, ParametersInfoGetSlotsAsBundle ¶ms) +napi_value ParseParametersGetSlotsByBundle( + const napi_env &env, const napi_callback_info &info, ParametersInfoGetSlotsByBundle ¶ms) { ANS_LOGI("enter"); @@ -397,12 +397,12 @@ napi_value ParseParametersByRemoveSlot( napi_value ParseParametersByRemoveAllSlots(const napi_env &env, const napi_callback_info &info, napi_ref &callback) { ANS_LOGI("enter"); - size_t argc = REMOVE_ALL_MAX_PARA; - napi_value argv[REMOVE_ALL_MAX_PARA] = {nullptr}; + size_t argc = REMOVE_ALL_SLOTS_MAX_PARA; + napi_value argv[REMOVE_ALL_SLOTS_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc >= REMOVE_ALL_MAX_PARA) { + if (argc >= REMOVE_ALL_SLOTS_MAX_PARA) { napi_valuetype valuetype = napi_undefined; // argv[0]:callback NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); @@ -531,17 +531,17 @@ napi_value AddSlots(napi_env env, napi_callback_info info) } } -napi_value SetSlotAsBundle(napi_env env, napi_callback_info info) +napi_value SetSlotByBundle(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); - ParametersInfoSetSlotAsBundle params{}; - if (ParseParametersSetSlotAsBundle(env, info, params) == nullptr) { + ParametersInfoSetSlotByBundle params{}; + if (ParseParametersSetSlotByBundle(env, info, params) == nullptr) { return Common::JSParaError(env, params.callback); } - AsyncCallbackInfoSetSlotAsBundle *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoSetSlotAsBundle{.env = env, .asyncWork = nullptr, .params = params}; + AsyncCallbackInfoSetSlotByBundle *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoSetSlotByBundle{.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { return Common::JSParaError(env, params.callback); } @@ -549,14 +549,14 @@ napi_value SetSlotAsBundle(napi_env env, napi_callback_info info) Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); napi_value resourceName = nullptr; - napi_create_string_latin1(env, "setSlotAsBundle", NAPI_AUTO_LENGTH, &resourceName); + napi_create_string_latin1(env, "setSlotByBundle", 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; + ANS_LOGI("SetSlotByBundle napi_create_async_work start"); + AsyncCallbackInfoSetSlotByBundle *asynccallbackinfo = (AsyncCallbackInfoSetSlotByBundle *)data; NotificationBundleOption bundleOption; bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); @@ -565,8 +565,8 @@ napi_value SetSlotAsBundle(napi_env env, napi_callback_info info) 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; + ANS_LOGI("SetSlotByBundle napi_create_async_work end"); + AsyncCallbackInfoSetSlotByBundle *asynccallbackinfo = (AsyncCallbackInfoSetSlotByBundle *)data; Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); @@ -664,17 +664,17 @@ napi_value GetSlot(napi_env env, napi_callback_info info) } } -napi_value GetSlotNumAsBundle(napi_env env, napi_callback_info info) +napi_value GetSlotNumByBundle(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); - ParametersInfoGetSlotNumAsBundle params{}; - if (ParseParametersGetSlotNumAsBundle(env, info, params) == nullptr) { + ParametersInfoGetSlotNumByBundle params{}; + if (ParseParametersGetSlotNumByBundle(env, info, params) == nullptr) { return Common::JSParaError(env, params.callback); } - AsyncCallbackInfoGetSlotNumAsBundle *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoGetSlotNumAsBundle{.env = env, .asyncWork = nullptr, .params = params}; + AsyncCallbackInfoGetSlotNumByBundle *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetSlotNumByBundle{.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { return Common::JSParaError(env, params.callback); } @@ -682,14 +682,14 @@ napi_value GetSlotNumAsBundle(napi_env env, napi_callback_info info) Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); napi_value resourceName = nullptr; - napi_create_string_latin1(env, "getSlotNumAsBundle", NAPI_AUTO_LENGTH, &resourceName); + napi_create_string_latin1(env, "getSlotNumByBundle", 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; + ANS_LOGI("GetSlotNumByBundle napi_create_async_work start"); + AsyncCallbackInfoGetSlotNumByBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; NotificationBundleOption bundleOption; bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); @@ -699,8 +699,8 @@ napi_value GetSlotNumAsBundle(napi_env env, napi_callback_info info) 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; + ANS_LOGI("GetSlotNumByBundle napi_create_async_work end"); + AsyncCallbackInfoGetSlotNumByBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); @@ -811,17 +811,17 @@ napi_value GetSlots(napi_env env, napi_callback_info info) } } -napi_value GetSlotsAsBundle(napi_env env, napi_callback_info info) +napi_value GetSlotsByBundle(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); - ParametersInfoGetSlotsAsBundle params{}; - if (ParseParametersGetSlotsAsBundle(env, info, params) == nullptr) { + ParametersInfoGetSlotsByBundle params{}; + if (ParseParametersGetSlotsByBundle(env, info, params) == nullptr) { return Common::JSParaError(env, params.callback); } - AsyncCallbackInfoGetSlotsAsBundle *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoGetSlotsAsBundle{.env = env, .asyncWork = nullptr, .params = params}; + AsyncCallbackInfoGetSlotsByBundle *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetSlotsByBundle{.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { return Common::JSParaError(env, params.callback); } @@ -829,14 +829,14 @@ napi_value GetSlotsAsBundle(napi_env env, napi_callback_info info) Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); napi_value resourceName = nullptr; - napi_create_string_latin1(env, "getSlotsAsBundle", NAPI_AUTO_LENGTH, &resourceName); + napi_create_string_latin1(env, "getSlotsByBundle", 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; + ANS_LOGI("GetSlotsByBundle napi_create_async_work start"); + AsyncCallbackInfoGetSlotsByBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotsByBundle *)data; NotificationBundleOption bundleOption; bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); @@ -865,7 +865,7 @@ napi_value GetSlotsAsBundle(napi_env env, napi_callback_info info) napi_set_element(env, arr, count, nSlot); count++; } - ANS_LOGI("getSlots count = %{public}d", count); + ANS_LOGI("getSlots count = %{public}zu", count); asynccallbackinfo->result = arr; if ((count == 0) && (slots.size() > 0)) { asynccallbackinfo->info.errorCode = ERROR; @@ -873,8 +873,8 @@ napi_value GetSlotsAsBundle(napi_env env, napi_callback_info info) } }, [](napi_env env, napi_status status, void *data) { - ANS_LOGI("GetSlotsAsBundle napi_create_async_work end"); - AsyncCallbackInfoGetSlotsAsBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotsAsBundle *)data; + ANS_LOGI("GetSlotsByBundle napi_create_async_work end"); + AsyncCallbackInfoGetSlotsByBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotsByBundle *)data; Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index 0cf6e5e64..f2bcb906e 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -21,13 +21,13 @@ 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 CONSUME = "onConsume"; +const std::string CANCEL = "onCancel"; 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"; +const std::string CONNECTED = "onConnect"; +const std::string DIS_CONNECTED = "onDisconnect"; +const std::string DIE = "onDestroy"; +const std::string DISTURB_MODE_CHANGE = "onDisturbModeChange"; struct NotificationReceiveDataWorker { napi_env env = nullptr; @@ -161,7 +161,7 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrGetNotificationRequest().GetNotificationId()); - ANS_LOGI("OnCanceled sortingMap size = %{public}d", sortingMap->GetKey().size()); + ANS_LOGI("OnCanceled sortingMap size = %{public}zu", sortingMap->GetKey().size()); ANS_LOGI("OnCanceled deleteReason = %{public}d", deleteReason); uv_loop_s *loop = nullptr; @@ -250,7 +250,7 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrGetNotificationRequest().GetNotificationId()); - ANS_LOGI("OnConsumed sortingMap size = %{public}d", sortingMap->GetKey().size()); + ANS_LOGI("OnConsumed sortingMap size = %{public}zu", sortingMap->GetKey().size()); uv_loop_s *loop = nullptr; #if NAPI_VERSION >= 2 @@ -327,7 +327,7 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr ANS_LOGE("sortingMap is null"); return; } - ANS_LOGI("OnUpdate sortingMap size = %{public}d", sortingMap->GetKey().size()); + ANS_LOGI("OnUpdate sortingMap size = %{public}zu", sortingMap->GetKey().size()); uv_loop_s *loop = nullptr; #if NAPI_VERSION >= 2 @@ -736,27 +736,27 @@ napi_value GetNotificationSubscriber( napi_create_reference(env, value, 1, &subscriberInfo.ref); - // onConsumed?:(data: SubscribeCallbackData) => void; - NAPI_CALL(env, napi_has_named_property(env, value, "onConsumed", &hasProperty)); + // onConsume?:(data: SubscribeCallbackData) => void + NAPI_CALL(env, napi_has_named_property(env, value, "onConsume", &hasProperty)); if (hasProperty) { napi_value nOnConsumed = nullptr; - napi_get_named_property(env, value, "onConsumed", &nOnConsumed); + napi_get_named_property(env, value, "onConsume", &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)); + // onCancel?:(data: SubscribeCallbackData) => void + NAPI_CALL(env, napi_has_named_property(env, value, "onCancel", &hasProperty)); if (hasProperty) { napi_value nOnCanceled = nullptr; - napi_get_named_property(env, value, "onCanceled", &nOnCanceled); + napi_get_named_property(env, value, "onCancel", &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; + // onUpdate?:(data: NotificationSortingMap) => void NAPI_CALL(env, napi_has_named_property(env, value, "onUpdate", &hasProperty)); if (hasProperty) { napi_value nOnUpdate = nullptr; @@ -766,41 +766,41 @@ napi_value GetNotificationSubscriber( 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)); + // onConnect?:() => void + NAPI_CALL(env, napi_has_named_property(env, value, "onConnect", &hasProperty)); if (hasProperty) { napi_value nOnConnected = nullptr; - napi_get_named_property(env, value, "onConnected", &nOnConnected); + napi_get_named_property(env, value, "onConnect", &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)); + // 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_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)); + // onDestroy?:() => void + NAPI_CALL(env, napi_has_named_property(env, value, "onDestroy", &hasProperty)); if (hasProperty) { napi_value nOnDied = nullptr; - napi_get_named_property(env, value, "onDied", &nOnDied); + napi_get_named_property(env, value, "onDestroy", &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); } - // onDisturbModeChanged?:(mode: notification.DoNotDisturbMode) => void; - NAPI_CALL(env, napi_has_named_property(env, value, "onDisturbModeChanged", &hasProperty)); + // onDisturbModeChange?:(mode: notification.DoNotDisturbMode) => void + NAPI_CALL(env, napi_has_named_property(env, value, "onDisturbModeChange", &hasProperty)); if (hasProperty) { napi_value nOnDisturbModeChanged = nullptr; - napi_get_named_property(env, value, "onDisturbModeChanged", &nOnDisturbModeChanged); + napi_get_named_property(env, value, "onDisturbModeChange", &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); @@ -897,9 +897,9 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[2]:callback if (argc >= SUBSRIBE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[SUBSRIBE_MAX_PARA - 1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[2], 1, &callback); + napi_create_reference(env, argv[SUBSRIBE_MAX_PARA - 1], 1, &callback); } return Common::NapiGetNull(env); diff --git a/interfaces/kits/napi/wantagent/napi_want_agent.cpp b/interfaces/kits/napi/wantagent/napi_want_agent.cpp index 1369b64e9..0f3471045 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.cpp +++ b/interfaces/kits/napi/wantagent/napi_want_agent.cpp @@ -55,7 +55,7 @@ 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) { @@ -92,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; @@ -142,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; @@ -183,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), @@ -209,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), @@ -243,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; @@ -252,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]); @@ -303,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); @@ -320,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."); @@ -363,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; @@ -372,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]); @@ -423,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); @@ -439,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."); @@ -482,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; @@ -491,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]); } @@ -541,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); @@ -557,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."); @@ -618,7 +619,7 @@ napi_value NAPI_CancelWrap( [](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; @@ -627,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]); @@ -680,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); @@ -696,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."); @@ -757,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); @@ -817,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; } @@ -836,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); @@ -867,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; @@ -876,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]); @@ -928,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); @@ -954,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; } @@ -969,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[2], 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) { @@ -1010,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; @@ -1039,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]); @@ -1123,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); @@ -1211,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 90b67e8e9..e5bf33c25 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/services/ans/BUILD.gn b/services/ans/BUILD.gn index a062596c3..629d4414e 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -67,6 +67,7 @@ ohos_shared_library("libans") { "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//utils/native/base:utils", ] diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index bfd654130..103c4c10d 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -80,13 +80,13 @@ private: NotificationPreferencesInfo &preferencesInfo) const; ErrCode CheckGroupForUpdateSlotGroup(const sptr &bundleOption, const sptr &group, NotificationPreferencesInfo &preferencesInfo) const; - template + template ErrCode SetBundleProperty(NotificationPreferencesInfo &preferencesInfo, const sptr &bundleOption, const BundleType &type, const T &value); - template + template ErrCode SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, const sptr &bundleOption, const BundleType &type, const T &value); - template + template ErrCode GetBundleProperty(const sptr &bundleOption, const BundleType &type, T &value) const; std::string GenerateBundleKey(const sptr &bundleOption) const; diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 2425af407..ef1f360a7 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -59,7 +59,7 @@ private: bool CheckBundle(const std::string &bundleKey); bool PutBundlePropertyValueToDisturbeDB(const NotificationPreferencesInfo::BundleInfo &bundleInfo); - template + template OHOS::DistributedKv::Status PutBundlePropertyToDisturbeDB( const std::string &bundleKey, const BundleType &type, const T &t); bool PutBundleToDisturbeDB( diff --git a/services/ans/include/notification_preferences_info.h b/services/ans/include/notification_preferences_info.h index 55ef82b58..4e7845325 100644 --- a/services/ans/include/notification_preferences_info.h +++ b/services/ans/include/notification_preferences_info.h @@ -64,15 +64,15 @@ public: int GetBundleUid() const; private: - std::string bundleName_ {}; - int uid_ {}; + std::string bundleName_; + int uid_ = 0; 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() @@ -92,7 +92,7 @@ public: private: bool isEnabledAllNotification_ = true; NotificationConstant::DisturbMode disturbMode_ = NotificationConstant::DisturbMode::ALLOW_ALL; - std::map infos_ {}; + std::map infos_; }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 878f46991..9305c21b5 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -41,19 +41,22 @@ 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 { - sptr notification{nullptr}; - bool isActive{false}; - int deleteReason{0}; - int64_t deleteTime{0}; + sptr notification = nullptr; + bool isActive = false; + int deleteReason = 0; + int64_t deleteTime = 0; }; } // namespace struct AdvancedNotificationService::RecentInfo { - std::list> list{}; - size_t recentCount{DEFAULT_RECENT_COUNT}; + std::list> list; + size_t recentCount = DEFAULT_RECENT_COUNT; }; sptr AdvancedNotificationService::instance_; @@ -119,6 +122,35 @@ inline ErrCode AssignValidNotificationSlot(const std::shared_ptr &request) +{ + ErrCode result = ERR_OK; + + auto content = request->GetContent(); + if (content != nullptr && content->GetContentType() == NotificationContent::Type::PICTURE) { + std::shared_ptr pictureContent = + std::static_pointer_cast(content->GetNotificationContent()); + if (pictureContent != nullptr) { + auto picture = pictureContent->GetBigPicture(); + if (picture != nullptr && (uint32_t)picture->GetByteCount() > MAX_PICTURE_SIZE) { + result = ERR_ANS_PICTURE_OVER_SIZE; + } + } + } + + auto littleIcon = request->GetLittleIcon(); + if (littleIcon != nullptr && (uint32_t)littleIcon->GetByteCount() > MAX_ICON_SIZE) { + result = ERR_ANS_ICON_OVER_SIZE; + } + + auto bigIcon = request->GetBigIcon(); + if (bigIcon != nullptr && (uint32_t)bigIcon->GetByteCount() > MAX_ICON_SIZE) { + result = ERR_ANS_ICON_OVER_SIZE; + } + + return result; +} + inline ErrCode PrepereNotificationRequest(const sptr &request) { std::string bundle = GetClientBundleName(); @@ -134,7 +166,9 @@ inline ErrCode PrepereNotificationRequest(const sptr &reque request->SetCreatorUid(uid); request->SetCreatorPid(pid); - return ERR_OK; + ErrCode result = CheckPictureSize(request); + + return result; } sptr AdvancedNotificationService::GetInstance() @@ -148,7 +182,9 @@ sptr AdvancedNotificationService::GetInstance() } AdvancedNotificationService::AdvancedNotificationService() - : systemEventObserver_({std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1)}) + : systemEventObserver_({ + std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1), + }) { runner_ = OHOS::AppExecFwk::EventRunner::Create(); handler_ = std::make_shared(runner_); @@ -1123,18 +1159,14 @@ ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed) { ANS_LOGD("%{public}s", __FUNCTION__); - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; } ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { allowed = false; result = NotificationPreferences::GetInstance().GetNotificationsEnabled(allowed); - if (result == ERR_OK && allowed) { - result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleOption, allowed); - } })); return result; } @@ -1249,7 +1281,7 @@ 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; } diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 94175a711..a937d9018 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -141,6 +141,7 @@ ErrCode NotificationPreferences::RemoveNotificationAllSlots(const sptrRemoveAllSlotsFromDisturbeDB(GenerateBundleKey(bundleOption))) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -389,8 +390,7 @@ ErrCode NotificationPreferences::SetShowBadge(const sptr &, std::string &)>> NotificationPreferencesDatabase::slotMap_ = { - {KEY_SLOT_GROUPID, + { + KEY_SLOT_GROUPID, std::bind(&NotificationPreferencesDatabase::ParseSlotGroupId, std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3)}, - {KEY_SLOT_DESCRIPTION, + std::placeholders::_3), + }, + { + KEY_SLOT_DESCRIPTION, std::bind(&NotificationPreferencesDatabase::ParseSlotDescription, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_SLOT_LEVEL, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_SLOT_LEVEL, std::bind(&NotificationPreferencesDatabase::ParseSlotLevel, std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3)}, - {KEY_SLOT_SHOW_BADGE, + std::placeholders::_3), + }, + { + KEY_SLOT_SHOW_BADGE, std::bind(&NotificationPreferencesDatabase::ParseSlotShowBadge, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_SLOT_ENABLE_LIGHT, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_SLOT_ENABLE_LIGHT, std::bind(&NotificationPreferencesDatabase::ParseSlotEnableLight, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_SLOT_ENABLE_VRBRATION, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_SLOT_ENABLE_VRBRATION, std::bind(&NotificationPreferencesDatabase::ParseSlotEnableVrbration, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_SLOT_LED_LIGHT_COLOR, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_SLOT_LED_LIGHT_COLOR, std::bind(&NotificationPreferencesDatabase::ParseSlotLedLightColor, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_SLOT_LOCKSCREEN_VISIBLENESS, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_SLOT_LOCKSCREEN_VISIBLENESS, std::bind(&NotificationPreferencesDatabase::ParseSlotLockscreenVisibleness, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_SLOT_SOUND, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_SLOT_SOUND, std::bind(&NotificationPreferencesDatabase::ParseSlotSound, std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3)}, - {KEY_SLOT_VIBRATION_STYLE, + std::placeholders::_3), + }, + { + KEY_SLOT_VIBRATION_STYLE, std::bind(&NotificationPreferencesDatabase::ParseSlotVibrationSytle, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_SLOT_VIBRATION_STYLE, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_SLOT_VIBRATION_STYLE, std::bind(&NotificationPreferencesDatabase::ParseSlotEnableBypassDnd, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}}; + std::placeholders::_2, std::placeholders::_3), + }}; const std::map> NotificationPreferencesDatabase::bundleMap_ = { - {KEY_BUNDLE_NAME, + { + KEY_BUNDLE_NAME, std::bind(&NotificationPreferencesDatabase::ParseBundleName, std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3)}, - {KEY_BUNDLE_IMPORTANCE, + std::placeholders::_3), + }, + { + KEY_BUNDLE_IMPORTANCE, std::bind(&NotificationPreferencesDatabase::ParseBundleImportance, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_BUNDLE_SHOW_BADGE, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_BUNDLE_SHOW_BADGE, std::bind(&NotificationPreferencesDatabase::ParseBundleShowBadge, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_BUNDLE_BADGE_TOTAL_NUM, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_BUNDLE_BADGE_TOTAL_NUM, std::bind(&NotificationPreferencesDatabase::ParseBundleBadgeNum, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_BUNDLE_PRIVATE_ALLOWED, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_BUNDLE_PRIVATE_ALLOWED, std::bind(&NotificationPreferencesDatabase::ParseBundlePrivateAllowed, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, - {KEY_BUNDLE_ENABLE_NOTIFICATION, + std::placeholders::_2, std::placeholders::_3), + }, + { + KEY_BUNDLE_ENABLE_NOTIFICATION, std::bind(&NotificationPreferencesDatabase::ParseBundleEnableNotification, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}}; + std::placeholders::_2, std::placeholders::_3), + }}; NotificationPreferencesDatabase::NotificationPreferencesDatabase() { @@ -105,10 +139,12 @@ void NotificationPreferencesDatabase::TryTwice(const std::function entries; - status = kvStorePtr_->GetEntries({KEY_BUNDLE_LABEL}, entries); + status = kvStorePtr_->GetEntries(DistributedKv::Key(KEY_BUNDLE_LABEL), entries); if (status != OHOS::DistributedKv::Status::SUCCESS) { ANS_LOGE("Get Bundle Info failed."); return false; @@ -486,7 +522,8 @@ bool NotificationPreferencesDatabase::RemoveBundleFromDisturbeDB(const std::stri OHOS::DistributedKv::Status status; std::vector entries; - status = kvStorePtr_->GetEntries({KEY_ANS_BUNDLE + KEY_UNDER_LINE + bundleKey + KEY_UNDER_LINE}, entries); + status = kvStorePtr_->GetEntries( + DistributedKv::Key(KEY_ANS_BUNDLE + KEY_UNDER_LINE + bundleKey + KEY_UNDER_LINE), entries); if (status != OHOS::DistributedKv::Status::SUCCESS) { ANS_LOGE("Get Bundle Info failed."); @@ -498,7 +535,7 @@ bool NotificationPreferencesDatabase::RemoveBundleFromDisturbeDB(const std::stri keys.push_back(iter.key); } - OHOS::DistributedKv::Key bundleDBKey({KEY_BUNDLE_LABEL + KEY_BUNDLE_NAME + KEY_UNDER_LINE + 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) { @@ -525,7 +562,8 @@ bool NotificationPreferencesDatabase::RemoveSlotFromDisturbeDB( OHOS::DistributedKv::Status status; std::vector slotentries; std::string slotType = std::to_string(type); - status = kvStorePtr_->GetEntries({GenerateSlotKey(bundleKey, slotType) + KEY_UNDER_LINE}, slotentries); + status = + kvStorePtr_->GetEntries(DistributedKv::Key(GenerateSlotKey(bundleKey, slotType) + KEY_UNDER_LINE), slotentries); if (status != DistributedKv::Status::SUCCESS) { return false; } @@ -559,7 +597,7 @@ bool NotificationPreferencesDatabase::RemoveAllSlotsFromDisturbeDB(const std::st OHOS::DistributedKv::Status status; std::vector slotsEntries; - status = kvStorePtr_->GetEntries({GenerateSlotKey(bundleKey) + KEY_UNDER_LINE}, slotsEntries); + status = kvStorePtr_->GetEntries(DistributedKv::Key(GenerateSlotKey(bundleKey) + KEY_UNDER_LINE), slotsEntries); if (status != DistributedKv::Status::SUCCESS) { return false; } @@ -616,7 +654,7 @@ bool NotificationPreferencesDatabase::GetRemoveGroupKeysFromDisturbeDB( OHOS::DistributedKv::Status status; std::vector groupentries; std::string slotKeyStr = GenerateGroupKey(bundleKey, groupId); - status = kvStorePtr_->GetEntries({slotKeyStr + KEY_UNDER_LINE}, groupentries); + status = kvStorePtr_->GetEntries(DistributedKv::Key(slotKeyStr + KEY_UNDER_LINE), groupentries); if (status != DistributedKv::Status::SUCCESS) { return false; } @@ -791,7 +829,7 @@ void NotificationPreferencesDatabase::ParseBundleFromDistureDB( std::string bundleKey = item.value.ToString(); ANS_LOGD("Bundle name is %{public}s.", bundleKey.c_str()); std::vector bundleEntries; - kvStorePtr_->GetEntries({GenerateBundleKey(bundleKey)}, bundleEntries); + kvStorePtr_->GetEntries(DistributedKv::Key(GenerateBundleKey(bundleKey)), bundleEntries); ANS_LOGD("Bundle key is %{public}s.", GenerateBundleKey(bundleKey).c_str()); NotificationPreferencesInfo::BundleInfo bunldeInfo; for (auto bundleEntry : bundleEntries) { @@ -927,7 +965,7 @@ int NotificationPreferencesDatabase::StringToInt(const std::string &str) const std::string NotificationPreferencesDatabase::GenerateSlotKey( const std::string &bundleKey, const std::string &type, const std::string &subType) const { - /*slot key + /* slot key * * KEY_ANS_BUNDLE_bundlename_slot_type_0_id * KEY_ANS_BUNDLE_bundlename_slot_type_0_des @@ -949,7 +987,7 @@ std::string NotificationPreferencesDatabase::GenerateSlotKey( std::string NotificationPreferencesDatabase::GenerateGroupKey( const std::string &bundleKey, const std::string &type) const { - /*group key + /* group key * * KEY_ANS_BUNDLE_bundlename_group_id_id0_id: * KEY_ANS_BUNDLE_bundlename_group_id_id0_name: @@ -967,7 +1005,7 @@ std::string NotificationPreferencesDatabase::GenerateGroupKey( std::string NotificationPreferencesDatabase::GenerateBundleKey( const std::string &bundleKey, const std::string &type) const { - /*bundle key + /* bundle key * * label_KEY_ANS_KEY_BUNDLE_NAME = "" * KEY_ANS_BUNDLE_bundlename_ diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 8da3be02e..3179f766d 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -81,6 +81,7 @@ ohos_unittest("ans_unit_test") { "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index 90d0cbc84..8d7d215f3 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -30,6 +30,7 @@ #include "notification_subscriber.h" using namespace testing::ext; +using namespace OHOS::Media; namespace OHOS { namespace Notification { @@ -116,6 +117,7 @@ void AdvancedNotificationServiceTest::TestAddSlotGroup() groups.push_back(group); advancedNotificationService_->AddSlotGroups(groups); } + /** * @tc.number : AMS_ANS_Publish_00100 * @tc.name : ANSPublish00100 @@ -412,7 +414,8 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01200, /** * @tc.number : AMS_ANS_Publish_01300 * @tc.name : ANSPublish01300 - * @tc.desc : When a bundle is not allowed to publish a notification, the notification publishing interface returns + * @tc.desc : When a bundle is not allowed to publish a notification, the notification publishing interface + returns * ERR_ANS_NOT_ALLOWED */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01300, Function | SmallTest | Level1) @@ -1209,18 +1212,6 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09300, (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 @@ -1228,9 +1219,10 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09500, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09600, Function | SmallTest | Level1) { - TestAddSlot(NotificationConstant::SlotType::OTHER); + EXPECT_EQ((int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); bool allowed = false; EXPECT_EQ((int)advancedNotificationService_->IsAllowedNotify(allowed), (int)ERR_OK); + EXPECT_TRUE(allowed); } /** @@ -1274,5 +1266,119 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09900, (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); } +inline std::shared_ptr MakePixelMap(int32_t width, int32_t height) +{ + const int32_t PIXEL_BYTES = 4; + std::shared_ptr pixelMap = std::make_shared(); + ImageInfo info; + info.size.width = width; + info.size.height = height; + info.pixelFormat = PixelFormat::ARGB_8888; + info.colorSpace = ColorSpace::SRGB; + pixelMap->SetImageInfo(info); + int32_t rowDataSize = width * PIXEL_BYTES; + uint32_t bufferSize = rowDataSize * height; + void *buffer = malloc(bufferSize); + EXPECT_NE(buffer, nullptr); + pixelMap->SetPixelsAddr(buffer, nullptr, bufferSize, AllocatorType::HEAP_ALLOC, nullptr); + return pixelMap; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_10000 + * @tc.name : AMS_ANS_Publish_With_PixelMap + * @tc.desc : Publish a notification with pixelMap. + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10000, Function | SmallTest | Level1) +{ + const int BIG_PICTURE_WIDTH = 400; + const int BIG_PICTURE_HEIGHT = 300; + const int ICON_SIZE = 36; + + sptr req = new NotificationRequest(1); + EXPECT_NE(req, nullptr); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("label"); + std::shared_ptr pictureContent = std::make_shared(); + EXPECT_NE(pictureContent, nullptr); + pictureContent->SetText("notification text"); + pictureContent->SetTitle("notification title"); + std::shared_ptr bigPicture = MakePixelMap(BIG_PICTURE_WIDTH, BIG_PICTURE_HEIGHT); + EXPECT_NE(bigPicture, nullptr); + pictureContent->SetBigPicture(bigPicture); + std::shared_ptr content = std::make_shared(pictureContent); + EXPECT_NE(content, nullptr); + req->SetContent(content); + std::shared_ptr littleIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req->SetLittleIcon(littleIcon); + std::shared_ptr bigIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req->SetBigIcon(bigIcon); + EXPECT_EQ(advancedNotificationService_->Publish("label", req), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_10100 + * @tc.name : AMS_ANS_Publish_With_PixelMap_Oversize_00100 + * @tc.desc : Publish a notification with oversize pixelMap. + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10100, Function | SmallTest | Level1) +{ + const int BIG_PICTURE_WIDTH = 1024; + const int BIG_PICTURE_HEIGHT = 1024; + const int ICON_SIZE = 36; + + sptr req = new NotificationRequest(1); + EXPECT_NE(req, nullptr); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("label"); + std::shared_ptr pictureContent = std::make_shared(); + EXPECT_NE(pictureContent, nullptr); + pictureContent->SetText("notification text"); + pictureContent->SetTitle("notification title"); + std::shared_ptr bigPicture = MakePixelMap(BIG_PICTURE_WIDTH, BIG_PICTURE_HEIGHT); + EXPECT_NE(bigPicture, nullptr); + pictureContent->SetBigPicture(bigPicture); + std::shared_ptr content = std::make_shared(pictureContent); + EXPECT_NE(content, nullptr); + req->SetContent(content); + std::shared_ptr littleIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req->SetLittleIcon(littleIcon); + std::shared_ptr bigIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req->SetBigIcon(bigIcon); + EXPECT_EQ(advancedNotificationService_->Publish("label", req), (int)ERR_ANS_PICTURE_OVER_SIZE); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_10200 + * @tc.name : AMS_ANS_Publish_With_PixelMap_Oversize_00200 + * @tc.desc : Publish a notification with oversize pixelMap. + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10200, Function | SmallTest | Level1) +{ + const int BIG_PICTURE_WIDTH = 400; + const int BIG_PICTURE_HEIGHT = 300; + const int ICON_SIZE = 256; + + sptr req = new NotificationRequest(1); + EXPECT_NE(req, nullptr); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("label"); + std::shared_ptr pictureContent = std::make_shared(); + EXPECT_NE(pictureContent, nullptr); + pictureContent->SetText("notification text"); + pictureContent->SetTitle("notification title"); + std::shared_ptr bigPicture = MakePixelMap(BIG_PICTURE_WIDTH, BIG_PICTURE_HEIGHT); + EXPECT_NE(bigPicture, nullptr); + pictureContent->SetBigPicture(bigPicture); + std::shared_ptr content = std::make_shared(pictureContent); + EXPECT_NE(content, nullptr); + req->SetContent(content); + std::shared_ptr littleIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req->SetLittleIcon(littleIcon); + std::shared_ptr bigIcon = MakePixelMap(ICON_SIZE, ICON_SIZE); + req->SetBigIcon(bigIcon); + EXPECT_EQ(advancedNotificationService_->Publish("label", req), (int)ERR_ANS_ICON_OVER_SIZE); +} + } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/ans_ut_constant.h b/services/ans/test/unittest/ans_ut_constant.h index 147379994..886634b71 100644 --- a/services/ans/test/unittest/ans_ut_constant.h +++ b/services/ans/test/unittest/ans_ut_constant.h @@ -20,15 +20,10 @@ namespace OHOS { namespace Notification { - -namespace { 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 - } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/mock/include/mock_single_kv_store.h b/services/ans/test/unittest/mock/include/mock_single_kv_store.h index 8a777ea02..f32d46b6d 100644 --- a/services/ans/test/unittest/mock/include/mock_single_kv_store.h +++ b/services/ans/test/unittest/mock/include/mock_single_kv_store.h @@ -19,13 +19,13 @@ #include #include +#include "data_query.h" #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" +#include "types.h" namespace OHOS { namespace DistributedKv { @@ -33,218 +33,72 @@ namespace DistributedKv { // 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 GetResultSet( + const Key &prefixKey, std::function)> callback) const override; + 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. + std::function)> callback) const override; + + virtual void GetResultSetWithQuery( + const DataQuery &query, std::function)> callback) const override; + 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 Sync( + const std::vector &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs = 0) override; + 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; + 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 DistributedKv } // namespace OHOS #endif // SINGLE_KV_STORE_H diff --git a/services/ans/test/unittest/mock/mock_ipc.cpp b/services/ans/test/unittest/mock/mock_ipc.cpp index 42687ac92..6f08e07f8 100644 --- a/services/ans/test/unittest/mock/mock_ipc.cpp +++ b/services/ans/test/unittest/mock/mock_ipc.cpp @@ -34,6 +34,6 @@ pid_t IPCSkeleton::GetCallingPid() void IPCSkeleton::SetCallingUid(pid_t uid) { - uid_ = uid; + uid_ = uid; } } // namespace OHOS diff --git a/services/ans/test/unittest/mock/mock_single_kv_store.cpp b/services/ans/test/unittest/mock/mock_single_kv_store.cpp index 4f9c78aa8..85aed3fef 100644 --- a/services/ans/test/unittest/mock/mock_single_kv_store.cpp +++ b/services/ans/test/unittest/mock/mock_single_kv_store.cpp @@ -18,127 +18,60 @@ 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; @@ -146,70 +79,31 @@ StoreId AnsTestSingleKvStore::GetStoreId() const 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; @@ -225,55 +119,31 @@ 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; diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index 740e3b895..7711118f9 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -80,6 +80,7 @@ ohos_moduletest("ans_module_test") { "//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", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp index b9a2f3535..fa3d4c130 100644 --- a/services/test/moduletest/ans_module_test.cpp +++ b/services/test/moduletest/ans_module_test.cpp @@ -72,10 +72,10 @@ public: } } - ConsumedFunc consumedCb_{nullptr}; - CanceledFunc canceledCb_{nullptr}; - std::function unSubscriberCb_{nullptr}; - std::function subscriberCb_{nullptr}; + ConsumedFunc consumedCb_ = nullptr; + CanceledFunc canceledCb_ = nullptr; + std::function unSubscriberCb_ = nullptr; + std::function subscriberCb_ = nullptr; }; class AnsModuleTest : public testing::Test { @@ -2324,46 +2324,31 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0122, Function | SmallTest | Level1) HWTEST_F(AnsModuleTest, AnsModuleTest_0123, Function | SmallTest | Level1) { int ret = 0; - - // subscriber auto subscriber = new TestAnsSubscriber(); g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr); subscriber->consumedCb_ = [&ret](const std::shared_ptr notification, const std::shared_ptr sortingMap) { ret++; }; - subscriber->canceledCb_ = [](const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason) { passed = true; }; - - // add slot std::vector> slots; - sptr socialSlot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr reminderSlot = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); - sptr contentSlot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); - sptr otherSlot = new NotificationSlot(NotificationConstant::SlotType::OTHER); - sptr customSlot = new NotificationSlot(NotificationConstant::SlotType::CUSTOM); - - slots.push_back(socialSlot); - slots.push_back(reminderSlot); - slots.push_back(contentSlot); - slots.push_back(otherSlot); - slots.push_back(customSlot); - + slots.push_back(new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION)); + slots.push_back(new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER)); + slots.push_back(new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION)); + slots.push_back(new NotificationSlot(NotificationConstant::SlotType::OTHER)); + slots.push_back(new NotificationSlot(NotificationConstant::SlotType::CUSTOM)); EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), 0); - - // create request - std::string label = "testLabel"; sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); sptr req2 = new NotificationRequest(2); sptr req3 = new NotificationRequest(3); sptr req4 = new NotificationRequest(4); - req->SetLabel(label); - req1->SetLabel(label); - req2->SetLabel(label); - req3->SetLabel(label); - req4->SetLabel(label); + req->SetLabel("testLabel"); + req1->SetLabel("testLabel"); + req2->SetLabel("testLabel"); + req3->SetLabel("testLabel"); + req4->SetLabel("testLabel"); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); req1->SetSlotType(NotificationConstant::SlotType::SERVICE_REMINDER); @@ -2371,17 +2356,16 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0123, Function | SmallTest | Level1) req3->SetSlotType(NotificationConstant::SlotType::OTHER); req4->SetSlotType(NotificationConstant::SlotType::CUSTOM); - g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish("testLabel", req); EXPECT_EQ(ret, 0); - g_advancedNotificationService->Publish(label, req1); + g_advancedNotificationService->Publish("testLabel", req1); EXPECT_EQ(ret, 0); - g_advancedNotificationService->Publish(label, req2); + g_advancedNotificationService->Publish("testLabel", req2); EXPECT_EQ(ret, 0); - g_advancedNotificationService->Publish(label, req3); + g_advancedNotificationService->Publish("testLabel", req3); EXPECT_EQ(ret, 0); - g_advancedNotificationService->Publish(label, req4); + g_advancedNotificationService->Publish("testLabel", req4); EXPECT_EQ(ret, 0); - g_advancedNotificationService->DeleteAll(); g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); EXPECT_FALSE(passed); @@ -2620,10 +2604,8 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0130, Function | SmallTest | Level1) // subscriber auto subscriber = new TestAnsSubscriber(); g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr); - subscriber->consumedCb_ = []( - const std::shared_ptr notification, - const std::shared_ptr sortingMap) - { + subscriber->consumedCb_ = + [](const std::shared_ptr notification, const std::shared_ptr sortingMap) { EXPECT_EQ(false, notification->EnableVibrate()); EXPECT_EQ(NotificationConstant::VisiblenessType::PUBLIC, notification->GetLockscreenVisibleness()); }; diff --git a/services/test/moduletest/mock/distributed_kv_data_manager.cpp b/services/test/moduletest/mock/distributed_kv_data_manager.cpp index 656932c20..d755b0151 100644 --- a/services/test/moduletest/mock/distributed_kv_data_manager.cpp +++ b/services/test/moduletest/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" diff --git a/services/test/moduletest/mock/include/mock_single_kv_store.h b/services/test/moduletest/mock/include/mock_single_kv_store.h index 8a777ea02..f32d46b6d 100644 --- a/services/test/moduletest/mock/include/mock_single_kv_store.h +++ b/services/test/moduletest/mock/include/mock_single_kv_store.h @@ -19,13 +19,13 @@ #include #include +#include "data_query.h" #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" +#include "types.h" namespace OHOS { namespace DistributedKv { @@ -33,218 +33,72 @@ namespace DistributedKv { // 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 GetResultSet( + const Key &prefixKey, std::function)> callback) const override; + 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. + std::function)> callback) const override; + + virtual void GetResultSetWithQuery( + const DataQuery &query, std::function)> callback) const override; + 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 Sync( + const std::vector &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs = 0) override; + 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; + 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 DistributedKv } // namespace OHOS #endif // SINGLE_KV_STORE_H diff --git a/services/test/moduletest/mock/mock_bundle_manager.cpp b/services/test/moduletest/mock/mock_bundle_manager.cpp index 340c592c3..98d2bcac2 100644 --- a/services/test/moduletest/mock/mock_bundle_manager.cpp +++ b/services/test/moduletest/mock/mock_bundle_manager.cpp @@ -19,6 +19,9 @@ namespace OHOS { namespace AppExecFwk { + +constexpr int SYSTEMAPP_UUID = 1000; + void MockBundleMgrService::MockSetIsSystemApp(bool isSystemApp) { isSystemAppMock_ = true; @@ -30,7 +33,7 @@ bool MockBundleMgrService::CheckIsSystemAppByUid(const int uid) if (isSystemAppMock_) { return isSystemApp_; } - return (uid < 1000) ? false : true; + return (uid < SYSTEMAPP_UUID) ? false : true; } int MockBundleMgrService::CheckPermission(const std::string &bundleName, const std::string &permission) diff --git a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp index 7654e493f..5738fc881 100644 --- a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -258,13 +258,13 @@ bool BundleMgrProxy::UnregisterPermissionsChanged(const sptr +template bool BundleMgrProxy::GetParcelableInfo(IBundleMgr::Message code, MessageParcel &data, T &parcelableInfo) { return true; } -template +template bool BundleMgrProxy::GetParcelableInfos(IBundleMgr::Message code, MessageParcel &data, std::vector &parcelableInfos) { return true; diff --git a/services/test/moduletest/mock/mock_event_handler.cpp b/services/test/moduletest/mock/mock_event_handler.cpp index 4fcdd4a2c..12a7f65b9 100644 --- a/services/test/moduletest/mock/mock_event_handler.cpp +++ b/services/test/moduletest/mock/mock_event_handler.cpp @@ -17,108 +17,94 @@ #include "event_handler_utils.h" #include -namespace OHOS +namespace OHOS { +namespace AppExecFwk { + +std::shared_ptr EventHandler::Current() +{ + const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); + return wp.lock(); +} + +EventHandler::EventHandler(const std::shared_ptr &runner) : eventRunner_(runner) +{} + +EventHandler::~EventHandler() +{} + +bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Priority priority) +{ + std::function callback = event->GetTaskCallback(); + callback(); + return true; +} + +bool EventHandler::SendTimingEvent(InnerEvent::Pointer &event, int64_t taskTime, Priority priority) +{ + return true; +} + +bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority) +{ + std::function callback = event->GetTaskCallback(); + callback(); + return true; +} + +void EventHandler::RemoveAllEvents() +{} + +void EventHandler::RemoveEvent(uint32_t innerEventId) +{} + +void EventHandler::RemoveEvent(uint32_t innerEventId, int64_t param) +{} + +void EventHandler::RemoveTask(const std::string &name) +{} + +ErrCode EventHandler::AddFileDescriptorListener( + int32_t fileDescriptor, uint32_t events, const std::shared_ptr &listener) { - namespace AppExecFwk - { - - std::shared_ptr EventHandler::Current() - { - const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); - return wp.lock(); - } - - EventHandler::EventHandler(const std::shared_ptr &runner) : eventRunner_(runner) - { - } - - EventHandler::~EventHandler() - { - } - - bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Priority priority) - { - std::function callback = event->GetTaskCallback(); - callback(); - return true; - } - - bool EventHandler::SendTimingEvent(InnerEvent::Pointer &event, int64_t taskTime, Priority priority) - { - return true; - } - - bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority) - { - std::function callback = event->GetTaskCallback(); - callback(); - return true; - } - - void EventHandler::RemoveAllEvents() - { - } - - void EventHandler::RemoveEvent(uint32_t innerEventId) - { - } - - void EventHandler::RemoveEvent(uint32_t innerEventId, int64_t param) - { - } - - void EventHandler::RemoveTask(const std::string &name) - { - } - - ErrCode EventHandler::AddFileDescriptorListener( - int32_t fileDescriptor, uint32_t events, const std::shared_ptr &listener) - { - return EVENT_HANDLER_ERR_INVALID_PARAM; - } - - void EventHandler::RemoveAllFileDescriptorListeners() - { - } - - void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) - { - } - - void EventHandler::SetEventRunner(const std::shared_ptr &runner) - { - } - - void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) - { - } - - void EventHandler::Dump(Dumper &dumper) - { - } - - bool EventHandler::HasInnerEvent(uint32_t innerEventId) - { - return true; - } - - bool EventHandler::HasInnerEvent(int64_t param) - { - return true; - } - - std::string EventHandler::GetEventName(const InnerEvent::Pointer &event) - { - return "132123"; - } - - bool EventHandler::IsIdle() - { - return true; - } - - void EventHandler::ProcessEvent(const InnerEvent::Pointer &) - { - } - } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file + return EVENT_HANDLER_ERR_INVALID_PARAM; +} + +void EventHandler::RemoveAllFileDescriptorListeners() +{} + +void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) +{} + +void EventHandler::SetEventRunner(const std::shared_ptr &runner) +{} + +void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) +{} + +void EventHandler::Dump(Dumper &dumper) +{} + +bool EventHandler::HasInnerEvent(uint32_t innerEventId) +{ + return true; +} + +bool EventHandler::HasInnerEvent(int64_t param) +{ + return true; +} + +std::string EventHandler::GetEventName(const InnerEvent::Pointer &event) +{ + return "132123"; +} + +bool EventHandler::IsIdle() +{ + return true; +} + +void EventHandler::ProcessEvent(const InnerEvent::Pointer &) +{} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/mock/mock_single_kv_store.cpp b/services/test/moduletest/mock/mock_single_kv_store.cpp index 4b580d297..85aed3fef 100644 --- a/services/test/moduletest/mock/mock_single_kv_store.cpp +++ b/services/test/moduletest/mock/mock_single_kv_store.cpp @@ -18,132 +18,60 @@ 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 -{ - -} +void AnsTestSingleKvStore::GetResultSet( + const Key &prefixKey, 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 -{ +void AnsTestSingleKvStore::GetResultSetWithQuery( + const std::string &query, std::function)> callback) const +{} -} +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) +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; @@ -151,70 +79,31 @@ StoreId AnsTestSingleKvStore::GetStoreId() const 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; @@ -230,56 +119,31 @@ 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; @@ -290,8 +154,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 +170,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/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h b/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h index d745fbf31..cdab5c143 100644 --- a/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h +++ b/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h @@ -18,7 +18,7 @@ #include #include "ability_loader.h" -#include +#include "notification_helper.h" #ifdef PRINT_LOG #undef PRINT_LOG #endif diff --git a/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp index c54f270f7..a1efa3a98 100644 --- a/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp +++ b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp @@ -14,22 +14,23 @@ */ #include "ans_slotgroup_test.h" -#include +#include "notification_slot_group.h" namespace OHOS { namespace AppExecFwk { void AnsSlotGroupSystemTest::OnStart(const Want &want) { - APP_LOGI("====> ans SlotGroup test start:====>"); + 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); + APP_LOGI("====> ansSlotGroupTest add:====> %{public}d", errcodeAdd); Notification::NotificationSlot notificationSlotFirst( Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION); @@ -42,37 +43,26 @@ void AnsSlotGroupSystemTest::OnStart(const Want &want) 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); + 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}d", - group->GetSlots().size()); + APP_LOGI("====> ansSlotGroupTest get:====> %{public}d", errcodeGet); + + if (group != nullptr) { + std::string dumpGroupStr = group->Dump(); + APP_LOGI("====> ansSlotGroupTest dump:====> %{public}s", dumpGroupStr.c_str()); + APP_LOGI("====> ansSlotGroupTest the size of slots:====> %{public}zu", group->GetSlots().size()); + } else { + APP_LOGI("====>group is null====>"); + } ErrCode errcodeRem = Notification::NotificationHelper::RemoveNotificationSlotGroup("id_test"); - APP_LOGI("====> ansSlotGroupTest:: remove remove remove remove :" - "====> %{public}d", - errcodeRem); + APP_LOGI("====> ansSlotGroupTest 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); - APP_LOGI("====> ansSlotGroupTest:: the size of slots :" - "====> %{public}d", - groupTwo->GetSlots().size()); + APP_LOGI("====> ansSlotGroupTest get:====> %{public}d", errcodeGetTwo); Ability::OnStart(want); } diff --git a/tools/dump/src/notification_shell_command.cpp b/tools/dump/src/notification_shell_command.cpp index a4c105699..8a2969d54 100644 --- a/tools/dump/src/notification_shell_command.cpp +++ b/tools/dump/src/notification_shell_command.cpp @@ -26,6 +26,15 @@ namespace OHOS { namespace Notification { namespace { + +static const struct option OPTIONS[] = { + {"help", no_argument, nullptr, 'h'}, + {"active", no_argument, nullptr, 'A'}, + {"recent", no_argument, nullptr, 'R'}, + {"setRecentCount", required_argument, nullptr, 0}, + {0, 0, 0, 0}, +}; + static const std::string HELP_MSG = "usage: anm []\n" "These are common commands list:\n" " help list available commands\n" @@ -82,19 +91,11 @@ ErrCode NotificationShellCommand::RunAsHelpCommand() ErrCode NotificationShellCommand::RunAsDumpCommand() { - struct option options[] = { - {"help", no_argument, nullptr, 'h'}, - {"active", no_argument, nullptr, 'A'}, - {"recent", no_argument, nullptr, 'R'}, - {"setRecentCount", required_argument, nullptr, 0}, - {0, 0, 0, 0}, - }; - int ind = 0; - int option = getopt_long(argc_, argv_, "hAR", options, &ind); + int option = getopt_long(argc_, argv_, "hAR", OPTIONS, &ind); ErrCode ret = ERR_OK; - std::vector infos{}; + std::vector infos; switch (option) { case 'h': @@ -118,7 +119,7 @@ ErrCode NotificationShellCommand::RunAsDumpCommand() break; case 0: if (ans_ != nullptr) { - ret = ans_->ShellDump(std::string(options[ind].name) + " " + std::string(optarg), infos); + ret = ans_->ShellDump(std::string(OPTIONS[ind].name) + " " + std::string(optarg), infos); } else { ret = ERR_ANS_SERVICE_NOT_CONNECTED; } -- Gitee