diff --git a/kits/BUILD.gn b/frameworks/BUILD.gn similarity index 80% rename from kits/BUILD.gn rename to frameworks/BUILD.gn index e153ff42e6c59135fcb4be85185e5dd2f0acee97..e4053fa5cdcda9218046b82cbb843da4c49f727e 100644 --- a/kits/BUILD.gn +++ b/frameworks/BUILD.gn @@ -11,11 +11,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -group("kits_target") { +group("frameworks_target") { deps = [ - "napi:notification", - "native:native_targets", - "native/wantagent:native_wantagent", - "wantAgent:wantagent", + "ans/core:ans_core_target", + "ans/native:native_targets", + "wantagent:native_wantagent", ] } diff --git a/innerkits/BUILD.gn b/frameworks/ans/core/BUILD.gn similarity index 34% rename from innerkits/BUILD.gn rename to frameworks/ans/core/BUILD.gn index 72b56403ec9bcbedef396ef9f13bfe4882851082..4f52df4d5346907427031355b7ef86149d79b32b 100644 --- a/innerkits/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -13,66 +13,63 @@ import("//base/notification/ans_standard/notification.gni") import("//build/ohos.gni") -ANS_STANDARD_INNERKITS_CORE_PATH = "${innerkits_path}/core" -ANS_STANDARD_INNERKITS_BASE_PATH = "${innerkits_path}/base" - -group("innerkits_target") { - deps = [ ":ans_innerkits" ] +group("ans_core_target") { + deps = [ ":ans_core" ] } config("private_config") { include_dirs = [ "//utils/system/safwk/native/include" ] } -config("public_ans_innerkits_config") { +config("public_ans_core_config") { include_dirs = [ - "${ANS_STANDARD_INNERKITS_CORE_PATH}/include", - "${ANS_STANDARD_INNERKITS_BASE_PATH}/include", - "//foundation/aafwk/standard/interfaces/innerkits/base/include", - "${kits_path}/native/include", + "${core_path}/common/include", + "${core_path}/include", + "${interfaces_path}/innerkits/ans/native/include", + "${interfaces_path}/innerkits/wantAgent/include", "//utils/native/base/include", ] } -ohos_shared_library("ans_innerkits") { +ohos_shared_library("ans_core") { sources = [ - "${ANS_STANDARD_INNERKITS_BASE_PATH}/src/ans_log_wrapper.cpp", - "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_manager_death_recipient.cpp", - "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_manager_proxy.cpp", - "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_manager_stub.cpp", - "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_notification.cpp", - "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_subscriber_proxy.cpp", - "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_subscriber_stub.cpp", - "${kits_path}/native/src/message_user.cpp", - "${kits_path}/native/src/notification.cpp", - "${kits_path}/native/src/notification_action_button.cpp", - "${kits_path}/native/src/notification_basic_content.cpp", - "${kits_path}/native/src/notification_constant.cpp", - "${kits_path}/native/src/notification_content.cpp", - "${kits_path}/native/src/notification_conversational_content.cpp", - "${kits_path}/native/src/notification_conversational_message.cpp", - "${kits_path}/native/src/notification_helper.cpp", - "${kits_path}/native/src/notification_long_text_content.cpp", - "${kits_path}/native/src/notification_media_content.cpp", - "${kits_path}/native/src/notification_multiline_content.cpp", - "${kits_path}/native/src/notification_normal_content.cpp", - "${kits_path}/native/src/notification_picture_content.cpp", - "${kits_path}/native/src/notification_request.cpp", - "${kits_path}/native/src/notification_slot.cpp", - "${kits_path}/native/src/notification_slot_group.cpp", - "${kits_path}/native/src/notification_sorting.cpp", - "${kits_path}/native/src/notification_sorting_map.cpp", - "${kits_path}/native/src/notification_subscribe_info.cpp", - "${kits_path}/native/src/notification_subscriber.cpp", - "${kits_path}/native/src/notification_user_input.cpp", + "${core_path}/common/src/ans_log_wrapper.cpp", + "${core_path}/src/ans_manager_death_recipient.cpp", + "${core_path}/src/ans_manager_proxy.cpp", + "${core_path}/src/ans_manager_stub.cpp", + "${core_path}/src/ans_notification.cpp", + "${core_path}/src/ans_subscriber_proxy.cpp", + "${core_path}/src/ans_subscriber_stub.cpp", + "${frameworks_path}/ans/native/src/message_user.cpp", + "${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_constant.cpp", + "${frameworks_path}/ans/native/src/notification_content.cpp", + "${frameworks_path}/ans/native/src/notification_conversational_content.cpp", + "${frameworks_path}/ans/native/src/notification_conversational_message.cpp", + "${frameworks_path}/ans/native/src/notification_helper.cpp", + "${frameworks_path}/ans/native/src/notification_long_text_content.cpp", + "${frameworks_path}/ans/native/src/notification_media_content.cpp", + "${frameworks_path}/ans/native/src/notification_multiline_content.cpp", + "${frameworks_path}/ans/native/src/notification_normal_content.cpp", + "${frameworks_path}/ans/native/src/notification_picture_content.cpp", + "${frameworks_path}/ans/native/src/notification_request.cpp", + "${frameworks_path}/ans/native/src/notification_slot.cpp", + "${frameworks_path}/ans/native/src/notification_slot_group.cpp", + "${frameworks_path}/ans/native/src/notification_sorting.cpp", + "${frameworks_path}/ans/native/src/notification_sorting_map.cpp", + "${frameworks_path}/ans/native/src/notification_subscribe_info.cpp", + "${frameworks_path}/ans/native/src/notification_subscriber.cpp", + "${frameworks_path}/ans/native/src/notification_user_input.cpp", ] configs = [ ":private_config" ] - public_configs = [ ":public_ans_innerkits_config" ] + public_configs = [ ":public_ans_core_config" ] deps = [ - "${kits_path}/native/wantagent:wantagent_kits", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//utils/native/base:utils", diff --git a/innerkits/base/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h similarity index 86% rename from innerkits/base/include/ans_const_define.h rename to frameworks/ans/core/common/include/ans_const_define.h index 016adbf38d702fef188e4ac8186a17f056270a0e..61e08768ba92c39b3bc6bfecb367f86547408c9c 100644 --- a/innerkits/base/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -20,13 +20,13 @@ namespace OHOS { namespace Notification { // Max active notification number -constexpr uint32_t MAX_ACTIVE_NUM = 1024 * 1024; +constexpr uint32_t MAX_ACTIVE_NUM = 1000; +constexpr uint32_t MAX_ACTIVE_NUM_PERAPP = 100; +constexpr uint32_t MAX_ACTIVE_NUM_PERSECOND = 10; constexpr uint32_t MAX_SLOT_NUM = 5; constexpr uint32_t MAX_SLOT_GROUP_NUM = 4; -constexpr int32_t ANS_UID = 1000; -constexpr int32_t ANS_GID = 1000; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_CONST_DEFINE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_CONST_DEFINE_H diff --git a/innerkits/base/include/ans_inner_errors.h b/frameworks/ans/core/common/include/ans_inner_errors.h similarity index 89% rename from innerkits/base/include/ans_inner_errors.h rename to frameworks/ans/core/common/include/ans_inner_errors.h index 1a43e7103c36f37b604c861871cf0526c9a64635..1c59b864ad8e9365b5bf731ae54026e73b34274a 100644 --- a/innerkits/base/include/ans_inner_errors.h +++ b/frameworks/ans/core/common/include/ans_inner_errors.h @@ -47,6 +47,7 @@ enum ErrorCode : uint32_t { ERR_ANS_INVALID_PARAM, ERR_ANS_INVALID_UID, ERR_ANS_INVALID_PID, + ERR_ANS_INVALID_BUNDLE, ERR_ANS_NOT_ALLOWED, ERR_ANS_PARCELABLE_FAILED, ERR_ANS_TRANSACT_FAILED, @@ -56,21 +57,17 @@ enum ErrorCode : uint32_t { ERR_ANS_NON_SYSTEM_APP, ERR_ANS_NOTIFICATION_NOT_EXISTS, ERR_ANS_NOTIFICATION_IS_UNREMOVABLE, + ERR_ANS_OVER_MAX_ACITVE_PERSECOND, - ERR_ANS_PREFERENCES_FILE_IS_NULL, - ERR_ANS_PREFERENCES_FILE_DOES_NOT_OPEN, - ERR_ANS_PREFERENCES_FILE_EXCEPTION, + ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED, ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST, ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST, - ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ID_INVALID, ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST, - ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_EXCEED_MAX_NUM, ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST, - ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_HAS_EXISTED, ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID, ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM, }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_INNER_ERRORS_H \ No newline at end of file +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_INNER_ERRORS_H diff --git a/innerkits/base/include/ans_log_wrapper.h b/frameworks/ans/core/common/include/ans_log_wrapper.h similarity index 100% rename from innerkits/base/include/ans_log_wrapper.h rename to frameworks/ans/core/common/include/ans_log_wrapper.h diff --git a/innerkits/base/src/ans_log_wrapper.cpp b/frameworks/ans/core/common/src/ans_log_wrapper.cpp similarity index 100% rename from innerkits/base/src/ans_log_wrapper.cpp rename to frameworks/ans/core/common/src/ans_log_wrapper.cpp diff --git a/innerkits/core/include/ans_manager_death_recipient.h b/frameworks/ans/core/include/ans_manager_death_recipient.h similarity index 77% rename from innerkits/core/include/ans_manager_death_recipient.h rename to frameworks/ans/core/include/ans_manager_death_recipient.h index acf6b93728fb1b0aca7312b788d0e860b291e0f8..f46e8df6f0fa6d0ba4fd657f14ee094bc0f63d54 100644 --- a/innerkits/core/include/ans_manager_death_recipient.h +++ b/frameworks/ans/core/include/ans_manager_death_recipient.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_DEATH_RECIPIENT_H -#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_DEATH_RECIPIENT_H +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_DEATH_RECIPIENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_DEATH_RECIPIENT_H #include "iremote_object.h" @@ -31,4 +31,4 @@ public: } // namespace Notification } // namespace OHOS -#endif +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_DEATH_RECIPIENT_H diff --git a/innerkits/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h similarity index 93% rename from innerkits/core/include/ans_manager_interface.h rename to frameworks/ans/core/include/ans_manager_interface.h index ad843cdd10947ff271f253196bc173bf849a0133..136bf8cd1bf2aaa5f5057d6c1ced1f05f647596b 100644 --- a/innerkits/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_INTERFACE_H -#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_INTERFACE_H +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_INTERFACE_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_INTERFACE_H #include #include @@ -43,10 +43,9 @@ public: virtual ErrCode Cancel(int notificationId, const std::string &label) = 0; virtual ErrCode CancelAll() = 0; virtual ErrCode AddSlots(const std::vector> &slots) = 0; - virtual ErrCode RemoveSlots(const std::vector &slotIds) = 0; virtual ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) = 0; + virtual ErrCode RemoveAllSlots() = 0; virtual ErrCode AddSlotGroups(std::vector> groups) = 0; - virtual ErrCode GetSlot(const std::string &slotId, sptr &slot) = 0; virtual ErrCode GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) = 0; virtual ErrCode GetSlots(std::vector> &slots) = 0; virtual ErrCode GetSlotGroup(const std::string &groupId, sptr &group) = 0; @@ -90,6 +89,7 @@ public: virtual ErrCode IsAllowedNotify(bool &allowed) = 0; virtual ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) = 0; + virtual ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) = 0; protected: enum TransactId : uint32_t { PUBLISH_NOTIFICATION = FIRST_CALL_TRANSACTION, @@ -97,10 +97,9 @@ protected: CANCEL_NOTIFICATION, CANCEL_ALL_NOTIFICATIONS, ADD_SLOTS, - REMOVE_SLOTS, REMOVE_SLOT_BY_TYPE, + REMOVE_ALL_SLOTS, ADD_SLOT_GROUPS, - GET_SLOT, GET_SLOT_BY_TYPE, GET_SLOTS, GET_SLOT_GROUP, @@ -138,9 +137,10 @@ protected: GET_CURRENT_APP_SORTING, IS_ALLOWED_NOTIFY, IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, + SHELL_DUMP, }; }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_INTERFACE_H +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_INTERFACE_H diff --git a/innerkits/core/include/ans_manager_proxy.h b/frameworks/ans/core/include/ans_manager_proxy.h similarity index 92% rename from innerkits/core/include/ans_manager_proxy.h rename to frameworks/ans/core/include/ans_manager_proxy.h index c9e9e8e173ba2bba09307b8e63fda425f0c98b0c..d3221d4a0e4d35e9dbd3161269daf7dbcfb6c1c4 100644 --- a/innerkits/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_PROXY_H -#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_PROXY_H +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_PROXY_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_PROXY_H #include "ans_manager_interface.h" #include "iremote_proxy.h" @@ -33,10 +33,9 @@ public: ErrCode Cancel(int notificationId, const std::string &label) override; ErrCode CancelAll() override; ErrCode AddSlots(const std::vector> &slots) override; - ErrCode RemoveSlots(const std::vector &slotIds) override; ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) override; + ErrCode RemoveAllSlots() override; ErrCode AddSlotGroups(std::vector> groups) override; - ErrCode GetSlot(const std::string &slotId, sptr &slot) 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; @@ -79,6 +78,8 @@ public: ErrCode IsAllowedNotify(bool &allowed) override; ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) override; + ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; + private: ErrCode InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); @@ -92,4 +93,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_PROXY_H +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_PROXY_H diff --git a/innerkits/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h similarity index 94% rename from innerkits/core/include/ans_manager_stub.h rename to frameworks/ans/core/include/ans_manager_stub.h index ec967f40f278c86d71f9329eaccc0ebb2047b0b5..bc9f3b3569b3b53a5870fac3ef9f7d82e4ea249a 100644 --- a/innerkits/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_STUB_H -#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_STUB_H +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_STUB_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_STUB_H #include #include @@ -39,10 +39,9 @@ public: virtual ErrCode Cancel(int notificationId, const std::string &label) override; virtual ErrCode CancelAll() override; virtual ErrCode AddSlots(const std::vector> &slots) override; - virtual ErrCode RemoveSlots(const std::vector &slotIds) override; virtual ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) override; + virtual ErrCode RemoveAllSlots() override; virtual ErrCode AddSlotGroups(std::vector> groups) override; - virtual ErrCode GetSlot(const std::string &slotId, sptr &slot) override; virtual ErrCode GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) override; virtual ErrCode GetSlots(std::vector> &slots) override; virtual ErrCode GetSlotGroup(const std::string &groupId, sptr &group) override; @@ -87,6 +86,8 @@ public: virtual ErrCode IsAllowedNotify(bool &allowed) override; virtual ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) override; + virtual ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; + private: static const std::map> interfaces_; @@ -95,10 +96,9 @@ private: ErrCode HandleCancel(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelAll(MessageParcel &data, MessageParcel &reply); ErrCode HandleAddSlots(MessageParcel &data, MessageParcel &reply); - ErrCode HandleRemoveSlots(MessageParcel &data, MessageParcel &reply); ErrCode HandleRemoveSlotByType(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveAllSlots(MessageParcel &data, MessageParcel &reply); ErrCode HandleAddSlotGroups(MessageParcel &data, MessageParcel &reply); - ErrCode HandleGetSlot(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetSlots(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetSlotByType(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetSlotGroup(MessageParcel &data, MessageParcel &reply); @@ -137,6 +137,8 @@ private: ErrCode HandleIsAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply); + ErrCode HandleShellDump(MessageParcel &data, MessageParcel &reply); + template bool WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result); @@ -146,4 +148,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_STUB_H +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_MANAGER_STUB_H diff --git a/innerkits/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h similarity index 98% rename from innerkits/core/include/ans_notification.h rename to frameworks/ans/core/include/ans_notification.h index c75fbda1cb91172a9e00fb73e5482d272e8c0a33..bea2c2c7f478230e089068ee195cbab891603bf7 100644 --- a/innerkits/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_NOTIFICATION_H -#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_NOTIFICATION_H +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_NOTIFICATION_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_NOTIFICATION_H #include @@ -505,6 +505,11 @@ public: */ void ResetAnsManagerProxy(); + /** + * Shell dump. + */ + ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo); + private: /** * Get Ans Manager proxy. @@ -529,4 +534,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_NOTIFICATION_H \ No newline at end of file +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_NOTIFICATION_H \ No newline at end of file diff --git a/innerkits/core/include/ans_subscriber_interface.h b/frameworks/ans/core/include/ans_subscriber_interface.h similarity index 88% rename from innerkits/core/include/ans_subscriber_interface.h rename to frameworks/ans/core/include/ans_subscriber_interface.h index 9270ab9ffbce612ad6ee01ee4b365cf34ca2df70..68808a23b13725c5b8927efff653225f2abbe2fb 100644 --- a/innerkits/core/include/ans_subscriber_interface.h +++ b/frameworks/ans/core/include/ans_subscriber_interface.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_INTERFACE_H -#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_INTERFACE_H +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_SUBSCRIBER_INTERFACE_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_SUBSCRIBER_INTERFACE_H #include "iremote_broker.h" @@ -60,4 +60,4 @@ protected: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_INTERFACE_H +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_SUBSCRIBER_INTERFACE_H diff --git a/innerkits/core/include/ans_subscriber_proxy.h b/frameworks/ans/core/include/ans_subscriber_proxy.h similarity index 87% rename from innerkits/core/include/ans_subscriber_proxy.h rename to frameworks/ans/core/include/ans_subscriber_proxy.h index 514f4c4731c19730ba71517aaa9fc48f27941d97..b4561feefd359609b002795165ba423e837f0190 100644 --- a/innerkits/core/include/ans_subscriber_proxy.h +++ b/frameworks/ans/core/include/ans_subscriber_proxy.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_PROXY_H -#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_PROXY_H +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_SUBSCRIBER_PROXY_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_SUBSCRIBER_PROXY_H #include "ans_subscriber_interface.h" #include "iremote_proxy.h" @@ -47,4 +47,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_PROXY_H +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_SUBSCRIBER_PROXY_H diff --git a/innerkits/core/include/ans_subscriber_stub.h b/frameworks/ans/core/include/ans_subscriber_stub.h similarity index 90% rename from innerkits/core/include/ans_subscriber_stub.h rename to frameworks/ans/core/include/ans_subscriber_stub.h index 8690140ff3351f226b8baca88b9b3deb30b7f5f0..415074d7ce149cc2be535624b00969b60fb8d55e 100644 --- a/innerkits/core/include/ans_subscriber_stub.h +++ b/frameworks/ans/core/include/ans_subscriber_stub.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_STUB_H -#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_STUB_H +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_SUBSCRIBER_STUB_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_SUBSCRIBER_STUB_H #include "ans_subscriber_interface.h" #include "iremote_stub.h" @@ -57,4 +57,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_STUB_H +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_SUBSCRIBER_STUB_H diff --git a/innerkits/core/src/ans_manager_death_recipient.cpp b/frameworks/ans/core/src/ans_manager_death_recipient.cpp similarity index 100% rename from innerkits/core/src/ans_manager_death_recipient.cpp rename to frameworks/ans/core/src/ans_manager_death_recipient.cpp diff --git a/innerkits/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp similarity index 97% rename from innerkits/core/src/ans_manager_proxy.cpp rename to frameworks/ans/core/src/ans_manager_proxy.cpp index 6a479f34b5bea17f78594d53d33aea06ec1e4343..c113a25898d9ec5b9c9bd40c2f16a65ac2861b11 100644 --- a/innerkits/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -207,67 +207,57 @@ ErrCode AnsManagerProxy::AddSlots(const std::vector> &slo return result; } -ErrCode AnsManagerProxy::RemoveSlots(const std::vector &slotIds) +ErrCode AnsManagerProxy::RemoveSlotByType(const NotificationConstant::SlotType slotType) { - if (slotIds.empty()) { - ANS_LOGW("[RemoveSlots] fail: slotIds is empty."); - return ERR_ANS_INVALID_PARAM; - } - MessageParcel data; if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANS_LOGW("[RemoveSlots] fail: write interface token failed."); + ANS_LOGW("[RemoveSlotByType] fail: write interface token failed."); return ERR_ANS_PARCELABLE_FAILED; } - if (!data.WriteStringVector(slotIds)) { - ANS_LOGW("[RemoveSlots] fail:: write slotIds failed."); + if (!data.WriteInt32(slotType)) { + ANS_LOGW("[RemoveSlotByType] fail:: write slotIds failed."); return ERR_ANS_PARCELABLE_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(REMOVE_SLOTS, option, data, reply); + ErrCode result = InnerTransact(REMOVE_SLOT_BY_TYPE, option, data, reply); if (result != ERR_OK) { - ANS_LOGW("[RemoveSlots] fail: transact ErrCode=%{public}d", result); + ANS_LOGW("[RemoveSlotByType] fail: transact ErrCode=%{public}d", result); return ERR_ANS_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - ANS_LOGW("[RemoveSlots] fail: read result failed."); + ANS_LOGW("[RemoveSlotByType] fail: read result failed."); return ERR_ANS_PARCELABLE_FAILED; } return result; } -ErrCode AnsManagerProxy::RemoveSlotByType(const NotificationConstant::SlotType slotType) +ErrCode AnsManagerProxy::RemoveAllSlots() { MessageParcel data; if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANS_LOGW("[RemoveSlotByType] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - if (!data.WriteInt32(slotType)) { - ANS_LOGW("[RemoveSlotByType] fail:: write slotIds failed."); + ANS_LOGW("[RemoveAllSlots] fail: write interface token failed."); return ERR_ANS_PARCELABLE_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(REMOVE_SLOT_BY_TYPE, option, data, reply); + ErrCode result = InnerTransact(REMOVE_ALL_SLOTS, option, data, reply); if (result != ERR_OK) { - ANS_LOGW("[RemoveSlotByType] fail: transact ErrCode=%{public}d", result); + ANS_LOGW("[RemoveAllSlots] fail: transact ErrCode=%{public}d", result); return ERR_ANS_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - ANS_LOGW("[RemoveSlotByType] fail: read result failed."); + ANS_LOGW("[RemoveAllSlots] fail: read result failed."); return ERR_ANS_PARCELABLE_FAILED; } - return result; + return result; } ErrCode AnsManagerProxy::AddSlotGroups(std::vector> groups) @@ -310,46 +300,6 @@ ErrCode AnsManagerProxy::AddSlotGroups(std::vector> return result; } -ErrCode AnsManagerProxy::GetSlot(const std::string &slotId, sptr &slot) -{ - if (slotId.empty()) { - ANS_LOGW("[GetSlot] fail: slotId is null."); - return ERR_ANS_INVALID_PARAM; - } - - MessageParcel data; - if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANS_LOGW("[GetSlot] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - if (!data.WriteString(slotId)) { - ANS_LOGW("[GetSlot] fail:: write slotId failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(GET_SLOT, option, data, reply); - if (result != ERR_OK) { - ANS_LOGW("[GetSlot] fail: transact ErrCode=%{public}d", result); - return ERR_ANS_TRANSACT_FAILED; - } - - if (!reply.ReadInt32(result)) { - ANS_LOGW("[GetSlot] fail: read result failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - slot = reply.ReadParcelable(); - if (slot == nullptr) { - ANS_LOGW("[GetSlot] fail: read slot failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - - return result; -} - ErrCode AnsManagerProxy::GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) { MessageParcel data; @@ -547,7 +497,12 @@ ErrCode AnsManagerProxy::GetActiveNotificationNums(int &num) return ERR_ANS_TRANSACT_FAILED; } - if (!data.ReadInt32(num)) { + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetActiveNotificationNums] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadInt32(num)) { ANS_LOGW("[GetActiveNotificationNums] fail: read notification num failed."); return ERR_ANS_PARCELABLE_FAILED; } @@ -1607,6 +1562,40 @@ ErrCode AnsManagerProxy::IsSpecialBundleAllowedNotify(const std::string &bundle, return result; } +ErrCode AnsManagerProxy::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[ShellDump] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(dumpOption)) { + ANS_LOGW("[ShellDump] fail: write option failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SHELL_DUMP, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[ShellDump] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[ShellDump] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadStringVector(&dumpInfo)) { + ANS_LOGW("[ShellDump] fail: read dumpInfo failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + ErrCode AnsManagerProxy::InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply) { auto remote = Remote(); diff --git a/innerkits/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp similarity index 96% rename from innerkits/core/src/ans_manager_stub.cpp rename to frameworks/ans/core/src/ans_manager_stub.cpp index 9774f7de3d39c7ff3cfdd5cdd0ea4f2ad70fd284..484dd0a499a2a50293032590f02f95fcfc0d5130 100644 --- a/innerkits/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -42,18 +42,15 @@ const std::map slotIds; - if (!data.ReadStringVector(&slotIds)) { - ANS_LOGW("[HandleRemoveSlots] fail: read slotIds failed"); - return ERR_ANS_PARCELABLE_FAILED; - } + NotificationConstant::SlotType slotType = static_cast(data.ReadInt32()); - ErrCode result = RemoveSlots(slotIds); + ErrCode result = RemoveSlotByType(slotType); if (!reply.WriteInt32(result)) { - ANS_LOGW("[HandleRemoveSlots] fail: write result failed, ErrCode=%{public}d", result); + ANS_LOGW("[HandleRemoveSlotByType] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; } return ERR_OK; } -ErrCode AnsManagerStub::HandleRemoveSlotByType(MessageParcel &data, MessageParcel &reply) +ErrCode AnsManagerStub::HandleRemoveAllSlots(MessageParcel &data, MessageParcel &reply) { - NotificationConstant::SlotType slotType = static_cast(data.ReadInt32()); - - ErrCode result = RemoveSlotByType(slotType); + ErrCode result = RemoveAllSlots(); if (!reply.WriteInt32(result)) { - ANS_LOGW("[HandleRemoveSlotByType] fail: write result failed, ErrCode=%{public}d", result); + ANS_LOGW("[HandleRemoveAllSlots] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; } return ERR_OK; @@ -338,29 +338,6 @@ ErrCode AnsManagerStub::HandleAddSlotGroups(MessageParcel &data, MessageParcel & return ERR_OK; } -ErrCode AnsManagerStub::HandleGetSlot(MessageParcel &data, MessageParcel &reply) -{ - std::string slotId; - if (!data.ReadString(slotId)) { - ANS_LOGW("[HandleGetSlot] fail: read slotId failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - - sptr slot; - ErrCode result = GetSlot(slotId, slot); - - if (!reply.WriteInt32(result)) { - ANS_LOGW("[HandleGetSlot] fail: write result failed, ErrCode=%{public}d", result); - return ERR_ANS_PARCELABLE_FAILED; - } - - if (!reply.WriteParcelable(slot)) { - ANS_LOGW("[HandleGetSlot] fail: write slot failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - return ERR_OK; -} - ErrCode AnsManagerStub::HandleGetSlots(MessageParcel &data, MessageParcel &reply) { std::vector> slots; @@ -496,7 +473,7 @@ ErrCode AnsManagerStub::HandleGetSpecialActiveNotifications(MessageParcel &data, } std::vector> notifications; - ErrCode result = GetAllActiveNotifications(notifications); + ErrCode result = GetSpecialActiveNotifications(key, notifications); if (!WriteParcelableVector(notifications, reply, result)) { ANS_LOGW("[HandleGetSpecialActiveNotifications] fail: write notifications failed"); @@ -1047,6 +1024,29 @@ ErrCode AnsManagerStub::HandleIsSpecialBundleAllowedNotify(MessageParcel &data, return ERR_OK; } +ErrCode AnsManagerStub::HandleShellDump(MessageParcel &data, MessageParcel &reply) +{ + std::string dumpOption; + if (!data.ReadString(dumpOption)) { + ANS_LOGW("[HandleShellDump] fail: read dumpOption failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::vector notificationsInfo; + ErrCode result = ShellDump(dumpOption, notificationsInfo); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetRecentNotificationsInfo] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteStringVector(notificationsInfo)) { + ANS_LOGW("[HandleGetRecentNotificationsInfo] fail: write notificationsInfo failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + template bool AnsManagerStub::WriteParcelableVector( const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result) @@ -1122,27 +1122,21 @@ ErrCode AnsManagerStub::AddSlots(const std::vector> &slot return ERR_OK; } -ErrCode AnsManagerStub::RemoveSlots(const std::vector &slotIds) -{ - ANS_LOGW("AnsManagerStub::RemoveSlots called!"); - return ERR_OK; -} - ErrCode AnsManagerStub::RemoveSlotByType(const NotificationConstant::SlotType slotType) { ANS_LOGW("AnsManagerStub::RemoveSlotByType called!"); return ERR_OK; } -ErrCode AnsManagerStub::AddSlotGroups(std::vector> groups) +ErrCode AnsManagerStub::RemoveAllSlots() { - ANS_LOGW("AnsManagerStub::AddSlotGroups called!"); + ANS_LOGW("AnsManagerStub::RemoveAllSlots called!"); return ERR_OK; } -ErrCode AnsManagerStub::GetSlot(const std::string &slotId, sptr &slot) +ErrCode AnsManagerStub::AddSlotGroups(std::vector> groups) { - ANS_LOGW("AnsManagerStub::GetSlot called!"); + ANS_LOGW("AnsManagerStub::AddSlotGroups called!"); return ERR_OK; } @@ -1372,5 +1366,11 @@ ErrCode AnsManagerStub::IsSpecialBundleAllowedNotify(const std::string &bundle, return ERR_OK; } +ErrCode AnsManagerStub::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) +{ + ANS_LOGW("AnsManagerStub::ShellDump called!"); + return ERR_OK; +} + } // namespace Notification } // namespace OHOS diff --git a/innerkits/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp similarity index 98% rename from innerkits/core/src/ans_notification.cpp rename to frameworks/ans/core/src/ans_notification.cpp index fc521dbf1fbd340252d4b019be2aa6b794e66bb1..57abd571899ee7cf765af6e38320a625e0f01304 100644 --- a/innerkits/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -16,9 +16,9 @@ #include "ans_notification.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "iservice_registry.h" #include "notification_request.h" #include "notification_sorting.h" -#include "iservice_registry.h" #include "system_ability_definition.h" namespace OHOS { @@ -584,6 +584,15 @@ void AnsNotification::ResetAnsManagerProxy() ansManagerProxy_ = nullptr; } +ErrCode AnsNotification::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->ShellDump(dumpOption, dumpInfo); +} + bool AnsNotification::GetAnsManagerProxy() { if (!ansManagerProxy_) { diff --git a/innerkits/core/src/ans_subscriber_proxy.cpp b/frameworks/ans/core/src/ans_subscriber_proxy.cpp similarity index 100% rename from innerkits/core/src/ans_subscriber_proxy.cpp rename to frameworks/ans/core/src/ans_subscriber_proxy.cpp diff --git a/innerkits/core/src/ans_subscriber_stub.cpp b/frameworks/ans/core/src/ans_subscriber_stub.cpp similarity index 100% rename from innerkits/core/src/ans_subscriber_stub.cpp rename to frameworks/ans/core/src/ans_subscriber_stub.cpp diff --git a/kits/native/BUILD.gn b/frameworks/ans/native/BUILD.gn similarity index 78% rename from kits/native/BUILD.gn rename to frameworks/ans/native/BUILD.gn index 5a8c48e6df9f10ba3c01cc35e13ae8d629efdb52..cc0cb3825ef69dc45d6ac51c841823355adfd0b2 100644 --- a/kits/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -15,33 +15,28 @@ import("//base/notification/ans_standard/notification.gni") import("//build/ohos.gni") group("native_targets") { - deps = [ ":ans_kits" ] + deps = [ ":ans_innerkits" ] } -config("ans_kits_config") { - include_dirs = [ "${kits_path}/native/include" ] - configs = [ "${innerkits_path}:public_ans_innerkits_config" ] -} - -config("ans_kit_public_config") { +config("ans_innerkits_public_config") { visibility = [ ":*" ] include_dirs = [ - "${kits_path}/native/include", - "${innerkits_path}/core/include", - "${innerkits_path}/base/include", + "${interfaces_path}/ans/native/include", + "${frameworks_path}/ans/core/common/include", + "${frameworks_path}/ans/core/include", ] + configs = [ "${frameworks_path}/wantagent:wantagent_innerkits_public_config" ] } -ohos_shared_library("ans_kits") { +ohos_shared_library("ans_innerkits") { include_dirs = [ - "${kits_path}/native/include", + "${interfaces_path}/ans/native/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", "//utils/system/safwk/native/include", ] sources = [ - "${innerkits_path}/base/src/ans_log_wrapper.cpp", "src/message_user.cpp", "src/notification.cpp", "src/notification_action_button.cpp", @@ -68,14 +63,14 @@ ohos_shared_library("ans_kits") { configs = [ "//utils/native/base:utils_config", - "${innerkits_path}:public_ans_innerkits_config", + "${core_path}:public_ans_core_config", ] - public_configs = [ ":ans_kit_public_config" ] + public_configs = [ ":ans_innerkits_public_config" ] deps = [ - "${innerkits_path}:ans_innerkits", - "${kits_path}/native/wantagent:wantagent_kits", + "${frameworks_path}/ans/core:ans_core", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//utils/native/base:utils", diff --git a/kits/native/src/message_user.cpp b/frameworks/ans/native/src/message_user.cpp similarity index 100% rename from kits/native/src/message_user.cpp rename to frameworks/ans/native/src/message_user.cpp diff --git a/kits/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp similarity index 75% rename from kits/native/src/notification.cpp rename to frameworks/ans/native/src/notification.cpp index c333f0789ccfc8e3f22c1ec3e0d7fba5bcd958ca..31b3763654c7228e01fd12dfbf8d5614eb4130da 100644 --- a/kits/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -93,7 +93,7 @@ int32_t Notification::GetLedLightColor() const return ledLightColor_; } -int32_t Notification::GetLockscreenVisibleness() const +NotificationConstant::VisiblenessType Notification::GetLockscreenVisibleness() const { return lockscreenVisibleness_; } @@ -131,17 +131,28 @@ int64_t Notification::GetPostTime() const Uri Notification::GetSound() const { - return *sound_; + if (enableSound_ && sound_ != nullptr) { + return *sound_; + } + return Uri(""); } -int32_t Notification::GetUid() const +uid_t Notification::GetUid() const { if (request_ == nullptr) { - return -1; + return 0; } return request_->GetCreatorUid(); } +uid_t Notification::GetPid() const +{ + if (request_ == nullptr) { + return 0; + } + return request_->GetCreatorPid(); +} + std::vector Notification::GetVibrationStyle() const { return vibrationStyle_; @@ -155,8 +166,31 @@ bool Notification::IsGroup() const return !(request_->GetGroupValue() == ""); } +bool Notification::IsFloatingIcon() const +{ + if (request_ == nullptr) { + return false; + } + return request_->IsFloatingIcon(); +} + bool Notification::Marshalling(Parcel &parcel) const { + if(!parcel.WriteBool(enableLight_)){ + ANS_LOGE("Can't write enableLight_"); + return false; + } + + if(!parcel.WriteBool(enableSound_)) { + ANS_LOGE("Can't write enableSound_"); + return false; + } + + if(!parcel.WriteBool(enableViration_)) { + ANS_LOGE("Can't write enableViration_"); + return false; + } + if (!parcel.WriteString(key_)) { ANS_LOGE("Can't wirte key"); return false; @@ -166,7 +200,7 @@ bool Notification::Marshalling(Parcel &parcel) const return false; } - if (!parcel.WriteInt32(lockscreenVisibleness_)) { + if (!parcel.WriteInt32(static_cast(lockscreenVisibleness_))) { ANS_LOGE("Can't write visbleness"); return false; } @@ -181,9 +215,11 @@ bool Notification::Marshalling(Parcel &parcel) const return false; } - if (!parcel.WriteString(sound_->ToString())) { - ANS_LOGE("Can't write sound"); - return false; + if (enableSound_ && sound_ != nullptr) { + if (!parcel.WriteString(sound_->ToString())) { + ANS_LOGE("Can't write sound"); + return false; + } } if (!parcel.WriteInt64Vector(vibrationStyle_)) { @@ -196,6 +232,15 @@ bool Notification::Marshalling(Parcel &parcel) const bool Notification::ReadFromParcel(Parcel &parcel) { + // Read enableLight_ + enableLight_ = parcel.ReadBool(); + + // Read enableSound_ + enableSound_ = parcel.ReadBool(); + + // Read enableViration_ + enableViration_ = parcel.ReadBool(); + // Read key_ key_ = parcel.ReadString(); @@ -203,7 +248,7 @@ bool Notification::ReadFromParcel(Parcel &parcel) ledLightColor_ = parcel.ReadInt32(); // Read lockscreenVisibleness_ - lockscreenVisibleness_ = parcel.ReadInt32(); + lockscreenVisibleness_ = static_cast(parcel.ReadInt32()); // Read request_ request_ = parcel.ReadStrongParcelable(); @@ -212,7 +257,9 @@ bool Notification::ReadFromParcel(Parcel &parcel) postTime_ = parcel.ReadInt64(); // Read sound_ - sound_ = std::make_shared(parcel.ReadString()); + if (enableSound_) { + sound_ = std::make_shared(parcel.ReadString()); + } // Read vibrationStyle_ parcel.ReadInt64Vector(&vibrationStyle_); @@ -231,12 +278,27 @@ Notification *Notification::Unmarshalling(Parcel &parcel) return n; } +void Notification::SetEnableSound(const bool& enable) +{ + enableSound_ = enable; +} + +void Notification::SetEnableLight(const bool& enable) +{ + enableLight_ = enable; +} + +void Notification::SetEnableViration(const bool& enable) +{ + enableViration_ = enable; +} + void Notification::SetLedLightColor(const int32_t &color) { ledLightColor_ = color; } -void Notification::SetLockScreenVisbleness(const int32_t &visbleness) +void Notification::SetLockScreenVisbleness(const NotificationConstant::VisiblenessType &visbleness) { lockscreenVisibleness_ = visbleness; } @@ -269,7 +331,7 @@ 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(lockscreenVisibleness_) + ",request = "; + ", lockscreenVisbleness = " + std::to_string(static_cast(lockscreenVisibleness_)) + ",request = "; if (request_ == nullptr) { dump += "nullptr"; } else { diff --git a/kits/native/src/notification_action_button.cpp b/frameworks/ans/native/src/notification_action_button.cpp similarity index 100% rename from kits/native/src/notification_action_button.cpp rename to frameworks/ans/native/src/notification_action_button.cpp index fcc2f4e2204c2ebffe2bbcb123c0c5dc6ee2eadc..80f7e40c994ba52744dc5b7489437385fd39af2b 100644 --- a/kits/native/src/notification_action_button.cpp +++ b/frameworks/ans/native/src/notification_action_button.cpp @@ -59,29 +59,29 @@ NotificationActionButton::NotificationActionButton(const std::shared_ptr NotificationActionButton::GetIcon() const { - extras_->PutAll(pacMap); + return icon_; } -const std::shared_ptr NotificationActionButton::GetAdditionalData() const +std::string NotificationActionButton::GetTitle() const { - return extras_; + return title_; } -const std::shared_ptr NotificationActionButton::GetIcon() const +const std::shared_ptr NotificationActionButton::GetWantAgent() const { - return icon_; + return wantAgent_; } -const std::shared_ptr NotificationActionButton::GetWantAgent() const +void NotificationActionButton::AddAdditionalData(AppExecFwk::PacMap &pacMap) { - return wantAgent_; + extras_->PutAll(pacMap); } -std::vector> NotificationActionButton::GetMimeTypeOnlyUserInputs() const +const std::shared_ptr NotificationActionButton::GetAdditionalData() const { - return {}; + return extras_; } void NotificationActionButton::SetSemanticActionButton(NotificationConstant::SemanticActionButton semanticActionButton) @@ -94,11 +94,6 @@ NotificationConstant::SemanticActionButton NotificationActionButton::GetSemantic return semanticActionButton_; } -std::string NotificationActionButton::GetTitle() const -{ - return title_; -} - void NotificationActionButton::AddNotificationUserInput(const std::shared_ptr &userInput) { if (!userInput) { @@ -114,9 +109,9 @@ std::vector> NotificationActionButton::Ge return userInputs_; } -bool NotificationActionButton::IsAutoCreatedReplies() const +std::vector> NotificationActionButton::GetMimeTypeOnlyUserInputs() const { - return autoCreatedReplies_; + return {}; } void NotificationActionButton::SetAutoCreatedReplies(bool autoCreatedReplies) @@ -124,9 +119,9 @@ void NotificationActionButton::SetAutoCreatedReplies(bool autoCreatedReplies) autoCreatedReplies_ = autoCreatedReplies; } -bool NotificationActionButton::IsContextDependent() const +bool NotificationActionButton::IsAutoCreatedReplies() const { - return isContextual_; + return autoCreatedReplies_; } void NotificationActionButton::SetContextDependent(bool isContextual) @@ -134,6 +129,11 @@ void NotificationActionButton::SetContextDependent(bool isContextual) isContextual_ = isContextual; } +bool NotificationActionButton::IsContextDependent() const +{ + return isContextual_; +} + std::string NotificationActionButton::Dump() { return "NotificationActionButton[ title = " + title_ + diff --git a/kits/native/src/notification_basic_content.cpp b/frameworks/ans/native/src/notification_basic_content.cpp similarity index 100% rename from kits/native/src/notification_basic_content.cpp rename to frameworks/ans/native/src/notification_basic_content.cpp diff --git a/kits/native/src/notification_constant.cpp b/frameworks/ans/native/src/notification_constant.cpp similarity index 100% rename from kits/native/src/notification_constant.cpp rename to frameworks/ans/native/src/notification_constant.cpp diff --git a/kits/native/src/notification_content.cpp b/frameworks/ans/native/src/notification_content.cpp similarity index 100% rename from kits/native/src/notification_content.cpp rename to frameworks/ans/native/src/notification_content.cpp diff --git a/kits/native/src/notification_conversational_content.cpp b/frameworks/ans/native/src/notification_conversational_content.cpp similarity index 100% rename from kits/native/src/notification_conversational_content.cpp rename to frameworks/ans/native/src/notification_conversational_content.cpp diff --git a/kits/native/src/notification_conversational_message.cpp b/frameworks/ans/native/src/notification_conversational_message.cpp similarity index 100% rename from kits/native/src/notification_conversational_message.cpp rename to frameworks/ans/native/src/notification_conversational_message.cpp diff --git a/kits/native/src/notification_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp similarity index 100% rename from kits/native/src/notification_helper.cpp rename to frameworks/ans/native/src/notification_helper.cpp diff --git a/kits/native/src/notification_long_text_content.cpp b/frameworks/ans/native/src/notification_long_text_content.cpp similarity index 100% rename from kits/native/src/notification_long_text_content.cpp rename to frameworks/ans/native/src/notification_long_text_content.cpp diff --git a/kits/native/src/notification_media_content.cpp b/frameworks/ans/native/src/notification_media_content.cpp similarity index 100% rename from kits/native/src/notification_media_content.cpp rename to frameworks/ans/native/src/notification_media_content.cpp diff --git a/kits/native/src/notification_multiline_content.cpp b/frameworks/ans/native/src/notification_multiline_content.cpp similarity index 100% rename from kits/native/src/notification_multiline_content.cpp rename to frameworks/ans/native/src/notification_multiline_content.cpp diff --git a/kits/native/src/notification_normal_content.cpp b/frameworks/ans/native/src/notification_normal_content.cpp similarity index 100% rename from kits/native/src/notification_normal_content.cpp rename to frameworks/ans/native/src/notification_normal_content.cpp diff --git a/kits/native/src/notification_picture_content.cpp b/frameworks/ans/native/src/notification_picture_content.cpp similarity index 100% rename from kits/native/src/notification_picture_content.cpp rename to frameworks/ans/native/src/notification_picture_content.cpp diff --git a/kits/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp similarity index 100% rename from kits/native/src/notification_request.cpp rename to frameworks/ans/native/src/notification_request.cpp diff --git a/kits/native/src/notification_slot.cpp b/frameworks/ans/native/src/notification_slot.cpp similarity index 99% rename from kits/native/src/notification_slot.cpp rename to frameworks/ans/native/src/notification_slot.cpp index 7661db84e3673f239b56c830c45bf57691ac70dd..05223bd1c1a6d076013a29063db7bc1a9a9d232f 100644 --- a/kits/native/src/notification_slot.cpp +++ b/frameworks/ans/native/src/notification_slot.cpp @@ -108,13 +108,13 @@ void NotificationSlot::SetType(NotificationConstant::SlotType type) case NotificationConstant::SlotType::CONTENT_INFORMATION: id_ = "CONTENT_INFORMATION"; SetName("CONTENT_INFORMATION"); - SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PRIVATE); + SetLockscreenVisibleness(NotificationConstant::VisiblenessType::SECRET); SetEnableVibration(false); break; case NotificationConstant::SlotType::OTHER: id_ = "OTHER"; SetName("OTHER"); - SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PRIVATE); + SetLockscreenVisibleness(NotificationConstant::VisiblenessType::SECRET); SetEnableVibration(false); break; default: diff --git a/kits/native/src/notification_slot_group.cpp b/frameworks/ans/native/src/notification_slot_group.cpp similarity index 100% rename from kits/native/src/notification_slot_group.cpp rename to frameworks/ans/native/src/notification_slot_group.cpp diff --git a/kits/native/src/notification_sorting.cpp b/frameworks/ans/native/src/notification_sorting.cpp similarity index 100% rename from kits/native/src/notification_sorting.cpp rename to frameworks/ans/native/src/notification_sorting.cpp diff --git a/kits/native/src/notification_sorting_map.cpp b/frameworks/ans/native/src/notification_sorting_map.cpp similarity index 100% rename from kits/native/src/notification_sorting_map.cpp rename to frameworks/ans/native/src/notification_sorting_map.cpp diff --git a/kits/native/src/notification_subscribe_info.cpp b/frameworks/ans/native/src/notification_subscribe_info.cpp similarity index 100% rename from kits/native/src/notification_subscribe_info.cpp rename to frameworks/ans/native/src/notification_subscribe_info.cpp diff --git a/kits/native/src/notification_subscriber.cpp b/frameworks/ans/native/src/notification_subscriber.cpp similarity index 100% rename from kits/native/src/notification_subscriber.cpp rename to frameworks/ans/native/src/notification_subscriber.cpp diff --git a/kits/native/src/notification_user_input.cpp b/frameworks/ans/native/src/notification_user_input.cpp similarity index 100% rename from kits/native/src/notification_user_input.cpp rename to frameworks/ans/native/src/notification_user_input.cpp diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cc524695c7ce06474579878813859366ca909472 --- /dev/null +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -0,0 +1,127 @@ +# 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") + +module_output_path = "ans_standard/moduletest" + +config("public_ans_config") { + include_dirs = [ + "${core_path}/common/include", + "//utils/native/base/include", + "${services_path}/ans/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "${core_path}/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content/", + ] +} + +config("json_config") { + cflags_cc = [ "-fexceptions" ] +} + +ohos_moduletest("ans_fw_module_test") { + module_out_path = module_output_path + include_dirs = [ + "include", + "${core_path}/include", + "${interfaces_path}/ans/native/include", + "${frameworks_path}/ans/core/common/include", + "${frameworks_path}/ans/core/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/libs/libeventhandler/src", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/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", + "//base/notification/ans_standard/interfaces/innerkits/ans/native/test/moduletest/mock/include", + "//foundation/distributedschedule/samgr/services/samgr/native/include", + "//foundation/communication/ipc/interfaces/innerkits/libdbinder/include", + "//base/notification/ces_standard/cesfwk/interfaces/innerkits/native/include", + "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", + "//base/notification/ans_standard/interfaces/innerkits/wantagent/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", + ] + + sources = [ + "//base/notification/ans_standard/frameworks/ans/core/src/ans_manager_proxy.cpp", + "//base/notification/ans_standard/frameworks/ans/core/src/ans_manager_stub.cpp", + "//base/notification/ans_standard/frameworks/ans/core/src/ans_notification.cpp", + "//base/notification/ans_standard/frameworks/ans/core/src/ans_subscriber_proxy.cpp", + "//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/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", + ] + + 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/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] + + subsystem_name = "notification" + part_name = "ans_standard" +} + +group("moduletest") { + testonly = true + deps = [] + + deps += [ ":ans_fw_module_test" ] +} diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a33dab286b54ad5511a9a0ca73e24a6f0f928f8 --- /dev/null +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -0,0 +1,873 @@ +#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_content.h" +#include "notification_helper.h" +#include "notification_long_text_content.h" +#include "notification_subscriber.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +const int32_t USLEEP_TIME = 10000; +bool callBackFunReceived = false; +bool OnConsumedReceived = false; +bool OnCanceledReceived = false; +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 + { + OnCanceledReceived = true; + } + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override + { + callBackFunReceived = false; + } + virtual void OnConsumed(const std::shared_ptr &request) override + { + OnConsumedReceived = true; + } + virtual void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override + { + callBackFunReceived = true; + } +}; + +class AnsFWModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +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); +} + +void AnsFWModuleTest::TearDownTestCase() +{} + +void AnsFWModuleTest::SetUp() +{ + callBackFunReceived = false; + OnConsumedReceived = false; + OnCanceledReceived = false; +} + +void AnsFWModuleTest::TearDown() +{ + NotificationHelper::CancelAllNotifications(); + sleep(1); +} + +/** + * @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)); + + + 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); + 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)); +} + +/** + * @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)); + + 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); + 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(0, NotificationHelper::RemoveNotification(key)); + usleep(USLEEP_TIME); + EXPECT_EQ(OnCanceledReceived, true); + usleep(USLEEP_TIME); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); +} + +/** + * @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)); + + 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); + 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_INVALID_PARAM, (int)NotificationHelper::RemoveNotification(std::string())); + usleep(USLEEP_TIME); + EXPECT_EQ(OnCanceledReceived, false); + usleep(USLEEP_TIME); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); +} + +/** + * @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::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); + 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)); +} + +/** + * @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) +{ + 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); + + 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 = notifications[0]->GetKey().c_str(); + + 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)); +} + +/** + * @tc.number : ANS_FW_MT_RemoveNotification_00600 + * @tc.name : + * @tc.desc : Delete an Unremovable notification. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00600, 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); + + 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)); +} + +/** + * @tc.number : ANS_FW_MT_RemoveNotification_00700 + * @tc.name : + * @tc.desc : Delete all notifications including Unremovable notifications. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00700, 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); + + 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)); +} + +/** + * @tc.number : ANS_FW_MT_RemoveNotification_00800 + * @tc.name : + * @tc.desc : Delete notification based on bundle. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00800, 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); + + 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)); +} + +/** + * @tc.number : ANS_FW_MT_RemoveNotification_00900 + * @tc.name : + * @tc.desc : Delete notification based on A non-existent bundle. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotification_00900, 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); + + 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()); + + 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)); +} + +/** + * @tc.number : ANS_FW_MT_GetActiveNotificationNums_00100 + * @tc.name : + * @tc.desc : Get the number of active notifications for the current application. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetActiveNotificationNums_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); + + 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)); +} + +/** + * @tc.number : ANS_FW_MT_GetActiveNotificationNums_00200 + * @tc.name : + * @tc.desc : Get the number of active notifications for the current application. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetActiveNotificationNums_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; + + 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)); +} + +/** + * @tc.number : ANS_FW_MT_GetActiveNotifications_00100 + * @tc.name : + * @tc.desc : Get the active notifications for the current application. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetActiveNotifications_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); + + 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)); +} + +/** + * @tc.number : ANS_FW_MT_GetActiveNotifications_00200 + * @tc.name : + * @tc.desc : Get the active notifications for the current application. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetActiveNotifications_00200, 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)); +} + +/** + * @tc.number : ANS_FW_MT_GetAllActiveNotifications_00100 + * @tc.name : + * @tc.desc : Get all of active notifications for the current application. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetAllActiveNotifications_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); + + 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; + + 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)); +} + +/** + * @tc.number : ANS_FW_MT_GetAllActiveNotifications_00200 + * @tc.name : + * @tc.desc : Get all of active notifications for the current application. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetAllActiveNotifications_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); + + 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); + + std::vector> notifications; + EXPECT_EQ((int)ERR_OK, NotificationHelper::GetAllActiveNotifications(notifications)); + EXPECT_EQ(nullptr, notifications[0]); + + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); +} + +/** + * @tc.number : ANS_FW_MT_GetAllActiveNotifications_key_00100 + * @tc.name : + * @tc.desc : Get the active notifications related by key for the current application. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetAllActiveNotifications_key_00100, Function | MediumTest | Level1) +{ + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + + + std::vector key{"key_type1", "key_type2"}; + + std::string label1 = "label1"; + std::string label2 = "label2"; + std::string label3 = "label3"; + + NotificationRequest req1(0); + req1.SetSortingKey(key[0]); + req1.SetLabel(label1); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); + EXPECT_EQ(OnConsumedReceived, true); + OnConsumedReceived = false; + + NotificationRequest req2(0); + req2.SetSortingKey(key[0]); + req2.SetLabel(label2); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); + EXPECT_EQ(OnConsumedReceived, true); + OnConsumedReceived = false; + + NotificationRequest req3(0); + req3.SetSortingKey(key[1]); + req3.SetLabel(label3); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); + EXPECT_EQ(OnConsumedReceived, true); + OnConsumedReceived = false; + + std::vector> notifications; + EXPECT_EQ((int)ERR_OK, NotificationHelper::GetAllActiveNotifications(key, notifications)); + EXPECT_EQ(label1, notifications[0]->GetLabel()); + EXPECT_EQ(label2, notifications[1]->GetLabel()); + EXPECT_EQ(label3, notifications[2]->GetLabel()); + + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); +} + +/** + * @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)); + + + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); +} + +/** + * @tc.number : ANS_FW_MT_Subscribe_00100 + * @tc.name : + * @tc.desc : produce a subscribe + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_WantAgent_00100, Function | MediumTest | Level1) +{ + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + + + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); +} + +/** + * @tc.number : ANS_FW_MT_DeleteSlots_00100 + * @tc.name : + * @tc.desc : Delete slots. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_DeleteSlots_00100, Function | MediumTest | Level1) +{ + auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + 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(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 content = std::make_shared(implContent); + + NotificationRequest req(0); + req.SetContent(content); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + EXPECT_EQ(OnConsumedReceived, true); + + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..960b2aa7ba3a36c6b849dbf2b88728dae7186684 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h @@ -0,0 +1,413 @@ +/* + * 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 "ohos/aafwk/content/want.h" +#include "iremote_proxy.h" +#include "iremote_stub.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/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp b/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..340c592c36bce2f869e862a2e1af34d8d8e8ac5f --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp @@ -0,0 +1,45 @@ +/* + * 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 "ability_info.h" +#include "application_info.h" +#include "mock_bundle_manager.h" + +namespace OHOS { +namespace AppExecFwk { +void MockBundleMgrService::MockSetIsSystemApp(bool isSystemApp) +{ + isSystemAppMock_ = true; + isSystemApp_ = isSystemApp; +} + +bool MockBundleMgrService::CheckIsSystemAppByUid(const int uid) +{ + if (isSystemAppMock_) { + return isSystemApp_; + } + return (uid < 1000) ? false : true; +} + +int MockBundleMgrService::CheckPermission(const std::string &bundleName, const std::string &permission) +{ + if (!bundleName.compare("hello")) { + return 0; + } else { + return -1; + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd58a48388c28f596e09b1eb2933dfb6492ffd46 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -0,0 +1,282 @@ +/* + * 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/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp b/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4fcdd4a2c2f0b98f6108f5736524c72f179c854c --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp @@ -0,0 +1,124 @@ +/* + * 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 "event_handler.h" +#include "event_handler_utils.h" +#include + +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) + { + 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/ans/test/moduletest/mock/mock_ipc.cpp b/frameworks/ans/test/moduletest/mock/mock_ipc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1acbe4a3fd7b60e0a044d5f21d3fdfa60c25f879 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_ipc.cpp @@ -0,0 +1,27 @@ +/* + * 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_skeleton.h" + +namespace OHOS { +#ifdef CONFIG_IPC_SINGLE +using namespace IPC_SINGLE; +#endif +pid_t IPCSkeleton::GetCallingUid() +{ + pid_t uid = 1; + return 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 new file mode 100644 index 0000000000000000000000000000000000000000..4c184d7ebdedf02e998885a16bec6549bff2e97c --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_ipc_object_proxy.cpp @@ -0,0 +1,369 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..0e4751f1ccf8fd8400b60f7099fc2b3ed9040a95 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp @@ -0,0 +1,328 @@ +/* + * 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 "message_parcel.h" +#include +#include + +#include "ipc_debug.h" +#include "iremote_object.h" +#include "ipc_file_descriptor.h" +#include "sys_binder.h" +#include "ashmem.h" +#include "securec.h" +#include "ans_manager_stub.h" + +namespace OHOS { +MessageParcel::MessageParcel() + : Parcel(), + writeRawDataFd_(-1), + readRawDataFd_(-1), + kernelMappedWrite_(nullptr), + kernelMappedRead_(nullptr), + rawData_(nullptr), + rawDataSize_(0) +{} + +MessageParcel::MessageParcel(Allocator *allocator) + : Parcel(allocator), + writeRawDataFd_(-1), + readRawDataFd_(-1), + kernelMappedWrite_(nullptr), + kernelMappedRead_(nullptr), + rawData_(nullptr), + rawDataSize_(0) +{} + +MessageParcel::~MessageParcel() +{ + if (kernelMappedWrite_ != nullptr) { + ::munmap(kernelMappedWrite_, rawDataSize_); + kernelMappedWrite_ = nullptr; + } + if (kernelMappedRead_ != nullptr) { + ::munmap(kernelMappedRead_, rawDataSize_); + kernelMappedRead_ = nullptr; + } + + if (readRawDataFd_ > 0) { + ::close(readRawDataFd_); + readRawDataFd_ = -1; + } + if (writeRawDataFd_ > 0) { + ::close(writeRawDataFd_); + writeRawDataFd_ = -1; + } + + ClearFileDescriptor(); + + rawData_ = nullptr; + rawDataSize_ = 0; +} + +bool MessageParcel::WriteRemoteObject(const sptr &object) +{ + holders_.push_back(object); + return WriteObject(object); +} + +sptr MessageParcel::ReadRemoteObject() +{ + return ReadObject(); +} + +bool MessageParcel::WriteFileDescriptor(int fd) +{ + if (fd < 0) { + return false; + } + int dupFd = dup(fd); + if (dupFd < 0) { + return false; + } + sptr descriptor = new IPCFileDescriptor(dupFd); + return WriteObject(descriptor); +} + +int MessageParcel::ReadFileDescriptor() +{ + sptr descriptor = ReadObject(); + if (descriptor == nullptr) { + return -1; + } + int fd = descriptor->GetFd(); + if (fd < 0) { + return -1; + } + holders_.push_back(descriptor); + return dup(fd); +} + +void MessageParcel::ClearFileDescriptor() +{ + binder_size_t *object = reinterpret_cast(GetObjectOffsets()); + size_t objectNum = GetOffsetsSize(); + uintptr_t data = GetData(); + for (size_t i = 0; i < objectNum; i++) { + const flat_binder_object *flat = reinterpret_cast(data + object[i]); + if (flat->hdr.type == BINDER_TYPE_FD && flat->handle > 0) { + ::close(flat->handle); + } + } +} + +bool MessageParcel::ContainFileDescriptors() const +{ + binder_size_t *object = reinterpret_cast(GetObjectOffsets()); + size_t objectNum = GetOffsetsSize(); + uintptr_t data = GetData(); + for (size_t i = 0; i < objectNum; i++) { + const flat_binder_object *flat = reinterpret_cast(data + object[i]); + if (flat->hdr.type == BINDER_TYPE_FD) { + return true; + } + } + + return false; +} + +bool MessageParcel::WriteInterfaceToken(std::u16string name) +{ + constexpr int strictModePolicy = 0x100; + constexpr int workSource = 0; + size_t rewindPos = GetWritePosition(); + if (!WriteInt32(strictModePolicy)) { + return false; + } + + if (!WriteInt32(workSource)) { + if (!RewindWrite(rewindPos)) { + FlushBuffer(); + } + return false; + } + + return WriteString16(name); +} + +std::u16string MessageParcel::ReadInterfaceToken() +{ + [[maybe_unused]] int strictModePolicy = ReadInt32(); + [[maybe_unused]] int workSource = ReadInt32(); + return ReadString16(); +} + +bool MessageParcel::WriteRawData(const void *data, size_t size) +{ + if (data == nullptr || size > MAX_RAWDATA_SIZE) { + return false; + } + if (kernelMappedWrite_ != nullptr) { + return false; + } + if (!WriteInt32(size)) { + return false; + } + if (size <= MIN_RAWDATA_SIZE) { + return WriteUnpadBuffer(data, size); + } + int fd = AshmemCreate("Parcel RawData", size); + if (fd < 0) { + return false; + } + writeRawDataFd_ = fd; + + int result = AshmemSetProt(fd, PROT_READ | PROT_WRITE); + if (result < 0) { + return false; + } + void *ptr = ::mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (ptr == MAP_FAILED) { + return false; + } + if (!WriteFileDescriptor(fd)) { + ::munmap(ptr, size); + return false; + } + if (memcpy_s(ptr, size, data, size) != EOK) { + ::munmap(ptr, size); + return false; + } + kernelMappedWrite_ = ptr; + rawDataSize_ = size; + return true; +} + +bool MessageParcel::RestoreRawData(std::shared_ptr rawData, size_t size) +{ + if (rawData_ != nullptr || rawData == nullptr) { + return false; + } + rawData_ = rawData; + rawDataSize_ = size; + writeRawDataFd_ = 0; + return true; +} + +const void *MessageParcel::ReadRawData(size_t size) +{ + int32_t bufferSize = ReadInt32(); + if (static_cast(bufferSize) != size) { + return nullptr; + } + + if (static_cast(bufferSize) <= MIN_RAWDATA_SIZE) { + return ReadUnpadBuffer(size); + } + + /* if rawDataFd_ == 0 means rawData is received from remote + */ + if (rawData_ != nullptr && writeRawDataFd_ == 0) { + /* should read fd for move readCursor of parcel */ + if (ReadFileDescriptor()) { + // do nothing + } + if (rawDataSize_ != size) { + return nullptr; + } + return rawData_.get(); + } + int fd = ReadFileDescriptor(); + if (fd < 0) { + return nullptr; + } + readRawDataFd_ = fd; + + int ashmemSize = AshmemGetSize(fd); + if (ashmemSize < 0 || size_t(ashmemSize) < size) { + // do not close fd here. fd will be closed in FileDescriptor, ::close(fd) + return nullptr; + } + void *ptr = ::mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0); + if (ptr == MAP_FAILED) { + // do not close fd here. fd will be closed in FileDescriptor, ::close(fd) + return nullptr; + } + kernelMappedRead_ = ptr; + rawDataSize_ = size; + return ptr; +} + +const void *MessageParcel::GetRawData() const +{ + if (rawData_ != nullptr) { + return rawData_.get(); + } + if (kernelMappedWrite_ != nullptr) { + return kernelMappedWrite_; + } + if (kernelMappedRead_ != nullptr) { + return kernelMappedRead_; + } + return nullptr; +} + +size_t MessageParcel::GetRawDataSize() const +{ + return rawDataSize_; +} + +size_t MessageParcel::GetRawDataCapacity() const +{ + return MAX_RAWDATA_SIZE; +} + +void MessageParcel::WriteNoException() +{ + WriteInt32(0); +} + +int32_t MessageParcel::ReadException() +{ + int32_t errorCode = ReadInt32(); + if (errorCode != 0) { + ReadString16(); + } + return errorCode; +} + +bool MessageParcel::WriteAshmem(sptr ashmem) +{ + int fd = ashmem->GetAshmemFd(); + int32_t size = ashmem->GetAshmemSize(); + if (fd < 0 || size <= 0) { + return false; + } + if (!WriteFileDescriptor(fd) || !WriteInt32(size)) { + return false; + } + return true; +} + +sptr MessageParcel::ReadAshmem() +{ + int fd = ReadFileDescriptor(); + if (fd < 0) { + return nullptr; + } + + int32_t size = ReadInt32(); + if (size <= 0) { + ::close(fd); + return nullptr; + } + return new Ashmem(fd, size); +} +} // namespace OHOS diff --git a/kits/native/wantagent/BUILD.gn b/frameworks/wantagent/BUILD.gn similarity index 83% rename from kits/native/wantagent/BUILD.gn rename to frameworks/wantagent/BUILD.gn index 6dce5f3aab25402d1fc1d4eb01058fd20fe28118..d201befdf68912cebce1317824cc55c721cde375 100644 --- a/kits/native/wantagent/BUILD.gn +++ b/frameworks/wantagent/BUILD.gn @@ -15,16 +15,14 @@ import("//base/notification/ans_standard/notification.gni") import("//build/ohos.gni") group("native_wantagent") { - deps = [ ":wantagent_kits" ] + deps = [ ":wantagent_innerkits" ] } -config("wantagent_kit_public_config") { +config("wantagent_innerkits_public_config") { visibility = [ ":*" ] include_dirs = [ - "${innerkits_path}/core/include", - "${innerkits_path}/base/include", - "${kits_path}/native/wantagent/include", + "${interfaces_path}/innerkits/wantagent/include", "//base/global/resmgr_standard/interfaces/innerkits/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", @@ -38,13 +36,11 @@ config("wantagent_kit_public_config") { ] } -ohos_shared_library("wantagent_kits") { +ohos_shared_library("wantagent_innerkits") { include_dirs = [ "//utils/native/base/include", "//foundation/aafwk/standard/services/common/include", "//foundation/distributedschedule/safwk/services/safwk/include", - "//base/notification/ces_standard/cesfwk/innerkits/include", - "//base/notification/ces_standard/cesfwk/kits/native/include", ] sources = [ @@ -59,13 +55,11 @@ ohos_shared_library("wantagent_kits") { configs = [ "//utils/native/base:utils_config" ] - public_configs = [ ":wantagent_kit_public_config" ] + public_configs = [ ":wantagent_innerkits_public_config" ] deps = [ - "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", @@ -76,6 +70,7 @@ ohos_shared_library("wantagent_kits") { ] external_deps = [ + "ces_standard:cesfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "samgr_L2:samgr_proxy", diff --git a/kits/native/wantagent/src/completed_dispatcher.cpp b/frameworks/wantagent/src/completed_dispatcher.cpp similarity index 100% rename from kits/native/wantagent/src/completed_dispatcher.cpp rename to frameworks/wantagent/src/completed_dispatcher.cpp diff --git a/kits/native/wantagent/src/pending_want.cpp b/frameworks/wantagent/src/pending_want.cpp similarity index 100% rename from kits/native/wantagent/src/pending_want.cpp rename to frameworks/wantagent/src/pending_want.cpp diff --git a/kits/native/wantagent/src/trigger_info.cpp b/frameworks/wantagent/src/trigger_info.cpp similarity index 100% rename from kits/native/wantagent/src/trigger_info.cpp rename to frameworks/wantagent/src/trigger_info.cpp diff --git a/kits/native/wantagent/src/want_agent.cpp b/frameworks/wantagent/src/want_agent.cpp similarity index 100% rename from kits/native/wantagent/src/want_agent.cpp rename to frameworks/wantagent/src/want_agent.cpp diff --git a/kits/native/wantagent/src/want_agent_helper.cpp b/frameworks/wantagent/src/want_agent_helper.cpp similarity index 98% rename from kits/native/wantagent/src/want_agent_helper.cpp rename to frameworks/wantagent/src/want_agent_helper.cpp index 2a59abfc5569d5247b98d448ad8fb54f249e0672..3c59c41a82035aeafac069077f376163083f7b69 100644 --- a/kits/native/wantagent/src/want_agent_helper.cpp +++ b/frameworks/wantagent/src/want_agent_helper.cpp @@ -32,6 +32,7 @@ unsigned int WantAgentHelper::FlagsTransformer(const std::vector WantAgentHelper::GetWantAgent( } std::vector> wants = paramsInfo.GetWants(); - if (wants.empty() || paramsInfo.GetFlags().size() != wants.size()) { + if (wants.empty()) { WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent invalid input param."); return nullptr; } @@ -124,7 +125,7 @@ std::shared_ptr WantAgentHelper::GetWantAgent( std::shared_ptr WantAgentHelper::GetWantAgent(const WantAgentInfo ¶msInfo) { std::vector> wants = paramsInfo.GetWants(); - if (wants.empty() || (paramsInfo.GetFlags().size() != wants.size())) { + if (wants.empty()) { WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent invalid input param."); return nullptr; } diff --git a/kits/native/wantagent/src/want_agent_info.cpp b/frameworks/wantagent/src/want_agent_info.cpp similarity index 100% rename from kits/native/wantagent/src/want_agent_info.cpp rename to frameworks/wantagent/src/want_agent_info.cpp diff --git a/kits/native/wantagent/src/want_agent_log_wrapper.cpp b/frameworks/wantagent/src/want_agent_log_wrapper.cpp similarity index 100% rename from kits/native/wantagent/src/want_agent_log_wrapper.cpp rename to frameworks/wantagent/src/want_agent_log_wrapper.cpp diff --git a/kits/native/wantagent/test/BUILD.gn b/frameworks/wantagent/test/BUILD.gn similarity index 100% rename from kits/native/wantagent/test/BUILD.gn rename to frameworks/wantagent/test/BUILD.gn diff --git a/kits/native/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn b/frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn similarity index 86% rename from kits/native/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn rename to frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn index 64fc48665b8d8c9d8b7e9ff971360ddd73ce4d53..45b7c58e89e625c0ec04ed2cf13bcf5c2f24a731 100644 --- a/kits/native/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn @@ -20,8 +20,6 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("completed_dispatcher_test") { module_out_path = module_output_path include_dirs = [ - "${kits_path}/native/include", - "${kits_path}/native/wantagent/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include", "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", @@ -31,18 +29,14 @@ ohos_unittest("completed_dispatcher_test") { sources = [ "completed_dispatcher_test.cpp" ] - configs = [ - "//utils/native/base:utils_config", - "${innerkits_path}:public_ans_innerkits_config", - ] + configs = [ "//utils/native/base:utils_config" ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${innerkits_path}:ans_innerkits", - "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", - "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "${core_path}:ans_core", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", @@ -60,6 +54,7 @@ ohos_unittest("completed_dispatcher_test") { ] external_deps = [ + "ces_standard:cesfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/kits/native/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp b/frameworks/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp similarity index 100% rename from kits/native/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp rename to frameworks/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp diff --git a/kits/native/wantagent/test/unittest/pending_want_test/BUILD.gn b/frameworks/wantagent/test/unittest/pending_want_test/BUILD.gn similarity index 87% rename from kits/native/wantagent/test/unittest/pending_want_test/BUILD.gn rename to frameworks/wantagent/test/unittest/pending_want_test/BUILD.gn index 7a5f16587e04d907e3afce56dc949386d88dbed2..46d9f1e375e168767c51d2729ff6348a41ec3853 100644 --- a/kits/native/wantagent/test/unittest/pending_want_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/pending_want_test/BUILD.gn @@ -20,8 +20,6 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("pending_want_test") { module_out_path = module_output_path include_dirs = [ - "${kits_path}/native/include", - "${kits_path}/native/wantagent/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include", "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", @@ -35,18 +33,14 @@ ohos_unittest("pending_want_test") { sources = [ "pending_want_test.cpp" ] - configs = [ - "//utils/native/base:utils_config", - "${innerkits_path}:public_ans_innerkits_config", - ] + configs = [ "//utils/native/base:utils_config" ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${innerkits_path}:ans_innerkits", - "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", - "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "${core_path}:ans_core", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", @@ -64,6 +58,7 @@ ohos_unittest("pending_want_test") { ] external_deps = [ + "ces_standard:cesfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/kits/native/wantagent/test/unittest/pending_want_test/pending_want_test.cpp b/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp similarity index 100% rename from kits/native/wantagent/test/unittest/pending_want_test/pending_want_test.cpp rename to frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp diff --git a/kits/native/wantagent/test/unittest/trigger_Info_test/BUILD.gn b/frameworks/wantagent/test/unittest/trigger_Info_test/BUILD.gn similarity index 86% rename from kits/native/wantagent/test/unittest/trigger_Info_test/BUILD.gn rename to frameworks/wantagent/test/unittest/trigger_Info_test/BUILD.gn index f4d9729ef927971ef4a48c40d2690b33391d3fe2..13fcb04025e4b7229c66c955025807fe9e778bbb 100644 --- a/kits/native/wantagent/test/unittest/trigger_Info_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/trigger_Info_test/BUILD.gn @@ -20,8 +20,6 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("trigger_Info_test") { module_out_path = module_output_path include_dirs = [ - "${kits_path}/native/include", - "${kits_path}/native/wantagent/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include", "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", @@ -31,18 +29,14 @@ ohos_unittest("trigger_Info_test") { sources = [ "trigger_Info_test.cpp" ] - configs = [ - "//utils/native/base:utils_config", - "${innerkits_path}:public_ans_innerkits_config", - ] + configs = [ "//utils/native/base:utils_config" ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${innerkits_path}:ans_innerkits", - "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", - "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "${core_path}:ans_core", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", @@ -60,6 +54,7 @@ ohos_unittest("trigger_Info_test") { ] external_deps = [ + "ces_standard:cesfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/kits/native/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp b/frameworks/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp similarity index 100% rename from kits/native/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp rename to frameworks/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp diff --git a/kits/native/wantagent/test/unittest/want_agent_helper_test/BUILD.gn b/frameworks/wantagent/test/unittest/want_agent_helper_test/BUILD.gn similarity index 86% rename from kits/native/wantagent/test/unittest/want_agent_helper_test/BUILD.gn rename to frameworks/wantagent/test/unittest/want_agent_helper_test/BUILD.gn index c3faf5baf1b79f9126b78c37181a89a8f031e140..02dd1270e82f3ff787cc84ed2edbef82088a6b59 100644 --- a/kits/native/wantagent/test/unittest/want_agent_helper_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/want_agent_helper_test/BUILD.gn @@ -20,8 +20,6 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("want_agent_helper_test") { module_out_path = module_output_path include_dirs = [ - "${kits_path}/native/include", - "${kits_path}/native/wantagent/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include", "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", @@ -31,18 +29,14 @@ ohos_unittest("want_agent_helper_test") { sources = [ "want_agent_helper_test.cpp" ] - configs = [ - "//utils/native/base:utils_config", - "${innerkits_path}:public_ans_innerkits_config", - ] + configs = [ "//utils/native/base:utils_config" ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${innerkits_path}:ans_innerkits", - "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", - "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "${core_path}:ans_core", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", @@ -60,6 +54,7 @@ ohos_unittest("want_agent_helper_test") { ] external_deps = [ + "ces_standard:cesfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/kits/native/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 similarity index 100% rename from kits/native/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp rename to frameworks/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp diff --git a/kits/native/wantagent/test/unittest/want_agent_info_test/BUILD.gn b/frameworks/wantagent/test/unittest/want_agent_info_test/BUILD.gn similarity index 86% rename from kits/native/wantagent/test/unittest/want_agent_info_test/BUILD.gn rename to frameworks/wantagent/test/unittest/want_agent_info_test/BUILD.gn index 979db4d1105a5e77ecb42275309ea43eaea9be68..6175002f2ef60e5b0cbf37ec2138f2c7eea41c01 100644 --- a/kits/native/wantagent/test/unittest/want_agent_info_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/want_agent_info_test/BUILD.gn @@ -20,8 +20,6 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("want_agent_info_test") { module_out_path = module_output_path include_dirs = [ - "${kits_path}/native/include", - "${kits_path}/native/wantagent/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include", "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", @@ -31,18 +29,14 @@ ohos_unittest("want_agent_info_test") { sources = [ "want_agent_info_test.cpp" ] - configs = [ - "//utils/native/base:utils_config", - "${innerkits_path}:public_ans_innerkits_config", - ] + configs = [ "//utils/native/base:utils_config" ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${innerkits_path}:ans_innerkits", - "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", - "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "${core_path}:ans_core", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", @@ -60,6 +54,7 @@ ohos_unittest("want_agent_info_test") { ] external_deps = [ + "ces_standard:cesfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/kits/native/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 similarity index 100% rename from kits/native/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp rename to frameworks/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp diff --git a/kits/native/wantagent/test/unittest/want_agent_test/BUILD.gn b/frameworks/wantagent/test/unittest/want_agent_test/BUILD.gn similarity index 86% rename from kits/native/wantagent/test/unittest/want_agent_test/BUILD.gn rename to frameworks/wantagent/test/unittest/want_agent_test/BUILD.gn index 50feeea168fe527cb98dd9081671cc612e07b111..4a0ccaebd1d38e6dba64b7355950e0f8a248bce6 100644 --- a/kits/native/wantagent/test/unittest/want_agent_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/want_agent_test/BUILD.gn @@ -20,8 +20,6 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("want_agent_test") { module_out_path = module_output_path include_dirs = [ - "${kits_path}/native/include", - "${kits_path}/native/wantagent/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include", "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", @@ -31,18 +29,14 @@ ohos_unittest("want_agent_test") { sources = [ "want_agent_test.cpp" ] - configs = [ - "//utils/native/base:utils_config", - "${innerkits_path}:public_ans_innerkits_config", - ] + configs = [ "//utils/native/base:utils_config" ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${innerkits_path}:ans_innerkits", - "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", - "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "${core_path}:ans_core", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", @@ -60,6 +54,7 @@ ohos_unittest("want_agent_test") { ] external_deps = [ + "ces_standard:cesfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/kits/native/wantagent/test/unittest/want_agent_test/want_agent_test.cpp b/frameworks/wantagent/test/unittest/want_agent_test/want_agent_test.cpp similarity index 100% rename from kits/native/wantagent/test/unittest/want_agent_test/want_agent_test.cpp rename to frameworks/wantagent/test/unittest/want_agent_test/want_agent_test.cpp diff --git a/interfaces/BUILD.gn b/interfaces/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2c3010f9cc0e8536af768dddea767ee83903e2ee --- /dev/null +++ b/interfaces/BUILD.gn @@ -0,0 +1,19 @@ +# 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. + +group("interfaces_target") { + deps = [ + "kits/napi/ans:notification", + "kits/napi/wantagent:wantagent", + ] +} diff --git a/kits/native/include/message_user.h b/interfaces/innerkits/ans/native/include/message_user.h similarity index 100% rename from kits/native/include/message_user.h rename to interfaces/innerkits/ans/native/include/message_user.h diff --git a/kits/native/include/notification.h b/interfaces/innerkits/ans/native/include/notification.h similarity index 82% rename from kits/native/include/notification.h rename to interfaces/innerkits/ans/native/include/notification.h index b8c9d0bbdc8695cfc4aa2b606639790e27043c3a..ab91f6690c668fbba696b276813e7fdf203bf687 100644 --- a/kits/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -97,7 +97,7 @@ public: * * @return Return the display effect of this notification on the lock screen. */ - int32_t GetLockscreenVisibleness() const; + NotificationConstant::VisiblenessType GetLockscreenVisibleness() const; /** * @brief The ID passed to setGroup(), or the override, or null. @@ -142,11 +142,18 @@ public: Uri GetSound() const; /** - * @brief Obtains bundle's uid. + * @brief Obtains the UID of the notification creator. * - * @return Return the uid set by ANS. + * @return Return the UID of the notification creator. */ - int32_t GetUid() const; + uid_t GetUid() const; + + /** + * @brief Obtains the PID of the notification creator. + * + * @return Return the PID of the notification creator. + */ + uid_t GetPid() const; /** * @brief Obtains the vibration style for this notifications. if @@ -162,6 +169,13 @@ public: */ bool IsGroup() const; + /** + * @brief Checks whether this notification is displayed as a floating icon on top of the screen. + * + * @return true if this notification is displayed as a floating icon; returns false otherwise. + */ + bool IsFloatingIcon() const; + /** * @brief Dumps a string representation of the object. * @@ -189,8 +203,11 @@ public: private: Notification(); + void SetEnableSound(const bool &enable); + void SetEnableLight(const bool &enable); + void SetEnableViration(const bool &enable); void SetLedLightColor(const int32_t &color); - void SetLockScreenVisbleness(const int32_t &visbleness); + void SetLockScreenVisbleness(const NotificationConstant::VisiblenessType &visbleness); void SetPostTime(const int64_t &time); void SetSound(const Uri &sound); void SetVibrationStyle(const std::vector &style); @@ -198,12 +215,15 @@ private: std::string GenerateNotificationKey(int32_t uid, const std::string &label, int32_t id); private: + bool enableSound_{false}; + bool enableLight_{false}; + bool enableViration_{false}; std::string key_{""}; - int32_t ledLightColor_ = -1; - int32_t lockscreenVisibleness_; - sptr request_ = nullptr; - int64_t postTime_; - std::shared_ptr sound_ = nullptr; + int32_t ledLightColor_{0}; + NotificationConstant::VisiblenessType lockscreenVisibleness_{NotificationConstant::VisiblenessType::NO_OVERRIDE}; + sptr request_{nullptr}; + int64_t postTime_{0}; + std::shared_ptr sound_{nullptr}; std::vector vibrationStyle_{}; friend class AdvancedNotificationService; diff --git a/kits/native/include/notification_action_button.h b/interfaces/innerkits/ans/native/include/notification_action_button.h similarity index 99% rename from kits/native/include/notification_action_button.h rename to interfaces/innerkits/ans/native/include/notification_action_button.h index 32186dce9cc2c4596b721fa56d8cfbd37a256084..adda5ae958ce352bb29c066b94e04f7d94d7f00b 100644 --- a/kits/native/include/notification_action_button.h +++ b/interfaces/innerkits/ans/native/include/notification_action_button.h @@ -54,24 +54,18 @@ public: */ ~NotificationActionButton() = default; - /** - * Adds additional data to this Builder. - * @param pacMap Indicates the PacMap object containing the additional data. - */ - void AddAdditionalData(AppExecFwk::PacMap &pacMap); - - /** - * Obtains the additional data included in this NotificationActionButton. - * @return the additional data included in this NotificationActionButton. - */ - const std::shared_ptr GetAdditionalData() const; - /** * Obtains the icon of this NotificationActionButton. * @return the icon of this NotificationActionButton. */ const std::shared_ptr GetIcon() const; + /** + * Obtains the title of this NotificationActionButton. + * @return the title of this NotificationActionButton. + */ + std::string GetTitle() const; + /** * Obtains the WantAgent of this NotificationActionButton. * @return the WantAgent of this NotificationActionButton. @@ -79,11 +73,16 @@ public: const std::shared_ptr GetWantAgent() 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. + * Adds additional data to this NotificationActionButton. + * @param pacMap Indicates the PacMap object containing the additional data. */ - std::vector> GetMimeTypeOnlyUserInputs() const; + void AddAdditionalData(AppExecFwk::PacMap &pacMap); + + /** + * Obtains the additional data included in this NotificationActionButton. + * @return the additional data included in this NotificationActionButton. + */ + const std::shared_ptr GetAdditionalData() const; /** * Sets a semantic action for this NotificationActionButton. @@ -99,12 +98,6 @@ public: */ NotificationConstant::SemanticActionButton GetSemanticActionButton() const; - /** - * Obtains the title of this NotificationActionButton. - * @return the title of this NotificationActionButton. - */ - std::string GetTitle() const; - /** * Adds a NotificationUserInput object used to collect user input. * @param userInput Indicates the NotificationUserInput object to add. @@ -118,6 +111,13 @@ 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(). diff --git a/kits/native/include/notification_basic_content.h b/interfaces/innerkits/ans/native/include/notification_basic_content.h similarity index 100% rename from kits/native/include/notification_basic_content.h rename to interfaces/innerkits/ans/native/include/notification_basic_content.h diff --git a/kits/native/include/notification_constant.h b/interfaces/innerkits/ans/native/include/notification_constant.h similarity index 100% rename from kits/native/include/notification_constant.h rename to interfaces/innerkits/ans/native/include/notification_constant.h diff --git a/kits/native/include/notification_content.h b/interfaces/innerkits/ans/native/include/notification_content.h similarity index 100% rename from kits/native/include/notification_content.h rename to interfaces/innerkits/ans/native/include/notification_content.h diff --git a/kits/native/include/notification_conversational_content.h b/interfaces/innerkits/ans/native/include/notification_conversational_content.h similarity index 100% rename from kits/native/include/notification_conversational_content.h rename to interfaces/innerkits/ans/native/include/notification_conversational_content.h diff --git a/kits/native/include/notification_conversational_message.h b/interfaces/innerkits/ans/native/include/notification_conversational_message.h similarity index 100% rename from kits/native/include/notification_conversational_message.h rename to interfaces/innerkits/ans/native/include/notification_conversational_message.h diff --git a/kits/native/include/notification_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h similarity index 100% rename from kits/native/include/notification_helper.h rename to interfaces/innerkits/ans/native/include/notification_helper.h diff --git a/kits/native/include/notification_long_text_content.h b/interfaces/innerkits/ans/native/include/notification_long_text_content.h similarity index 100% rename from kits/native/include/notification_long_text_content.h rename to interfaces/innerkits/ans/native/include/notification_long_text_content.h diff --git a/kits/native/include/notification_media_content.h b/interfaces/innerkits/ans/native/include/notification_media_content.h similarity index 100% rename from kits/native/include/notification_media_content.h rename to interfaces/innerkits/ans/native/include/notification_media_content.h diff --git a/kits/native/include/notification_multiline_content.h b/interfaces/innerkits/ans/native/include/notification_multiline_content.h similarity index 100% rename from kits/native/include/notification_multiline_content.h rename to interfaces/innerkits/ans/native/include/notification_multiline_content.h diff --git a/kits/native/include/notification_normal_content.h b/interfaces/innerkits/ans/native/include/notification_normal_content.h similarity index 100% rename from kits/native/include/notification_normal_content.h rename to interfaces/innerkits/ans/native/include/notification_normal_content.h diff --git a/kits/native/include/notification_picture_content.h b/interfaces/innerkits/ans/native/include/notification_picture_content.h similarity index 100% rename from kits/native/include/notification_picture_content.h rename to interfaces/innerkits/ans/native/include/notification_picture_content.h diff --git a/kits/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h similarity index 100% rename from kits/native/include/notification_request.h rename to interfaces/innerkits/ans/native/include/notification_request.h diff --git a/kits/native/include/notification_slot.h b/interfaces/innerkits/ans/native/include/notification_slot.h similarity index 99% rename from kits/native/include/notification_slot.h rename to interfaces/innerkits/ans/native/include/notification_slot.h index 84951f8001ef8cab3130fb1243f7639116c95603..c5cce655349f78045340f6d311b316e34f560b02 100644 --- a/kits/native/include/notification_slot.h +++ b/interfaces/innerkits/ans/native/include/notification_slot.h @@ -354,7 +354,7 @@ private: bool isBypassDnd_; std::string description_; int32_t lightColor_ = 0; - NotificationLevel level_; + NotificationLevel level_ = LEVEL_DEFAULT; NotificationConstant::SlotType type_; NotificationConstant::VisiblenessType lockScreenVisibleness_{NotificationConstant::VisiblenessType::NO_OVERRIDE}; std::string groupId_; diff --git a/kits/native/include/notification_slot_group.h b/interfaces/innerkits/ans/native/include/notification_slot_group.h similarity index 100% rename from kits/native/include/notification_slot_group.h rename to interfaces/innerkits/ans/native/include/notification_slot_group.h diff --git a/kits/native/include/notification_sorting.h b/interfaces/innerkits/ans/native/include/notification_sorting.h similarity index 100% rename from kits/native/include/notification_sorting.h rename to interfaces/innerkits/ans/native/include/notification_sorting.h diff --git a/kits/native/include/notification_sorting_map.h b/interfaces/innerkits/ans/native/include/notification_sorting_map.h similarity index 100% rename from kits/native/include/notification_sorting_map.h rename to interfaces/innerkits/ans/native/include/notification_sorting_map.h diff --git a/kits/native/include/notification_subscribe_info.h b/interfaces/innerkits/ans/native/include/notification_subscribe_info.h similarity index 100% rename from kits/native/include/notification_subscribe_info.h rename to interfaces/innerkits/ans/native/include/notification_subscribe_info.h diff --git a/kits/native/include/notification_subscriber.h b/interfaces/innerkits/ans/native/include/notification_subscriber.h similarity index 100% rename from kits/native/include/notification_subscriber.h rename to interfaces/innerkits/ans/native/include/notification_subscriber.h diff --git a/kits/native/include/notification_user_input.h b/interfaces/innerkits/ans/native/include/notification_user_input.h similarity index 100% rename from kits/native/include/notification_user_input.h rename to interfaces/innerkits/ans/native/include/notification_user_input.h diff --git a/kits/native/wantagent/include/cancel_listener.h b/interfaces/innerkits/wantagent/include/cancel_listener.h similarity index 100% rename from kits/native/wantagent/include/cancel_listener.h rename to interfaces/innerkits/wantagent/include/cancel_listener.h diff --git a/kits/native/wantagent/include/completed_callback.h b/interfaces/innerkits/wantagent/include/completed_callback.h similarity index 100% rename from kits/native/wantagent/include/completed_callback.h rename to interfaces/innerkits/wantagent/include/completed_callback.h diff --git a/kits/native/wantagent/include/completed_dispatcher.h b/interfaces/innerkits/wantagent/include/completed_dispatcher.h similarity index 100% rename from kits/native/wantagent/include/completed_dispatcher.h rename to interfaces/innerkits/wantagent/include/completed_dispatcher.h diff --git a/kits/native/wantagent/include/pending_want.h b/interfaces/innerkits/wantagent/include/pending_want.h similarity index 100% rename from kits/native/wantagent/include/pending_want.h rename to interfaces/innerkits/wantagent/include/pending_want.h diff --git a/kits/native/wantagent/include/trigger_info.h b/interfaces/innerkits/wantagent/include/trigger_info.h similarity index 100% rename from kits/native/wantagent/include/trigger_info.h rename to interfaces/innerkits/wantagent/include/trigger_info.h diff --git a/kits/native/wantagent/include/want_agent.h b/interfaces/innerkits/wantagent/include/want_agent.h similarity index 100% rename from kits/native/wantagent/include/want_agent.h rename to interfaces/innerkits/wantagent/include/want_agent.h diff --git a/kits/native/wantagent/include/want_agent_constant.h b/interfaces/innerkits/wantagent/include/want_agent_constant.h similarity index 100% rename from kits/native/wantagent/include/want_agent_constant.h rename to interfaces/innerkits/wantagent/include/want_agent_constant.h diff --git a/kits/native/wantagent/include/want_agent_helper.h b/interfaces/innerkits/wantagent/include/want_agent_helper.h similarity index 100% rename from kits/native/wantagent/include/want_agent_helper.h rename to interfaces/innerkits/wantagent/include/want_agent_helper.h diff --git a/kits/native/wantagent/include/want_agent_info.h b/interfaces/innerkits/wantagent/include/want_agent_info.h similarity index 100% rename from kits/native/wantagent/include/want_agent_info.h rename to interfaces/innerkits/wantagent/include/want_agent_info.h diff --git a/kits/native/wantagent/include/want_agent_log_wrapper.h b/interfaces/innerkits/wantagent/include/want_agent_log_wrapper.h similarity index 92% rename from kits/native/wantagent/include/want_agent_log_wrapper.h rename to interfaces/innerkits/wantagent/include/want_agent_log_wrapper.h index 1ecaab5e19e5d48cf0af1aa1be7c82104ba68b78..263310dfe9d8c8e453bc81c4d3f25ef1dc457511 100644 --- a/kits/native/wantagent/include/want_agent_log_wrapper.h +++ b/interfaces/innerkits/wantagent/include/want_agent_log_wrapper.h @@ -20,16 +20,16 @@ #include namespace OHOS::Notification::WantAgent { -#ifndef LOG_DOMAIN -#define LOG_DOMAIN 0xD001100 +#ifndef WANT_AGENT_LOG_DOMAIN +#define WANT_AGENT_LOG_DOMAIN 0xD001000 #endif -#ifndef APP_LOG_TAG -#define APP_LOG_TAG NULL +#ifndef WANT_AGENT_LOG_TAG +#define WANT_AGENT_LOG_TAG "WantAgent" #endif enum class WantAgentLogLevel { DEBUG = 0, INFO, WARN, ERROR, FATAL }; -static constexpr OHOS::HiviewDFX::HiLogLabel Want_Agent_LABEL = {LOG_CORE, LOG_DOMAIN, APP_LOG_TAG}; +static constexpr OHOS::HiviewDFX::HiLogLabel Want_Agent_LABEL = {LOG_CORE, WANT_AGENT_LOG_DOMAIN, WANT_AGENT_LOG_TAG}; class WantAgentLogWrapper { public: diff --git a/kits/napi/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn similarity index 75% rename from kits/napi/BUILD.gn rename to interfaces/kits/napi/ans/BUILD.gn index 7f6816f857c201fec308f56015e11d9f5a72c421..2c1ca3a90ebcbe3b20c1b87e3560694189b07a01 100644 --- a/kits/napi/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -33,8 +33,10 @@ config("native_module_config") { ohos_shared_library("notification") { include_dirs = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", "//foundation/ace/napi/interfaces/kits/napi", - "${kits_path}/napi/include", + "include", "//third_party/node/src", "//third_party/libuv/include", "//third_party/jsoncpp/include", @@ -57,9 +59,13 @@ ohos_shared_library("notification") { ] deps = [ - "${innerkits_path}:ans_innerkits", - "${kits_path}/native:ans_kits", - "${kits_path}/native/wantagent:wantagent_kits", + "${frameworks_path}/ans/core:ans_core", + "${frameworks_path}/ans/native:ans_innerkits", + "${frameworks_path}/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/ace/napi:ace_napi", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", diff --git a/kits/napi/include/cancel.h b/interfaces/kits/napi/ans/include/cancel.h similarity index 55% rename from kits/napi/include/cancel.h rename to interfaces/kits/napi/ans/include/cancel.h index 88e0d1287d2ab5f8f2d4af034405a199dcefb29b..6d41052f8af2140bf54bd577c1f265e61406f096 100644 --- a/kits/napi/include/cancel.h +++ b/interfaces/kits/napi/ans/include/cancel.h @@ -22,35 +22,8 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -const int CANCEL_MAX_PARA = 3; -const int CANCEL_ALL_MAX_PARA = 1; - -struct AsyncCallbackInfoCancel { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - std::string label; - int id; - bool hasLabel = false; - bool isCallback = false; - int errorCode = 0; -}; - -struct paraInfoCancel { - int id = 0; - std::string label; - bool hasLabel = false; -}; - napi_value Cancel(napi_env env, napi_callback_info info); napi_value CancelAll(napi_env env, napi_callback_info 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 ParseParametersByAll( - const napi_env &env, const napi_value (&argv)[CANCEL_ALL_MAX_PARA], const size_t &argc, napi_ref &callback); -void PaddingAsyncCallbackInfoIs( - const napi_env &env, AsyncCallbackInfoCancel *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); } // namespace NotificationNapi } // namespace OHOS diff --git a/kits/napi/include/common.h b/interfaces/kits/napi/ans/include/common.h similarity index 84% rename from kits/napi/include/common.h rename to interfaces/kits/napi/ans/include/common.h index cbe1d5392e2143d6190e7a1aabb2f1f60783b3d7..9b427c4d44ec13e053cbd7aa555e1ff4352f9918 100644 --- a/kits/napi/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -112,11 +112,13 @@ public: static void SetPromise(const napi_env &env, const napi_deferred &deferred, const napi_value &result); - static napi_value SetNotificationRequest( - const napi_env &env, const std::shared_ptr ¬ification, napi_value &result); + static napi_value JSParaError(const napi_env &env, const napi_ref &callback); + + static napi_value SetNotification( + const napi_env &env, OHOS::Notification::Notification *notification, napi_value &result); - static napi_value SetNotificationRequest2(const napi_env &env, - const std::shared_ptr &request, napi_value &result); + static napi_value SetNotificationRequest( + const napi_env &env, OHOS::Notification::NotificationRequest *request, napi_value &result); static napi_value SetNotificationSortingMap( const napi_env &env, const std::shared_ptr &sortingMap, napi_value &result); @@ -135,23 +137,22 @@ public: static napi_value SetNotificationLongTextContent( const napi_env &env, OHOS::Notification::NotificationLongTextContent *longTextContent, napi_value &result); - // static napi_value SetNotificationPictureContent( - // const napi_env &env, OHOS::Notification::NotificationPictureContent * pictureContent, napi_value &result); + static napi_value SetNotificationPictureContent( + const napi_env &env, OHOS::Notification::NotificationPictureContent *pictureContent, napi_value &result); - // static napi_value SetNotificationConversationalContent(const napi_env &env, - // OHOS::Notification::NotificationConversationalContent * conversationalContent, napi_value &result); + static napi_value SetNotificationConversationalContent(const napi_env &env, + OHOS::Notification::NotificationConversationalContent *conversationalContent, napi_value &result); static napi_value SetNotificationMultiLineContent( const napi_env &env, OHOS::Notification::NotificationMultiLineContent *multiLineContent, napi_value &result); - // static napi_value SetMessageUser( - // const napi_env &env, std::shared_ptr &messageUser, napi_value &result); + static napi_value SetMessageUser(const napi_env &env, const MessageUser &messageUser, napi_value &result); - // static napi_value SetConversationalMessage(const napi_env &env, - // std::shared_ptr &conversationalMessage, napi_value &result); + static napi_value SetConversationalMessage(const napi_env &env, + const std::shared_ptr &conversationalMessage, napi_value &result); static napi_value SetNotificationActionButton( - const napi_env &env, std::shared_ptr &actionButton, napi_value &result); + 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); diff --git a/kits/napi/include/constant.h b/interfaces/kits/napi/ans/include/constant.h similarity index 100% rename from kits/napi/include/constant.h rename to interfaces/kits/napi/ans/include/constant.h diff --git a/kits/napi/include/create_subscriber.h b/interfaces/kits/napi/ans/include/create_subscriber.h similarity index 67% rename from kits/napi/include/create_subscriber.h rename to interfaces/kits/napi/ans/include/create_subscriber.h index 0163fa8b0c67d7e9c89b3644c4720932905e1d12..a5f0055c48d5d36a868f23739610e4658da81243 100644 --- a/kits/napi/include/create_subscriber.h +++ b/interfaces/kits/napi/ans/include/create_subscriber.h @@ -24,18 +24,7 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -const int ON_MAX_PARA = 2; -const int OFF_MAX_PARA = 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"; - class SubscriberInstance; - struct AsyncCallbackInfoOn { napi_env env; napi_async_work asyncWork; @@ -44,29 +33,6 @@ struct AsyncCallbackInfoOn { std::string type; }; -struct AsyncCallbackInfoOff { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = 0; - SubscriberInstance *objectInfo; - std::string type; -}; - -struct CallbackInfo { - napi_env env; - napi_ref ref; -}; - -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; -}; - class SubscriberInstance : public NotificationSubscriber { public: SubscriberInstance(); @@ -111,6 +77,11 @@ private: 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_; @@ -120,34 +91,19 @@ private: CallbackInfo disturbModeCallbackInfo_; }; -napi_value SetSubscriberCallbackData( - const napi_env &env, const std::shared_ptr &request, napi_value &result); - -napi_value SetSubscriberCallbackData(const napi_env &env, - const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason, napi_value &result); - napi_value NotificationSubscriberInit(napi_env env, napi_value exports); napi_value On(napi_env env, napi_callback_info info); -napi_value ParseParametersByOn(const napi_env &env, const size_t &argc, const napi_value (&argv)[ON_MAX_PARA], - std::string &type, napi_ref &callback); - napi_value Off(napi_env env, napi_callback_info info); -napi_value ParseParametersByOff( - const napi_env &env, const size_t &argc, const napi_value (&argv)[OFF_MAX_PARA], std::string &type); - -napi_value SubscriberConstructor(napi_env env, napi_callback_info info); - napi_value CreateSubscriber(napi_env env, napi_callback_info info); bool CreateSubscriberInstanceRecord(SubscriberInstance **subscriber); -bool AddAsyncCallbackInfoOn(SubscriberInstance *subscriber, AsyncCallbackInfoOn *asynccallbackinfo); +bool AddAsyncCallbackInfo(SubscriberInstance *subscriber, AsyncCallbackInfoOn *asynccallbackinfo); -bool DelAsyncCallbackInfoOn(SubscriberInstance *subscriber, const std::string &type = ""); +bool DelAsyncCallbackInfo(SubscriberInstance *subscriber, const std::string &type = ""); bool HasNotificationSubscriber(SubscriberInstance *subscriber); diff --git a/kits/napi/include/get_active.h b/interfaces/kits/napi/ans/include/get_active.h similarity index 59% rename from kits/napi/include/get_active.h rename to interfaces/kits/napi/ans/include/get_active.h index d1ae7ad279989268ff76e9d3c1e368b5c5c8bd67..011c3eb40769ca34cbd9d702667cc34a372914d8 100644 --- a/kits/napi/include/get_active.h +++ b/interfaces/kits/napi/ans/include/get_active.h @@ -22,29 +22,9 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -const int ALL_ACTIVE_MAX_PARA = 2; -const int ACTIVE_OR_NUMS_MAX_PARA = 1; - -struct AsyncCallbackInfoActive { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - std::vector strValue; - bool isCallback = false; - napi_value result = nullptr; - int errorCode = 0; -}; - 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 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 ParseParameters( - const napi_env &env, const napi_value (&argv)[ACTIVE_OR_NUMS_MAX_PARA], const size_t &argc, napi_ref &callback); -void PaddingAsyncCallbackInfoIs( - const napi_env &env, AsyncCallbackInfoActive *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); } // namespace NotificationNapi } // namespace OHOS diff --git a/kits/napi/include/init.h b/interfaces/kits/napi/ans/include/init.h similarity index 100% rename from kits/napi/include/init.h rename to interfaces/kits/napi/ans/include/init.h diff --git a/interfaces/kits/napi/ans/include/publish.h b/interfaces/kits/napi/ans/include/publish.h new file mode 100644 index 0000000000000000000000000000000000000000..a288687b928cf2cbc8282ac5bd102810abca23da --- /dev/null +++ b/interfaces/kits/napi/ans/include/publish.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_PUBLISH_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H + +#include +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +napi_value Publish(napi_env env, napi_callback_info info); + +} // namespace NotificationNapi +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H \ No newline at end of file diff --git a/kits/napi/include/remove.h b/interfaces/kits/napi/ans/include/remove.h similarity index 59% rename from kits/napi/include/remove.h rename to interfaces/kits/napi/ans/include/remove.h index bbc06815443cd0f29817575241cf7679fbe31fd7..2e03ac5acd1be8d3ab223debda04c0dcb450c82b 100644 --- a/kits/napi/include/remove.h +++ b/interfaces/kits/napi/ans/include/remove.h @@ -22,32 +22,10 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -const int REMOVE_OR_BUNDLE_MAX_PARA = 2; -const int REMOVE_ALL_MAX_PARA = 1; - -struct AsyncCallbackInfoRemove { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - std::string strValue; - bool isCallback = false; - int errorCode = 0; -}; - napi_value Remove(napi_env env, napi_callback_info info); napi_value RemoveAsBundle(napi_env env, napi_callback_info info); napi_value RemoveAll(napi_env env, napi_callback_info info); -napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[REMOVE_OR_BUNDLE_MAX_PARA], const size_t &argc, - std::string &strValue, napi_ref &callback); - -napi_value ParseParametersByRemoveAll( - const napi_env &env, const napi_value (&argv)[REMOVE_ALL_MAX_PARA], const size_t &argc, napi_ref &callback); - -void PaddingAsyncCallbackInfoIs( - const napi_env &env, AsyncCallbackInfoRemove *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); - } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMOVE_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 new file mode 100644 index 0000000000000000000000000000000000000000..1f851d501b920daf942aba25d453ce55fdb5c300 --- /dev/null +++ b/interfaces/kits/napi/ans/include/slot.h @@ -0,0 +1,33 @@ +/* + * 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_SLOT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SLOT_H + +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +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 GetSlot(napi_env env, napi_callback_info info); +napi_value GetSlots(napi_env env, napi_callback_info info); +napi_value RemoveSlot(napi_env env, napi_callback_info info); + +} // namespace NotificationNapi +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SLOT_H \ No newline at end of file diff --git a/kits/napi/include/subscribe.h b/interfaces/kits/napi/ans/include/subscribe.h similarity index 60% rename from kits/napi/include/subscribe.h rename to interfaces/kits/napi/ans/include/subscribe.h index af87eed8a9298c4892d787ca1070c7ac927b3277..ad57a9ba182460286479f353c06a8f468d9309d4 100644 --- a/kits/napi/include/subscribe.h +++ b/interfaces/kits/napi/ans/include/subscribe.h @@ -22,25 +22,6 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -const int SUBSRIBE_MAX_PARA = 3; - -struct AsyncCallbackInfoSubscribe { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = 0; - napi_deferred deferred; - SubscriberInstance *objectInfo = nullptr; - NotificationSubscriberInfo subscriberInfo; - bool isCallback = false; - int errorCode = 0; -}; - -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); - -void PaddingAsyncCallbackInfoIs( - const napi_env &env, AsyncCallbackInfoSubscribe *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); - napi_value Subscribe(napi_env env, napi_callback_info info); } // namespace NotificationNapi diff --git a/kits/napi/include/unsubscribe.h b/interfaces/kits/napi/ans/include/unsubscribe.h similarity index 63% rename from kits/napi/include/unsubscribe.h rename to interfaces/kits/napi/ans/include/unsubscribe.h index 3872a276828fa3fea903376d36dab0036bfa2644..ac6c6d8c47f3d2026829c8c6ec4cd13d48381568 100644 --- a/kits/napi/include/unsubscribe.h +++ b/interfaces/kits/napi/ans/include/unsubscribe.h @@ -23,24 +23,6 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -const int UNSUBSCRIBE_MAX_PARA = 2; - -struct AsyncCallbackInfoUnsubscribe { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = 0; - napi_deferred deferred; - SubscriberInstance *objectInfo = nullptr; - bool isCallback = false; - int errorCode = 0; -}; - -napi_value ParseParameters(const napi_env &env, const size_t &argc, const napi_value (&argv)[UNSUBSCRIBE_MAX_PARA], - SubscriberInstance *&objectInfo, napi_ref &callback); - -void PaddingAsyncCallbackInfoIs(const napi_env &env, const size_t &argc, - AsyncCallbackInfoUnsubscribe *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); - napi_value Unsubscribe(napi_env env, napi_callback_info info); } // namespace NotificationNapi diff --git a/kits/napi/src/cancel.cpp b/interfaces/kits/napi/ans/src/cancel.cpp similarity index 91% rename from kits/napi/src/cancel.cpp rename to interfaces/kits/napi/ans/src/cancel.cpp index e74881339b4f3f599edc96ab9ea8f84968036df0..24fb596751343da61e6a91e47214b4a5204a523c 100644 --- a/kits/napi/src/cancel.cpp +++ b/interfaces/kits/napi/ans/src/cancel.cpp @@ -17,11 +17,35 @@ namespace OHOS { namespace NotificationNapi { + +const int CANCEL_MAX_PARA = 3; +const int CANCEL_ALL_MAX_PARA = 1; + +struct AsyncCallbackInfoCancel { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + std::string label; + int id; + bool hasLabel = false; + bool isCallback = false; + int errorCode = 0; +}; + +struct paraInfoCancel { + int id = 0; + std::string label; + bool hasLabel = false; +}; + napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[CANCEL_MAX_PARA], const size_t &argc, paraInfoCancel &info, napi_ref &callback) { ANS_LOGI("ParseParameters start"); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_valuetype valuetype; // argv[0]: id: number NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); @@ -93,17 +117,16 @@ napi_value Cancel(napi_env env, napi_callback_info info) napi_value argv[CANCEL_MAX_PARA]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_ref callback = nullptr; paraInfoCancel paraInfo; if (ParseParameters(env, argv, argc, paraInfo, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } ANS_LOGI("Cancel id = %{public}d", paraInfo.id); ANS_LOGI("Cancel label = %{public}s", paraInfo.label.c_str()); - AsyncCallbackInfoCancel *asynccallbackinfo = new AsyncCallbackInfoCancel{ + AsyncCallbackInfoCancel *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoCancel{ .env = env, .asyncWork = nullptr, .id = paraInfo.id, .label = paraInfo.label, .hasLabel = paraInfo.hasLabel}; napi_value promise = 0; @@ -120,10 +143,10 @@ napi_value Cancel(napi_env env, napi_callback_info info) AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; if (asynccallbackinfo->hasLabel) { - asynccallbackinfo->errorCode = NotificationHelper::CancelNotification(asynccallbackinfo->id); - } else { asynccallbackinfo->errorCode = NotificationHelper::CancelNotification(asynccallbackinfo->label, asynccallbackinfo->id); + } else { + asynccallbackinfo->errorCode = NotificationHelper::CancelNotification(asynccallbackinfo->id); } }, [](napi_env env, napi_status status, void *data) { @@ -164,14 +187,14 @@ napi_value CancelAll(napi_env env, napi_callback_info info) 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_ASSERT(env, argc >= 0, "Wrong number of arguments"); napi_ref callback = nullptr; if (ParseParametersByAll(env, argv, argc, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } - AsyncCallbackInfoCancel *asynccallbackinfo = new AsyncCallbackInfoCancel{.env = env, .asyncWork = nullptr}; + AsyncCallbackInfoCancel *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoCancel{.env = env, .asyncWork = nullptr}; napi_value promise = 0; PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); diff --git a/kits/napi/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp similarity index 74% rename from kits/napi/src/common.cpp rename to interfaces/kits/napi/ans/src/common.cpp index c1c12423408f4f88de7c96a61f7a630033a891df..19ae25e69f1537102383bc689d7ff10362902628 100644 --- a/kits/napi/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -14,6 +14,7 @@ */ #include "common.h" +#include "napi_common.h" #include "notification_long_text_content.h" #include "notification_multiline_content.h" #include "publish.h" @@ -44,8 +45,8 @@ static napi_value GetNotificationAutoDeletedTime( // 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 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); static napi_value GetNotificationColorEnabled( const napi_env &env, const napi_value &value, NotificationRequest &request); @@ -63,10 +64,8 @@ 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 GetNotificationIsFloatingIcon( -// 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); @@ -81,10 +80,15 @@ static napi_value GetNotificationBasicContent( const napi_env &env, const napi_value &result, NotificationRequest &request); static napi_value GetNotificationLongTextContent( const napi_env &env, const napi_value &result, NotificationRequest &request); +static napi_value GetNotificationPictureContent( + const napi_env &env, const napi_value &result, NotificationRequest &request); +static napi_value GetNotificationConversationalContent( + const napi_env &env, const napi_value &result, NotificationRequest &request); static napi_value GetNotificationMultiLineContent( const napi_env &env, const napi_value &result, NotificationRequest &request); static napi_value GetNotificationMultiLineContentLines(const napi_env &env, const napi_value &result, std::shared_ptr &multiLineContent); +static napi_value GetNotificationExtraInfo(const napi_env &env, const napi_value &value, NotificationRequest &request); Common::Common() {} @@ -152,225 +156,45 @@ void Common::SetPromise(const napi_env &env, const napi_deferred &deferred, cons ANS_LOGI("end"); } -napi_value Common::SetNotificationRequest( - const napi_env &env, const std::shared_ptr ¬ification, napi_value &result) +napi_value Common::JSParaError(const napi_env &env, const napi_ref &callback) { - ANS_LOGI("SetNotificationRequest start"); - - napi_value value; - NotificationRequest request = notification->GetNotificationRequest(); - - // content?NotificationContent - std::shared_ptr content = request.GetContent(); - if (content) { - napi_value contentResult; - napi_create_object(env, &contentResult); - if (!SetNotificationContent(env, content, contentResult)) { - ANS_LOGE("SetNotificationContent call failed"); - return NapiGetboolean(env, false); - } - napi_set_named_property(env, result, "content", contentResult); + if (callback) { + return Common::NapiGetNull(env); } else { - ANS_LOGE("content is nullptr"); + napi_value promise = 0; + napi_deferred deferred = nullptr; + napi_create_promise(env, &deferred, &promise); + SetPromise(env, deferred, Common::NapiGetNull(env)); + return promise; } +} - // id:number - napi_create_int32(env, request.GetNotificationId(), &value); - ANS_LOGE("SetNotificationContent get id is: %{public}d", request.GetNotificationId()); - napi_set_named_property(env, result, "id", value); - ANS_LOGE("SetNotificationContent id is: %{public}d", request.GetNotificationId()); - // slotType?: SlotType - enum SlotType outType; - if (!SlotTypeCToJS(request.GetSlotType(), outType)) { +napi_value Common::SetNotification( + const napi_env &env, OHOS::Notification::Notification *notification, napi_value &result) +{ + ANS_LOGI("SetNotification start"); + + if (notification == nullptr) { + ANS_LOGE("notification is nullptr"); + return NapiGetboolean(env, false); + } + napi_value value; + NotificationRequest request = notification->GetNotificationRequest(); + if (!SetNotificationRequest(env, &request, result)) { return NapiGetboolean(env, false); } - napi_create_int32(env, outType, &value); - napi_set_named_property(env, result, "slotType", value); - - // isOngoing?: boolean - napi_get_boolean(env, request.IsInProgress(), &value); - napi_set_named_property(env, result, "isOngoing", value); - - // isUnremovable?: boolean - 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); // hashCode?: string napi_create_string_utf8(env, notification->GetKey().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "hashCode", value); - // deliveryTime?: number - napi_create_int64(env, request.GetDeliveryTime(), &value); - napi_set_named_property(env, result, "deliveryTime", value); - - // tapDismissed?: boolean - napi_get_boolean(env, request.IsTapDismissed(), &value); - napi_set_named_property(env, result, "tapDismissed", value); - - // autoDeletedTime?: number - napi_create_int64(env, request.GetAutoDeletedTime(), &value); - napi_set_named_property(env, result, "autoDeletedTime", value); - - // wantAgent?: WantAgent - std::shared_ptr agent = request.GetWantAgent(); - if (agent) { - napi_value wantAgent; - wantAgent = CreateWantAgentByJS(env, agent); - napi_set_named_property(env, result, "wantAgent", wantAgent); - } - // extraInfo ?: {[key:string] : any}; //do - - // // 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) { - napi_value wantAgent; - wantAgent = CreateWantAgentByJS(env, removalAgent); - napi_set_named_property(env, result, "removalWantAgent", wantAgent); - } - - // maxScreenWantAgent ? WantAgent - std::shared_ptr maxScreenAgent = request.GetMaxScreenWantAgent(); - if (maxScreenAgent) { - napi_value wantAgent; - wantAgent = CreateWantAgentByJS(env, maxScreenAgent); - napi_set_named_property(env, result, "maxScreenWantAgent", wantAgent); - } - - // // classification ?: string - // napi_create_string_utf8(env, request.GetClassification().c_str(), NAPI_AUTO_LENGTH, &value); - // napi_set_named_property(env, result, "classification", value); - - // color ?: number - napi_create_int32(env, request.GetColor(), &value); - napi_set_named_property(env, result, "color", value); - - // colorEnabled ?: boolean - napi_get_boolean(env, request.IsColorEnabled(), &value); - napi_set_named_property(env, result, "colorEnabled", value); - - // isAlertOnce ?: boolean - napi_get_boolean(env, request.IsAlertOneTime(), &value); - napi_set_named_property(env, result, "isAlertOnce", value); - - // isStopwatch ?: boolean - napi_get_boolean(env, request.IsShowStopwatch(), &value); - napi_set_named_property(env, result, "isStopwatch", value); - - // isCountDown ?: boolean - napi_get_boolean(env, request.IsCountdownTimer(), &value); - napi_set_named_property(env, result, "isCountDown", value); - - // showCreateTime ?: boolean; do request - // napi_get_boolean(env, request.IsCountdownTimer(), &value); - // napi_set_named_property(env, result, "showCreateTime", 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 - - // // 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()) { - // 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); - - // badgeIconStyle ?: number - int badgeIconStyle = (int)request.GetBadgeIconStyle(); - 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); - - // actionButtons?: Array - napi_value arr; - int count = 0; - napi_create_array(env, &arr); - for (auto vec : request.GetActionButtons()) { - if (vec) { - napi_value actionButtonResult; - napi_create_object(env, &actionButtonResult); - if (SetNotificationActionButton(env, vec, actionButtonResult)) { - napi_set_element(env, arr, count, actionButtonResult); - count++; - } - } - } - napi_set_named_property(env, result, "actionButtons", arr); - - // smallIcon ?: image.PixelMap; do - // largeIcon ?: image.PixelMap; do + // isFloatingIcon ?: boolean; + napi_get_boolean(env, notification->IsFloatingIcon(), &value); + napi_set_named_property(env, result, "isFloatingIcon", value); // readonly creatorBundleName?: string napi_create_string_utf8(env, notification->GetCreateBundle().c_str(), NAPI_AUTO_LENGTH, &value); @@ -380,23 +204,27 @@ napi_value Common::SetNotificationRequest( napi_create_int32(env, notification->GetUid(), &value); napi_set_named_property(env, result, "creatorUid", value); - // readonly creatorPid?: number //do notification - // napi_create_int32(env, request.GetCreatorPid(), &value); - // napi_set_named_property(env, result, "creatorPid", value); + // readonly creatorPid?: number + napi_create_int32(env, notification->GetPid(), &value); + napi_set_named_property(env, result, "creatorPid", value); return NapiGetboolean(env, true); } -napi_value Common::SetNotificationRequest2( - const napi_env &env, const std::shared_ptr &request, napi_value &result) +napi_value Common::SetNotificationRequest( + const napi_env &env, OHOS::Notification::NotificationRequest *request, napi_value &result) { - ANS_LOGI("SetNotificationRequest2 start"); + ANS_LOGI("SetNotificationRequest start"); napi_value value; - // content?NotificationContent - std::shared_ptr content = request->GetContent(); + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return NapiGetboolean(env, false); + } + // content: NotificationContent + std::shared_ptr content = request->GetContent(); if (content) { napi_value contentResult; napi_create_object(env, &contentResult); @@ -407,13 +235,12 @@ napi_value Common::SetNotificationRequest2( napi_set_named_property(env, result, "content", contentResult); } else { ANS_LOGE("content is nullptr"); + return NapiGetboolean(env, false); } - // id:number + // id?: number napi_create_int32(env, request->GetNotificationId(), &value); - ANS_LOGE("SetNotificationContent get id is: %{public}d", request->GetNotificationId()); napi_set_named_property(env, result, "id", value); - ANS_LOGE("SetNotificationContent id is: %{public}d", request->GetNotificationId()); // slotType?: SlotType enum SlotType outType; @@ -435,10 +262,6 @@ napi_value Common::SetNotificationRequest2( // napi_create_int64(env, request->GetCreateTime(), &value); // napi_set_named_property(env, result, "createTime", value); - // hashCode?: string - napi_create_string_utf8(env, request->GetNotificationHashCode().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "hashCode", value); - // deliveryTime?: number napi_create_int64(env, request->GetDeliveryTime(), &value); napi_set_named_property(env, result, "deliveryTime", value); @@ -457,9 +280,17 @@ napi_value Common::SetNotificationRequest2( napi_value wantAgent; wantAgent = CreateWantAgentByJS(env, agent); napi_set_named_property(env, result, "wantAgent", wantAgent); + } else { + napi_set_named_property(env, result, "wantAgent", NapiGetNull(env)); } - // extraInfo ?: {[key:string] : any}; //do + // extraInfo ?: {[key:string] : any} + std::shared_ptr additionalData = request->GetAdditionalData(); + if (additionalData) { + napi_value extraInfo; + extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); + napi_set_named_property(env, result, "extraInfo", extraInfo); + } // // settingsText ?: string // napi_create_string_utf8(env, request->GetSettingsText().c_str(), NAPI_AUTO_LENGTH, &value); @@ -482,12 +313,14 @@ napi_value Common::SetNotificationRequest2( // napi_get_boolean(env, request->IsGroupOverview(), &value); // napi_set_named_property(env, result, "groupOverview", value); - // removalWantAgent ? WantAgent + // removalWantAgent ?: WantAgent std::shared_ptr removalAgent = request->GetRemovalWantAgent(); if (removalAgent) { napi_value wantAgent; wantAgent = CreateWantAgentByJS(env, removalAgent); napi_set_named_property(env, result, "removalWantAgent", wantAgent); + } else { + napi_set_named_property(env, result, "removalWantAgent", NapiGetNull(env)); } // maxScreenWantAgent ? WantAgent @@ -496,11 +329,13 @@ napi_value Common::SetNotificationRequest2( napi_value wantAgent; wantAgent = CreateWantAgentByJS(env, maxScreenAgent); napi_set_named_property(env, result, "maxScreenWantAgent", wantAgent); + } else { + napi_set_named_property(env, result, "maxScreenWantAgent", NapiGetNull(env)); } - // // classification ?: string - // napi_create_string_utf8(env, request->GetClassification().c_str(), NAPI_AUTO_LENGTH, &value); - // napi_set_named_property(env, result, "classification", value); + // classification ?: string + napi_create_string_utf8(env, request->GetClassification().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "classification", value); // color ?: number napi_create_int32(env, request->GetColor(), &value); @@ -522,10 +357,6 @@ napi_value Common::SetNotificationRequest2( napi_get_boolean(env, request->IsCountdownTimer(), &value); napi_set_named_property(env, result, "isCountDown", value); - // showCreateTime ?: boolean; do request - // napi_get_boolean(env, request->IsCountdownTimer(), &value); - // napi_set_named_property(env, result, "showCreateTime", value); - // // visibleness ?: number // int visibleness = (int)request->GetVisibleness(); // napi_create_int32(env, visibleness, &value); @@ -548,20 +379,33 @@ napi_value Common::SetNotificationRequest2( napi_set_named_property(env, result, "statusBarText", value); // isFloatingIcon ?: boolean; do notification + 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); + // 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); @@ -606,9 +450,9 @@ napi_value Common::SetNotificationRequest2( napi_create_int32(env, request->GetCreatorUid(), &value); napi_set_named_property(env, result, "creatorUid", value); - // readonly creatorPid?: number //do notification - // napi_create_int32(env, request->GetCreatorPid(), &value); - // napi_set_named_property(env, result, "creatorPid", value); + // readonly creatorPid?: number + napi_create_int32(env, request->GetCreatorPid(), &value); + napi_set_named_property(env, result, "creatorPid", value); return NapiGetboolean(env, true); } @@ -722,14 +566,6 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl napi_create_int32(env, outType, &value); napi_set_named_property(env, result, "type", value); - // // slotId: string - // napi_create_string_utf8(env, slot.GetId().c_str(), NAPI_AUTO_LENGTH, &value); - // napi_set_named_property(env, result, "slotId", value); - - // // slotName: string - // napi_create_string_utf8(env, slot.GetName().c_str(), NAPI_AUTO_LENGTH, &value); - // napi_set_named_property(env, result, "slotName", value); - // level?: number napi_create_int32(env, slot.GetLevel(), &value); napi_set_named_property(env, result, "level", value); @@ -767,10 +603,6 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl napi_create_int32(env, slot.GetLedLightColor(), &value); napi_set_named_property(env, result, "lightColor", value); - // slotGroupId?: string - // napi_create_string_utf8(env, slot.GetSlotGroup().c_str(), NAPI_AUTO_LENGTH, &value); - // napi_set_named_property(env, result, "slotGroupId", value); - // vibrationValues?: Array napi_value arr; napi_create_array(env, &arr); @@ -784,6 +616,7 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl return NapiGetboolean(env, true); } + napi_value Common::SetNotificationContent( const napi_env &env, const std::shared_ptr &content, napi_value &result) { @@ -796,93 +629,73 @@ napi_value Common::SetNotificationContent( napi_value value; // contentType: ContentType; NotificationContent::Type type = content->GetContentType(); - napi_create_int32(env, (int32_t)type, &value); - napi_set_named_property(env, result, "contentType", value); - ContentType outType; if (!ContentTypeCToJS(type, outType)) { return NapiGetboolean(env, false); } + napi_create_int32(env, (int32_t)outType, &value); + napi_set_named_property(env, result, "contentType", value); + + std::shared_ptr basicContent = content->GetNotificationContent(); + if (basicContent == nullptr) { + ANS_LOGI("content is null"); + return NapiGetboolean(env, false); + } if (outType == ContentType::NOTIFICATION_CONTENT_BASIC_TEXT) { // normal?: NotificationBasicContent - std::shared_ptr basicContent = content->GetNotificationContent(); - if (basicContent == nullptr) { - ANS_LOGI("basicContent is null"); - napi_set_named_property(env, result, "normal", NapiGetNull(env)); + napi_value basicContentResult; + napi_create_object(env, &basicContentResult); + if (SetNotificationBasicContent(env, basicContent.get(), basicContentResult)) { + napi_set_named_property(env, result, "normal", basicContentResult); } else { - napi_value basicContentResult; - napi_create_object(env, &basicContentResult); - if (SetNotificationBasicContent(env, basicContent.get(), basicContentResult)) { - napi_set_named_property(env, result, "normal", basicContentResult); - } else { - napi_set_named_property(env, result, "normal", NapiGetNull(env)); - } + return NapiGetboolean(env, false); } + } else if (outType == ContentType::NOTIFICATION_CONTENT_LONG_TEXT) { // longText?: NotificationLongTextContent OHOS::Notification::NotificationLongTextContent *longTextContent = - static_cast(content->GetNotificationContent().get()); - if (longTextContent == nullptr) { - ANS_LOGI("longTextContent is null"); - napi_set_named_property(env, result, "longText", NapiGetNull(env)); + static_cast(basicContent.get()); + napi_value longTextContentResult; + napi_create_object(env, &longTextContentResult); + if (SetNotificationLongTextContent(env, longTextContent, longTextContentResult)) { + napi_set_named_property(env, result, "longText", longTextContentResult); } else { - napi_value longTextContentResult; - napi_create_object(env, &longTextContentResult); - if (SetNotificationLongTextContent(env, longTextContent, longTextContentResult)) { - napi_set_named_property(env, result, "longText", longTextContentResult); - } else { - napi_set_named_property(env, result, "longText", NapiGetNull(env)); - } + return NapiGetboolean(env, false); } + } else if (outType == ContentType::NOTIFICATION_CONTENT_PICTURE) { // picture?: NotificationPictureContent - // OHOS::Notification::NotificationPictureContent * pictureContent = - // static_cast(content->GetNotificationContent().get()); - // if (pictureContent == nullptr) { - // ANS_LOGI("pictureContent is null"); - // napi_set_named_property(env, result, "picture", NapiGetNull(env)); - // } else { - // napi_value pictureContentResult; - // napi_create_object(env, &pictureContentResult); - // if (SetNotificationPictureContent(env, pictureContent, pictureContentResult)) { - // napi_set_named_property(env, result, "picture", pictureContentResult); - // } else { - // napi_set_named_property(env, result, "picture", NapiGetNull(env)); - // } - // } + OHOS::Notification::NotificationPictureContent *pictureContent = + static_cast(basicContent.get()); + napi_value pictureContentResult; + napi_create_object(env, &pictureContentResult); + if (SetNotificationPictureContent(env, pictureContent, pictureContentResult)) { + napi_set_named_property(env, result, "picture", pictureContentResult); + } else { + return NapiGetboolean(env, false); + } } else if (outType == ContentType::NOTIFICATION_CONTENT_CONVERSATION) { // conversational?: NotificationConversationalContent - // OHOS::Notification::NotificationConversationalContent * conversationalContent = - // static_cast(content->GetNotificationContent().get()); - // if (conversationalContent == nullptr) { - // ANS_LOGI("conversationalContent is null"); - // napi_set_named_property(env, result, "conversational", NapiGetNull(env)); - // } else { - // napi_value conversationalContentResult; - // napi_create_object(env, &conversationalContentResult); - // if (SetNotificationConversationalContent(env, conversationalContent, conversationalContentResult)) { - // napi_set_named_property(env, result, "conversational", conversationalContentResult); - // } else { - // napi_set_named_property(env, result, "conversational", NapiGetNull(env)); - // } - // } + OHOS::Notification::NotificationConversationalContent *conversationalContent = + static_cast(basicContent.get()); + napi_value conversationalContentResult; + napi_create_object(env, &conversationalContentResult); + if (SetNotificationConversationalContent(env, conversationalContent, conversationalContentResult)) { + napi_set_named_property(env, result, "conversational", conversationalContentResult); + } else { + return NapiGetboolean(env, false); + } } else if (outType == ContentType::NOTIFICATION_CONTENT_MULTILINE) { // multiLine?: NotificationMultiLineContent OHOS::Notification::NotificationMultiLineContent *multiLineContent = - static_cast(content->GetNotificationContent().get()); - if (multiLineContent == nullptr) { - ANS_LOGI("multiLineContent is null"); - napi_set_named_property(env, result, "multiLine", NapiGetNull(env)); + static_cast(basicContent.get()); + napi_value multiLineContentResult; + napi_create_object(env, &multiLineContentResult); + if (SetNotificationMultiLineContent(env, multiLineContent, multiLineContentResult)) { + napi_set_named_property(env, result, "multiLine", multiLineContentResult); } else { - napi_value multiLineContentResult; - napi_create_object(env, &multiLineContentResult); - if (SetNotificationMultiLineContent(env, multiLineContent, multiLineContentResult)) { - napi_set_named_property(env, result, "multiLine", multiLineContentResult); - } else { - napi_set_named_property(env, result, "multiLine", NapiGetNull(env)); - } + return NapiGetboolean(env, false); } } else { ANS_LOGE("ContentType is does not exist"); @@ -948,89 +761,89 @@ napi_value Common::SetNotificationLongTextContent( return NapiGetboolean(env, true); } -// napi_value Common::SetNotificationPictureContent( -// const napi_env &env, OHOS::Notification::NotificationPictureContent *pictureContent, napi_value &result) -// { -// ANS_LOGI("SetNotificationPictureContent start"); -// if (pictureContent == nullptr) { -// ANS_LOGE("pictureContent is null"); -// return NapiGetboolean(env, false); -// } +napi_value Common::SetNotificationPictureContent( + const napi_env &env, OHOS::Notification::NotificationPictureContent *pictureContent, napi_value &result) +{ + ANS_LOGI("SetNotificationPictureContent start"); + if (pictureContent == nullptr) { + ANS_LOGE("pictureContent is null"); + return NapiGetboolean(env, false); + } -// if (!SetNotificationBasicContent(env, pictureContent, result)) { -// ANS_LOGE("SetNotificationBasicContent call failed"); -// return NapiGetboolean(env, false); -// } + if (!SetNotificationBasicContent(env, pictureContent, result)) { + ANS_LOGE("SetNotificationBasicContent call failed"); + return NapiGetboolean(env, false); + } -// napi_value value; + napi_value value; -// // pictureId: number //c++ no do + // 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); + // briefText: string + napi_create_string_utf8(env, pictureContent->GetBriefText().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "briefText", value); -// // expandedTitle: string -// napi_create_string_utf8(env, pictureContent->GetExpandedTitle().c_str(), NAPI_AUTO_LENGTH, &value); -// napi_set_named_property(env, result, "expandedTitle", value); + // expandedTitle: string + 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 + // bigPicture: image.PixelMap //do -// return NapiGetboolean(env, true); -// } + return NapiGetboolean(env, true); +} -// napi_value Common::SetNotificationConversationalContent( -// const napi_env &env, OHOS::Notification::NotificationConversationalContent *conversationalContent, napi_value -// &result) -// { -// ANS_LOGI("SetNotificationConversationalContent start"); -// if (conversationalContent == nullptr) { -// ANS_LOGE("conversationalContent is null"); -// return NapiGetboolean(env, false); -// } +napi_value Common::SetNotificationConversationalContent(const napi_env &env, + OHOS::Notification::NotificationConversationalContent *conversationalContent, napi_value &result) +{ + ANS_LOGI("SetNotificationConversationalContent start"); + if (conversationalContent == nullptr) { + ANS_LOGE("conversationalContent is null"); + return NapiGetboolean(env, false); + } -// if (!SetNotificationBasicContent(env, conversationalContent, result)) { -// ANS_LOGE("SetNotificationBasicContent call failed"); -// return NapiGetboolean(env, false); -// } + if (!SetNotificationBasicContent(env, conversationalContent, result)) { + ANS_LOGE("SetNotificationBasicContent call failed"); + return NapiGetboolean(env, false); + } -// napi_value value; -// // conversationTitle: string -// napi_create_string_utf8(env, conversationalContent->GetConversationTitle().c_str(), NAPI_AUTO_LENGTH, &value); -// napi_set_named_property(env, result, "conversationTitle", value); - -// // conversationGroup: boolean -// napi_get_boolean(env, conversationalContent->IsConversationGroup(), &value); -// napi_set_named_property(env, result, "conversationGroup", value); - -// // messages: Array -// napi_value arr; -// int count = 0; -// napi_create_array(env, &arr); -// std::vector> messages = -// conversationalContent->GetAllConversationalMessages(); -// for (auto vec : messages) { -// if (vec) { -// napi_value conversationalMessageResult; -// napi_create_object(env, &conversationalMessageResult); -// if (SetConversationalMessage(env, vec, conversationalMessageResult)) { -// napi_set_element(env, arr, count, conversationalMessageResult); -// count++; -// } -// } -// } -// napi_set_named_property(env, result, "messages", arr); + napi_value value; + // conversationTitle: string + napi_create_string_utf8(env, conversationalContent->GetConversationTitle().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "conversationTitle", value); -// // user: MessageUser -// napi_value messageUserResult; -// napi_create_object(env, &messageUserResult); -// if (!SetMessageUser(env, conversationalContent->GetMessageUser(), messageUserResult)) { -// messageUserResult = NapiGetNull(); -// } -// napi_set_named_property(env, result, "user", messageUserResult); + // conversationGroup: boolean + napi_get_boolean(env, conversationalContent->IsConversationGroup(), &value); + napi_set_named_property(env, result, "conversationGroup", value); -// return NapiGetboolean(env, true); -// } + // messages: Array + napi_value arr; + int count = 0; + napi_create_array(env, &arr); + std::vector> messages = + conversationalContent->GetAllConversationalMessages(); + for (auto vec : messages) { + if (!vec) { + continue; + } + napi_value conversationalMessageResult; + napi_create_object(env, &conversationalMessageResult); + if (SetConversationalMessage(env, vec, conversationalMessageResult)) { + napi_set_element(env, arr, count, conversationalMessageResult); + count++; + } + } + napi_set_named_property(env, result, "messages", arr); + + // user: MessageUser + napi_value messageUserResult; + napi_create_object(env, &messageUserResult); + if (!SetMessageUser(env, conversationalContent->GetMessageUser(), messageUserResult)) { + messageUserResult = NapiGetNull(env); + } + napi_set_named_property(env, result, "user", messageUserResult); + + return NapiGetboolean(env, true); +} napi_value Common::SetNotificationMultiLineContent( const napi_env &env, OHOS::Notification::NotificationMultiLineContent *multiLineContent, napi_value &result) @@ -1069,81 +882,75 @@ napi_value Common::SetNotificationMultiLineContent( return NapiGetboolean(env, true); } -// napi_value Common::SetMessageUser(const napi_env &env, std::shared_ptr &messageUser, napi_value -// &result) -// { -// ANS_LOGI("SetMessageUser start"); -// if (messageUser == nullptr) { -// ANS_LOGE("SetMessageUser is null"); -// return NapiGetboolean(env, false); -// } +napi_value Common::SetMessageUser(const napi_env &env, const MessageUser &messageUser, napi_value &result) +{ + ANS_LOGI("SetMessageUser start"); -// napi_value value; -// // name: string -// napi_create_string_utf8(env, messageUser->GetName().c_str(), NAPI_AUTO_LENGTH, &value); -// napi_set_named_property(env, result, "name", value); + napi_value value; + // name: string + 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 + // pixelMap: image.PixelMap //do -// // uri: string -// napi_create_string_utf8(env, pictureContent->GetUri().ToString().c_str(), NAPI_AUTO_LENGTH, &value); -// napi_set_named_property(env, result, "uri", value); + // uri: string + napi_create_string_utf8(env, messageUser.GetUri().ToString().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "uri", value); -// // important: boolean -// napi_get_boolean(env, pictureContent->IsUserImportant(), &value); -// napi_set_named_property(env, result, "important", value); + // important: boolean + napi_get_boolean(env, messageUser.IsUserImportant(), &value); + napi_set_named_property(env, result, "important", value); -// // machine: boolean -// napi_get_boolean(env, pictureContent->IsMachine(), &value); -// napi_set_named_property(env, result, "machine", value); + // machine: boolean + napi_get_boolean(env, messageUser.IsMachine(), &value); + napi_set_named_property(env, result, "machine", value); -// // key: string -// napi_create_string_utf8(env, pictureContent->GetKey().c_str(), NAPI_AUTO_LENGTH, &value); -// napi_set_named_property(env, result, "key", value); + // key: string + napi_create_string_utf8(env, messageUser.GetKey().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "key", value); -// return NapiGetboolean(env, true); -// } + return NapiGetboolean(env, true); +} -// napi_value Common::SetConversationalMessage( -// const napi_env &env, std::shared_ptr &conversationalMessage, napi_value -// &result) -// { -// ANS_LOGI("SetConversationalMessage start"); -// if (conversationalMessage == nullptr) { -// ANS_LOGE("SetConversationalMessage is null"); -// return NapiGetboolean(env, false); -// } +napi_value Common::SetConversationalMessage(const napi_env &env, + const std::shared_ptr &conversationalMessage, napi_value &result) +{ + ANS_LOGI("SetConversationalMessage start"); + if (conversationalMessage == nullptr) { + ANS_LOGE("SetConversationalMessage is null"); + return NapiGetboolean(env, false); + } -// napi_value value; -// // text: string -// napi_create_string_utf8(env, conversationalMessage->GetText().c_str(), NAPI_AUTO_LENGTH, &value); -// napi_set_named_property(env, result, "text", value); + napi_value value; + // text: string + napi_create_string_utf8(env, conversationalMessage->GetText().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "text", value); -// // timestamp: number; -// napi_create_int64(env, conversationalMessage->GetArrivedTime(), &value); -// napi_set_named_property(env, result, "timestamp", value); + // timestamp: number; + napi_create_int64(env, conversationalMessage->GetArrivedTime(), &value); + napi_set_named_property(env, result, "timestamp", value); -// // mimeType: string; -// napi_create_string_utf8(env, conversationalMessage->GetMimeType().c_str(), NAPI_AUTO_LENGTH, &value); -// napi_set_named_property(env, result, "mimeType", value); + // 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; -// napi_create_string_utf8(env, conversationalMessage->GetUri()->ToString().c_str(), NAPI_AUTO_LENGTH, &value); -// napi_set_named_property(env, result, "uri", value); + // 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; -// napi_value messageUserResult; -// napi_create_object(env, &messageUserResult); -// if (SetMessageUser(env, conversationalMessage->GetSender(), messageUserResult)) { -// messageUserResult = NapiGetNull(); -// } -// napi_set_named_property(env, result, "sender", messageUserResult); + // sender: MessageUser; + napi_value messageUserResult; + napi_create_object(env, &messageUserResult); + if (SetMessageUser(env, conversationalMessage->GetSender(), messageUserResult)) { + messageUserResult = NapiGetNull(env); + } + napi_set_named_property(env, result, "sender", messageUserResult); -// return NapiGetboolean(env, true); -// } + return NapiGetboolean(env, true); +} napi_value Common::SetNotificationActionButton( - const napi_env &env, std::shared_ptr &actionButton, napi_value &result) + const napi_env &env, const std::shared_ptr &actionButton, napi_value &result) { ANS_LOGI("SetNotificationActionButton start"); if (actionButton == nullptr) { @@ -1160,14 +967,15 @@ napi_value Common::SetNotificationActionButton( // wantAgent: WantAgent std::shared_ptr agent = actionButton->GetWantAgent(); if (!agent) { - ANS_LOGE("wantAgent is null"); - return NapiGetboolean(env, false); + ANS_LOGI("wantAgent is null"); + napi_set_named_property(env, result, "wantAgent", NapiGetNull(env)); + return NapiGetboolean(env, true); } napi_value wantAgent; wantAgent = CreateWantAgentByJS(env, agent); napi_set_named_property(env, result, "wantAgent", wantAgent); - // extras?: {[key: string]: any} //do + // extras?: {[key: string]: any} //do // icon?: image.PixelMap //do return NapiGetboolean(env, true); } @@ -1277,7 +1085,10 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value return nullptr; } - // extraInfo?: {[key: string]: any} : do + // extraInfo?: {[key: string]: any} + if (GetNotificationExtraInfo(env, value, request) == nullptr) { + return nullptr; + } // removalWantAgent?: WantAgent if (GetNotificationRemovalWantAgent(env, value, request) == nullptr) { @@ -1314,10 +1125,10 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value // return nullptr; // } - // // classification?: string - // if (GetNotificationClassification(env, value, request) == nullptr) { - // return nullptr; - // } + // classification?: string + if (GetNotificationClassification(env, value, request) == nullptr) { + return nullptr; + } // color?: number if (GetNotificationColor(env, value, request) == nullptr) { @@ -1378,15 +1189,10 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value // return nullptr; // } - // // sortingKey?: string - // if (GetNotificationSortingKey(env, value, request) == nullptr) { - // return nullptr; - // } - - // isFloatingIcon?: boolean - // if (GetNotificationIsFloatingIcon(env, value, request) == nullptr) { - // return nullptr; - // } + // sortingKey?: string + if (GetNotificationSortingKey(env, value, request) == nullptr) { + return nullptr; + } // label?: string if (GetNotificationLabel(env, value, request) == nullptr) { @@ -1482,22 +1288,14 @@ napi_value Common::GetNotificationContent(const napi_env &env, const napi_value int32_t type; NAPI_CALL(env, napi_has_named_property(env, value, "content", &hasProperty)); - ANS_LOGI("============GetNotificationContent hasProperty = %{public}d", hasProperty); if (hasProperty) { - ANS_LOGI("============GetNotificationContent 000000000000000000000================"); napi_get_named_property(env, value, "content", &result); - ANS_LOGI("============GetNotificationContent 000000001111111111111111111================"); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - ANS_LOGI("============GetNotificationContent 0000000022222222222222222================"); - ANS_LOGI("============GetNotificationContent 0000000022222222222222222================ valuetype = " - "%{public}d", - valuetype); + ANS_LOGI("GetNotificationContent valuetype = %{public}d", valuetype); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - ANS_LOGI("============GetNotificationContent 11111111111111================"); if (GetNotificationContentType(env, result, type) == nullptr) { return nullptr; } - NotificationContent::Type outType; if (!ContentTypeJSToC(ContentType(type), outType)) { return nullptr; @@ -1516,8 +1314,16 @@ napi_value Common::GetNotificationContent(const napi_env &env, const napi_value } 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================"); @@ -1625,22 +1431,47 @@ napi_value Common::GetNotificationWantAgent(const napi_env &env, const napi_valu { ANS_LOGI("enter"); - bool hasProperty = false; - WantAgent::WantAgent *wantAgent = nullptr; - napi_value result; + bool hasProperty = false; + WantAgent::WantAgent *wantAgent = nullptr; + napi_value result; + napi_valuetype valuetype; + + NAPI_CALL(env, napi_has_named_property(env, value, "wantAgent", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "wantAgent", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + napi_unwrap(env, result, (void **)&wantAgent); + if (wantAgent == nullptr) { + return nullptr; + } + std::shared_ptr sWantAgent = std::make_shared(*wantAgent); + request.SetWantAgent(sWantAgent); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationExtraInfo(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; - NAPI_CALL(env, napi_has_named_property(env, value, "wantAgent", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "extraInfo", &hasProperty)); if (hasProperty) { - napi_get_named_property(env, value, "wantAgent", &result); + napi_get_named_property(env, value, "extraInfo", &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Bool expected."); - napi_unwrap(env, result, (void **)&wantAgent); - if (wantAgent == nullptr) { + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + AAFwk::WantParams wantParams; + if (!OHOS::AppExecFwk::UnwrapWantParams(env, result, wantParams)) { return nullptr; } - std::shared_ptr sWantAgent{wantAgent}; - request.SetWantAgent(sWantAgent); + + std::shared_ptr extras = std::make_shared(wantParams); + request.SetAdditionalData(extras); } return Common::NapiGetNull(env); @@ -1659,12 +1490,12 @@ napi_value GetNotificationRemovalWantAgent(const napi_env &env, const napi_value if (hasProperty) { napi_get_named_property(env, value, "removalWantAgent", &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Bool expected."); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); napi_unwrap(env, result, (void **)&wantAgent); if (wantAgent == nullptr) { return nullptr; } - std::shared_ptr removeWantAgent(wantAgent); + std::shared_ptr removeWantAgent = std::make_shared(*wantAgent); request.SetRemovalWantAgent(removeWantAgent); } @@ -1684,12 +1515,12 @@ napi_value GetNotificationMaxScreenWantAgent(const napi_env &env, const napi_val if (hasProperty) { napi_get_named_property(env, value, "maxScreenWantAgent", &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Bool expected."); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); napi_unwrap(env, result, (void **)&wantAgent); if (wantAgent == nullptr) { return nullptr; } - std::shared_ptr maxScreenWantAgent(wantAgent); + std::shared_ptr maxScreenWantAgent = std::make_shared(*wantAgent); request.SetMaxScreenWantAgent(maxScreenWantAgent); } @@ -1809,29 +1640,28 @@ 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) -// { -// ANS_LOGI("enter"); +napi_value GetNotificationClassification( + 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_value result; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; -// NAPI_CALL(env, napi_has_named_property(env, value, "classification", &hasProperty)); -// if (hasProperty) { -// napi_get_named_property(env, value, "classification", &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.SetClassification(str); -// } + NAPI_CALL(env, napi_has_named_property(env, value, "classification", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "classification", &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.SetClassification(str); + } -// ANS_LOGI("===============GetNotificationClassification====classification = %{public}s end", str); -// return Common::NapiGetNull(env); -// } + return Common::NapiGetNull(env); +} napi_value GetNotificationColor(const napi_env &env, const napi_value &value, NotificationRequest &request) { @@ -2091,46 +1921,24 @@ 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_valuetype valuetype; -// napi_value result; -// 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); -// } - -// ANS_LOGI("===============GetNotificationSortingKey====sortingKey = %{public}s end", str); -// return Common::NapiGetNull(env); -// } - -napi_value GetNotificationIsFloatingIcon(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value GetNotificationSortingKey( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); napi_valuetype valuetype; napi_value result; bool hasProperty = false; - bool isFloatingIcon; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; - NAPI_CALL(env, napi_has_named_property(env, value, "isFloatingIcon", &hasProperty)); + NAPI_CALL(env, napi_has_named_property(env, value, "sortingKey", &hasProperty)); if (hasProperty) { - napi_get_named_property(env, value, "isFloatingIcon", &result); + napi_get_named_property(env, value, "sortingKey", &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, &isFloatingIcon); - request.SetOnlyLocal(isFloatingIcon); + 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); @@ -2266,13 +2074,12 @@ napi_value GetNotificationNotificationActionButtons( 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. String expected."); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); napi_unwrap(env, wantAgentActionButton, (void **)&wantAgentPtr); if (wantAgentPtr == nullptr) { return nullptr; } - std::shared_ptr wantAgentOut(wantAgentPtr); - wantAgent = wantAgentOut; + wantAgent = std::make_shared(*wantAgentPtr); } std::vector> vec{nullptr}; @@ -2318,6 +2125,10 @@ napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &re 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."); @@ -2371,6 +2182,10 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value 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."); @@ -2405,10 +2220,6 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value ANS_LOGI("longText::additionalText = %{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, "longText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "longText", &longContentResult); @@ -2443,7 +2254,367 @@ napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value 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; + 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_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); + } + + 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); + } + + 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, "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); + } + + 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); + } + + 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); + } + + // bigPicture: image.PixelMap do + + request.SetContent(std::make_shared(pictureContent)); + } + + return Common::NapiGetNull(env); +} + +napi_value getMessageUser(const napi_env &env, const napi_value &senderResult, MessageUser &sender) +{ + ANS_LOGI("enter"); + napi_valuetype valuetype; + 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)); + if (hasProperty) { + napi_value nameResult; + napi_get_named_property(env, senderResult, "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); + ANS_LOGI("MessageUser::name = %{public}s", str); + } + // pixelMap: image.PixelMap do + // uri: string + NAPI_CALL(env, napi_has_named_property(env, senderResult, "uri", &hasProperty)); + if (hasProperty) { + napi_value uriResult; + napi_get_named_property(env, senderResult, "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); + ANS_LOGI("MessageUser::uri = %{public}s", str); + } + // important: boolean + NAPI_CALL(env, napi_has_named_property(env, senderResult, "important", &hasProperty)); + if (hasProperty) { + napi_value importantResult; + napi_get_named_property(env, senderResult, "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); + ANS_LOGI("MessageUser::important = %{public}d", important); + } + // machine: boolean + NAPI_CALL(env, napi_has_named_property(env, senderResult, "machine", &hasProperty)); + if (hasProperty) { + napi_value machineResult; + napi_get_named_property(env, senderResult, "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); + ANS_LOGI("MessageUser::machine = %{public}d", machine); + } + // key: string + NAPI_CALL(env, napi_has_named_property(env, senderResult, "key", &hasProperty)); + if (hasProperty) { + napi_value keyResult; + napi_get_named_property(env, senderResult, "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); + ANS_LOGI("MessageUser::key = %{public}s", str); + } + return Common::NapiGetNull(env); +} +napi_value getConversationalMessage(const napi_env &env, const napi_value &conversationalMessage, + std::shared_ptr &message) +{ + ANS_LOGI("enter"); + napi_valuetype valuetype; + 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_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); + } + // timestamp: number + NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "timestamp", &hasProperty)); + if (hasProperty) { + napi_value timestampResult; + 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}lld", timestamp); + } + // mimeType: string + NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "mimeType", &hasProperty)); + if (hasProperty) { + napi_value mimeTypeResult; + 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); + } + // uri: string + NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "uri", &hasProperty)); + if (hasProperty) { + napi_value uriResult; + 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); + } + // sender: MessageUser + NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "sender", &hasProperty)); + if (hasProperty) { + napi_value senderResult; + 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)) { + return nullptr; + } + } + std::shared_ptr messagePtr = + std::make_shared(text, timestamp, sender); + if (messagePtr == nullptr) { + ANS_LOGE("conversationalMessage is null"); + return nullptr; + } + std::shared_ptr uriPtr = std::make_shared(uri); + messagePtr->SetData(mimeType, uriPtr); + message = messagePtr; + return Common::NapiGetNull(env); +} + +napi_value GetNotificationConversationalContent( + const napi_env &env, const napi_value &result, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value contentResult; + napi_value conversationalContentResult; + napi_value basicContentResult; + 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_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."); + + // 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"); + 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); + } + + 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); + } + + 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, "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); + } + + 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); + } + 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 { + 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"); @@ -2492,10 +2663,6 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value ANS_LOGI("multiLine::additionalText = %{public}s", str); } - 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, "briefText", &hasProperty)); if (hasProperty) { napi_get_named_property(env, contentResult, "briefText", &multiLineContentResult); @@ -2780,9 +2947,6 @@ bool Common::ContentTypeCToJS(const enum NotificationContent::Type &inType, enum bool Common::SlotTypeJSToC(const enum SlotType &inType, enum NotificationConstant::SlotType &outType) { switch (inType) { - case SlotType::UNKNOWN_TYPE: - outType = NotificationConstant::SlotType::CUSTOM; - break; case SlotType::SOCIAL_COMMUNICATION: outType = NotificationConstant::SlotType::SOCIAL_COMMUNICATION; break; @@ -2792,6 +2956,7 @@ bool Common::SlotTypeJSToC(const enum SlotType &inType, enum NotificationConstan case SlotType::CONTENT_INFORMATION: outType = NotificationConstant::SlotType::CONTENT_INFORMATION; break; + case SlotType::UNKNOWN_TYPE: case SlotType::OTHER_TYPES: outType = NotificationConstant::SlotType::OTHER; break; diff --git a/kits/napi/src/constant.cpp b/interfaces/kits/napi/ans/src/constant.cpp similarity index 100% rename from kits/napi/src/constant.cpp rename to interfaces/kits/napi/ans/src/constant.cpp diff --git a/kits/napi/src/create_subscriber.cpp b/interfaces/kits/napi/ans/src/create_subscriber.cpp similarity index 74% rename from kits/napi/src/create_subscriber.cpp rename to interfaces/kits/napi/ans/src/create_subscriber.cpp index d256718b2fbc40cb89b21cadfc779f27a5e78a39..639da8fa8defc17d05113b03340fa427f795d40d 100644 --- a/kits/napi/src/create_subscriber.cpp +++ b/interfaces/kits/napi/ans/src/create_subscriber.cpp @@ -18,72 +18,95 @@ namespace OHOS { namespace NotificationNapi { -SubscriberInstance::SubscriberInstance() -{} - -SubscriberInstance::~SubscriberInstance() -{} - -void SubscriberInstance::OnCanceled(const std::shared_ptr &request) +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("OnCanceled start"); - - if (canceCallbackInfo_.ref == nullptr) { - ANS_LOGI("cancel callback unset"); - return; - } - + ANS_LOGI("SetSubscribeCallbackData start"); if (request == nullptr) { ANS_LOGE("request is null"); - return; + return Common::NapiGetboolean(env, false); } - ANS_LOGI("OnCanceled NotificationId = %{public}d", request->GetNotificationRequest().GetNotificationId()); - uv_loop_s *loop = nullptr; -#if NAPI_VERSION >= 2 - napi_get_uv_event_loop(canceCallbackInfo_.env, &loop); -#endif // NAPI_VERSION >= 2 + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return Common::NapiGetboolean(env, false); + } - NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); - dataWorker->request = request; - dataWorker->env = canceCallbackInfo_.env; - dataWorker->ref = canceCallbackInfo_.ref; + // 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); - uv_work_t *work = new uv_work_t; - work->data = (void *)dataWorker; + // 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); - 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_LOGI("dataWorkerData is nullptr"); - return; - } - napi_value result; - napi_create_object(dataWorkerData->env, &result); - int error = 0; - if (!SetSubscriberCallbackData(dataWorkerData->env, dataWorkerData->request, result)) { - result = Common::NapiGetNull(dataWorkerData->env); - error = ERROR; - } else { - error = NO_ERROR; - } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + // 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); + } - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + 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("OnCanceled2 start"); + ANS_LOGI("OnCanceled start"); if (canceCallbackInfo_.ref == nullptr) { ANS_LOGI("cancel callback unset"); @@ -99,16 +122,16 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrGetNotificationRequest().GetNotificationId()); - ANS_LOGI("OnCanceled2 sortingMap size = %{public}d", sortingMap->GetKey().size()); - ANS_LOGI("OnCanceled2 deleteReason = %{public}d", deleteReason); + 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 NotificationReceiveDataWorker(); + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); dataWorker->request = request; dataWorker->sortingMap = sortingMap; dataWorker->deleteReason = deleteReason; @@ -122,7 +145,7 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrdata; if (dataWorkerData == nullptr) { ANS_LOGE("dataWorkerData is null"); @@ -131,7 +154,7 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrenv, &result); int error = 0; - if (!SetSubscriberCallbackData(dataWorkerData->env, + if (!SetSubscribeCallbackData(dataWorkerData->env, dataWorkerData->request, dataWorkerData->sortingMap, dataWorkerData->deleteReason, @@ -151,65 +174,12 @@ void SubscriberInstance::OnCanceled(const std::shared_ptr &request) -{ - ANS_LOGI("OnConsumed start"); - - if (consumeCallbackInfo_.ref == nullptr) { - ANS_LOGI("consume callback unset"); - return; - } - - if (request == nullptr) { - ANS_LOGE("request is null"); - return; - } - ANS_LOGI("OnConsumed NotificationId = %{public}d", request->GetNotificationRequest().GetNotificationId()); - - uv_loop_s *loop = nullptr; -#if NAPI_VERSION >= 2 - napi_get_uv_event_loop(consumeCallbackInfo_.env, &loop); -#endif // NAPI_VERSION >= 2 - - NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); - dataWorker->request = request; - dataWorker->env = consumeCallbackInfo_.env; - dataWorker->ref = consumeCallbackInfo_.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("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 (!SetSubscriberCallbackData(dataWorkerData->env, dataWorkerData->request, 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, const std::shared_ptr &sortingMap) { - ANS_LOGI("OnConsumed2 start"); + ANS_LOGI("OnConsumed start"); if (consumeCallbackInfo_.ref == nullptr) { ANS_LOGI("consume callback unset"); @@ -225,28 +195,28 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrGetNotificationRequest().GetNotificationId()); - ANS_LOGI("OnConsumed2 sortingMap size = %{public}d", sortingMap->GetKey().size()); + 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 NotificationReceiveDataWorker(); + 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 uv_work_t; + 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("OnConsumed2 uv_work_t start"); + ANS_LOGI("OnConsumed uv_work_t start"); NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; if (dataWorkerData == nullptr) { ANS_LOGE("dataWorkerData is null"); @@ -255,10 +225,10 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrenv, &result); int error = 0; - if (!SetSubscriberCallbackData(dataWorkerData->env, + if (!SetSubscribeCallbackData(dataWorkerData->env, dataWorkerData->request, dataWorkerData->sortingMap, - dataWorkerData->deleteReason, + NO_DELETE_REASON, result)) { result = Common::NapiGetNull(dataWorkerData->env); error = ERROR; @@ -294,12 +264,12 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr napi_get_uv_event_loop(updateCallbackInfo_.env, &loop); #endif // NAPI_VERSION >= 2 - NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); dataWorker->sortingMap = sortingMap; dataWorker->env = updateCallbackInfo_.env; dataWorker->ref = updateCallbackInfo_.ref; - uv_work_t *work = new uv_work_t; + uv_work_t *work = new (std::nothrow) uv_work_t; work->data = (void *)dataWorker; uv_queue_work(loop, @@ -345,12 +315,12 @@ void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult napi_get_uv_event_loop(subscribeCallbackInfo_.env, &loop); #endif // NAPI_VERSION >= 2 - NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); dataWorker->result = (int)result; dataWorker->env = subscribeCallbackInfo_.env; dataWorker->ref = subscribeCallbackInfo_.ref; - uv_work_t *work = new uv_work_t; + uv_work_t *work = new (std::nothrow) uv_work_t; work->data = (void *)dataWorker; uv_queue_work(loop, @@ -391,12 +361,12 @@ void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResu napi_get_uv_event_loop(unsubscribeCallbackInfo_.env, &loop); #endif // NAPI_VERSION >= 2 - NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); dataWorker->result = (int)result; dataWorker->env = unsubscribeCallbackInfo_.env; dataWorker->ref = unsubscribeCallbackInfo_.ref; - uv_work_t *work = new uv_work_t; + uv_work_t *work = new (std::nothrow) uv_work_t; work->data = (void *)dataWorker; uv_queue_work(loop, @@ -436,11 +406,11 @@ void SubscriberInstance::OnDied() napi_get_uv_event_loop(dieCallbackInfo_.env, &loop); #endif // NAPI_VERSION >= 2 - NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); dataWorker->env = dieCallbackInfo_.env; dataWorker->ref = dieCallbackInfo_.ref; - uv_work_t *work = new uv_work_t; + uv_work_t *work = new (std::nothrow) uv_work_t; work->data = (void *)dataWorker; uv_queue_work(loop, @@ -479,12 +449,12 @@ void SubscriberInstance::OnDisturbModeChanged(int disturbMode) napi_get_uv_event_loop(disturbModeCallbackInfo_.env, &loop); #endif // NAPI_VERSION >= 2 - NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); dataWorker->disturbMode = disturbMode; dataWorker->env = disturbModeCallbackInfo_.env; dataWorker->ref = disturbModeCallbackInfo_.ref; - uv_work_t *work = new uv_work_t; + uv_work_t *work = new (std::nothrow) uv_work_t; work->data = (void *)dataWorker; uv_queue_work(loop, @@ -569,7 +539,7 @@ void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string } else if (type == DISTURB_MODE_CHANGE) { SetDisturbModeCallbackInfo(env, ref); } else { - ANS_LOGI("type is error"); + ANS_LOGW("type is error"); } } @@ -581,23 +551,24 @@ napi_value ParseParametersByOn(const napi_env &env, const size_t &argc, const na size_t strLen = 0; char str[STR_MAX_SIZE] = {0}; - if (argc >= ON_MAX_PARA) { - // 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; - } + NAPI_ASSERT(env, argc >= ON_MAX_PARA, "Wrong number of arguments"); - // 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); + // 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); } @@ -609,7 +580,6 @@ napi_value On(napi_env env, napi_callback_info info) napi_value argv[ON_MAX_PARA]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= ON_MAX_PARA, "Wrong number of arguments"); std::string type; napi_ref callback = 0; @@ -621,10 +591,10 @@ napi_value On(napi_env env, napi_callback_info info) napi_unwrap(env, thisVar, (void **)&objectInfo); ANS_LOGI("On objectInfo = %{public}p", objectInfo); - AsyncCallbackInfoOn *asynccallbackinfo = new AsyncCallbackInfoOn{ + AsyncCallbackInfoOn *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoOn{ .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .type = type, .callback = callback}; - if (!AddAsyncCallbackInfoOn(objectInfo, asynccallbackinfo)) { + if (!AddAsyncCallbackInfo(objectInfo, asynccallbackinfo)) { return Common::NapiGetNull(env); } @@ -661,18 +631,19 @@ napi_value ParseParametersByOff( size_t strLen = 0; char str[STR_MAX_SIZE] = {0}; - if (argc >= OFF_MAX_PARA) { - // 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; - } + 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); } @@ -684,7 +655,6 @@ napi_value Off(napi_env env, napi_callback_info info) napi_value argv[OFF_MAX_PARA]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= OFF_MAX_PARA, "Wrong number of arguments"); std::string type; if (ParseParametersByOff(env, argc, argv, type) == nullptr) { @@ -695,7 +665,7 @@ napi_value Off(napi_env env, napi_callback_info info) napi_unwrap(env, thisVar, (void **)&objectInfo); ANS_LOGI("Off objectInfo = %{public}p", objectInfo); - AsyncCallbackInfoOff *asynccallbackinfo = new AsyncCallbackInfoOff{ + AsyncCallbackInfoOff *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoOff{ .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .type = type, .callback = nullptr}; napi_value resourceName; @@ -715,7 +685,7 @@ napi_value Off(napi_env env, napi_callback_info info) AsyncCallbackInfoOff *asynccallbackinfo = (AsyncCallbackInfoOff *)data; napi_delete_async_work(env, asynccallbackinfo->asyncWork); - DelAsyncCallbackInfoOn(asynccallbackinfo->objectInfo, asynccallbackinfo->type); + DelAsyncCallbackInfo(asynccallbackinfo->objectInfo, asynccallbackinfo->type); if (asynccallbackinfo) { delete asynccallbackinfo; @@ -737,7 +707,6 @@ napi_value CreateSubscriber(napi_env env, napi_callback_info info) size_t argc = 0; napi_value argv[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); napi_value result = 0; napi_new_instance(env, g_NotificationSubscriber, 0, nullptr, &result); @@ -758,7 +727,7 @@ napi_value SubscriberConstructor(napi_env env, napi_callback_info info) if (!CreateSubscriberInstanceRecord(&objectInfo)) { return Common::NapiGetNull(env); } - ANS_LOGI("SubscriberConstructor objectInfo = %{public}p", objectInfo); + ANS_LOGI("SubscriberConstructor objectInfo = %{public}p", objectInfo); napi_wrap(env, thisVar, @@ -767,7 +736,7 @@ napi_value SubscriberConstructor(napi_env env, napi_callback_info info) SubscriberInstance *objectInfo = (SubscriberInstance *)data; ANS_LOGI("SubscriberConstructor this = %{public}p, destruct", objectInfo); - DelAsyncCallbackInfoOn(objectInfo); + DelAsyncCallbackInfo(objectInfo); if (objectInfo) { delete objectInfo; @@ -785,7 +754,7 @@ bool CreateSubscriberInstanceRecord(SubscriberInstance **subscriber) { ANS_LOGI("CreateSubscriberInstanceRecord start"); - *subscriber = new SubscriberInstance(); + *subscriber = new (std::nothrow) SubscriberInstance(); if (*subscriber == nullptr) { ANS_LOGE("subscriber is null"); @@ -798,9 +767,9 @@ bool CreateSubscriberInstanceRecord(SubscriberInstance **subscriber) return true; } -bool AddAsyncCallbackInfoOn(SubscriberInstance *subscriber, AsyncCallbackInfoOn *asynccallbackinfo) +bool AddAsyncCallbackInfo(SubscriberInstance *subscriber, AsyncCallbackInfoOn *asynccallbackinfo) { - ANS_LOGI("AddAsyncCallbackInfoOn start"); + ANS_LOGI("AddAsyncCallbackInfo start"); if (subscriber == nullptr) { ANS_LOGE("subscriber is null"); @@ -815,10 +784,10 @@ bool AddAsyncCallbackInfoOn(SubscriberInstance *subscriber, AsyncCallbackInfoOn std::lock_guard lock(mutex_); auto infoItem = g_SubscriberInstances.find(subscriber); if (infoItem != g_SubscriberInstances.end()) { - ANS_LOGI("AddAsyncCallbackInfoOn AsyncCallbackInfoOn size = %{public}d", infoItem->second.size()); + ANS_LOGI("AddAsyncCallbackInfo AsyncCallbackInfoOn size = %{public}d", infoItem->second.size()); for (auto asyncCallbackInfoOn : infoItem->second) { - ANS_LOGI("AddAsyncCallbackInfoOn AsyncCallbackInfoOn ptr = %{public}p", asyncCallbackInfoOn); - ANS_LOGI("AsyncCallbackInfoOn->type = %{public}s", asyncCallbackInfoOn->type.c_str()); + 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; @@ -833,7 +802,7 @@ bool AddAsyncCallbackInfoOn(SubscriberInstance *subscriber, AsyncCallbackInfoOn return true; } -bool DelAsyncCallbackInfoOn(SubscriberInstance *subscriber, const std::string &type) +bool DelAsyncCallbackInfo(SubscriberInstance *subscriber, const std::string &type) { ANS_LOGI("DelSubscriberInstance start"); @@ -857,7 +826,7 @@ bool DelAsyncCallbackInfoOn(SubscriberInstance *subscriber, const std::string &t } 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()); + ANS_LOGI("DelSubscriberInstance type = %{public}s", (*it)->type.c_str()); if ((*it)->type == type) { delete *it; *it = nullptr; @@ -898,71 +867,6 @@ bool HasNotificationSubscriber(SubscriberInstance *subscriber) } } -napi_value SetSubscriberCallbackData( - const napi_env &env, const std::shared_ptr &request, napi_value &result) -{ - ANS_LOGI("SetSubscriberCallbackData start"); - if (request == nullptr) { - ANS_LOGE("request is null"); - return Common::NapiGetboolean(env, false); - } - - // request: NotificationRequest - napi_value requestResult; - napi_create_object(env, &requestResult); - if (!Common::SetNotificationRequest(env, request, requestResult)) { - ANS_LOGE("SetNotificationRequest call failed"); - return Common::NapiGetboolean(env, false); - } - napi_set_named_property(env, result, "request", requestResult); - return Common::NapiGetboolean(env, true); -} - -napi_value SetSubscriberCallbackData(const napi_env &env, - const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason, napi_value &result) -{ - ANS_LOGI("SetSubscriberCallbackData2 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::SetNotificationRequest(env, request, requestResult)) { - ANS_LOGE("SetNotificationRequest 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 - 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); -} - napi_value NotificationSubscriberInit(napi_env env, napi_value exports) { ANS_LOGI("NotificationSubscriberInit start"); diff --git a/kits/napi/src/get_active.cpp b/interfaces/kits/napi/ans/src/get_active.cpp similarity index 72% rename from kits/napi/src/get_active.cpp rename to interfaces/kits/napi/ans/src/get_active.cpp index ce550ec574f89dfdad8bb19a0f0e723203b503b7..28ab27097df2d58abc0f5ef689ca396db0618ae0 100644 --- a/kits/napi/src/get_active.cpp +++ b/interfaces/kits/napi/ans/src/get_active.cpp @@ -17,45 +17,31 @@ namespace OHOS { namespace NotificationNapi { +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_value result = nullptr; + int errorCode = 0; +}; + 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) { ANS_LOGI("ParseParametersByAllActive start"); - if (argc >= 1) { + if (argc >= ALL_ACTIVE_MAX_PARA) { napi_valuetype valuetype; - // argv[0]: hashcode: Array / callback - bool isArray = false; - napi_is_array(env, argv[0], &isArray); - if (isArray) { - uint32_t length = 0; - napi_get_array_length(env, argv[0], &length); - if (length > 0) { - for (uint32_t i = 0; i < length; ++i) { - napi_value nHashcode; - char str[STR_MAX_SIZE] = {0}; - size_t strLen = 0; - napi_get_element(env, argv[0], i, &nHashcode); - NAPI_CALL(env, napi_typeof(env, nHashcode, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, nHashcode, str, STR_MAX_SIZE - 1, &strLen)); - strValue.emplace_back(str); - } - } else { - ANS_LOGI("hashcode: Array lenth is 0"); - return nullptr; - } - } else { - 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); - } - if (argc >= ALL_ACTIVE_MAX_PARA) { - // 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); - } + // 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); @@ -100,17 +86,16 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) 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_ASSERT(env, argc >= 0, "Wrong number of arguments"); napi_ref callback = nullptr; std::vector hashcode; if (ParseParametersByAllActive(env, argv, argc, hashcode, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } ANS_LOGI("GetAllActiveNotifications hashcode.size = %{public}d", hashcode.size()); AsyncCallbackInfoActive *asynccallbackinfo = - new AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr, .strValue = hashcode}; + new (std::nothrow) AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr, .strValue = hashcode}; napi_value promise = 0; PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); @@ -133,23 +118,28 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) asynccallbackinfo->errorCode = NotificationHelper::GetAllActiveNotifications(notification); } - napi_value arr; - int count = 0; - napi_create_array(env, &arr); - for (auto vec : notification) { - if (vec) { - napi_value result; - std::shared_ptr notificationSharedPtr( - static_cast(vec.GetRefPtr())); - if (Common::SetNotificationRequest(env, notificationSharedPtr, result)) { - napi_set_element(env, arr, count, result); - count++; + 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++; + } } } - } - if (count > 0) { - ANS_LOGI("GetAllActiveNotifications count = %{public}d", count); - asynccallbackinfo->result = arr; + if (count > 0) { + ANS_LOGI("GetAllActiveNotifications count = %{public}d", count); + asynccallbackinfo->result = arr; + } else { + asynccallbackinfo->errorCode = ERROR; + asynccallbackinfo->result = Common::NapiGetNull(env); + } } else { asynccallbackinfo->result = Common::NapiGetNull(env); } @@ -191,14 +181,14 @@ napi_value GetActiveNotifications(napi_env env, napi_callback_info info) 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_ASSERT(env, argc >= 0, "Wrong number of arguments"); napi_ref callback = nullptr; if (ParseParameters(env, argv, argc, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } - AsyncCallbackInfoActive *asynccallbackinfo = new AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr}; + AsyncCallbackInfoActive *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr}; napi_value promise = 0; PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); @@ -216,23 +206,28 @@ napi_value GetActiveNotifications(napi_env env, napi_callback_info info) std::vector> request; asynccallbackinfo->errorCode = NotificationHelper::GetActiveNotifications(request); - napi_value arr; - int count = 0; - napi_create_array(env, &arr); - for (auto vec : request) { - if (vec) { - napi_value result; - std::shared_ptr requestSharedPtr( - static_cast(vec.GetRefPtr())); - if (Common::SetNotificationRequest2(env, requestSharedPtr, result)) { - napi_set_element(env, arr, count, result); - count++; + 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++; + } } } - } - if (count > 0) { - ANS_LOGI("GetActiveNotifications count = %{public}d", count); - asynccallbackinfo->result = arr; + if (count > 0) { + ANS_LOGI("GetActiveNotifications count = %{public}d", count); + asynccallbackinfo->result = arr; + } else { + asynccallbackinfo->errorCode = ERROR; + asynccallbackinfo->result = Common::NapiGetNull(env); + } } else { asynccallbackinfo->result = Common::NapiGetNull(env); } @@ -273,14 +268,14 @@ napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info) 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_ASSERT(env, argc >= 0, "Wrong number of arguments"); napi_ref callback = nullptr; if (ParseParameters(env, argv, argc, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } - AsyncCallbackInfoActive *asynccallbackinfo = new AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr}; + AsyncCallbackInfoActive *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr}; napi_value promise = 0; PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); @@ -298,7 +293,11 @@ napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info) int32_t nums = 0; asynccallbackinfo->errorCode = NotificationHelper::GetActiveNotificationNums(nums); ANS_LOGI("GetActiveNotificationNums nums = %{public}d", nums); - napi_create_int32(env, nums, &asynccallbackinfo->result); + if (asynccallbackinfo->errorCode == ERR_OK) { + napi_create_int32(env, nums, &asynccallbackinfo->result); + } else { + asynccallbackinfo->result = Common::NapiGetNull(env); + } }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("GetActiveNotificationNums napi_create_async_work end"); diff --git a/kits/napi/src/init.cpp b/interfaces/kits/napi/ans/src/init.cpp similarity index 84% rename from kits/napi/src/init.cpp rename to interfaces/kits/napi/ans/src/init.cpp index 4c4a99ee9eff7ab48bb04cb4b3660b6854e69c2b..25bfdb3d4440735d69ad05e6d0266031a4b741c3 100644 --- a/kits/napi/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -35,20 +35,13 @@ 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("removeAsBundle", RemoveAsBundle), DECLARE_NAPI_FUNCTION("getAllActiveNotifications", GetAllActiveNotifications), DECLARE_NAPI_FUNCTION("getActiveNotifications", GetActiveNotifications), DECLARE_NAPI_FUNCTION("getActiveNotificationNums", GetActiveNotificationNums), DECLARE_NAPI_FUNCTION("cancel", Cancel), DECLARE_NAPI_FUNCTION("cancelAll", CancelAll), - DECLARE_NAPI_FUNCTION("addSlot", AddSlot), - DECLARE_NAPI_FUNCTION("addSlots", AddSlots), DECLARE_NAPI_FUNCTION("getSlot", GetSlot), DECLARE_NAPI_FUNCTION("getSlots", GetSlots), DECLARE_NAPI_FUNCTION("removeSlot", RemoveSlot), @@ -83,4 +76,4 @@ __attribute__((constructor)) void RegisterModule(void) EXTERN_C_END } // namespace NotificationNapi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/kits/napi/src/publish.cpp b/interfaces/kits/napi/ans/src/publish.cpp similarity index 79% rename from kits/napi/src/publish.cpp rename to interfaces/kits/napi/ans/src/publish.cpp index a4a45797338fed3c75fbc162c3bd2c7bb9773da2..4f85115a7ccedd06427a9e07f722b476ad858bc2 100644 --- a/kits/napi/src/publish.cpp +++ b/interfaces/kits/napi/ans/src/publish.cpp @@ -20,10 +20,114 @@ namespace OHOS { namespace NotificationNapi { -using namespace OHOS::Notification; +static const int32_t PUBLISH_NOTIFICATION_MAX = 2; -static napi_value GetCallbackByPublish( - ParseParametersPublish &parseParameters, const napi_value &value, napi_valuetype &valuetype); +struct AsyncCallbackInfoPublish { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = 0; + napi_deferred deferred; + NotificationRequest notificationRequest; + std::string lable; + bool isCallback = false; + bool isPublishNotificationTwoPara = false; + int errorCode = 0; +}; + +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; + std::string lable; + napi_ref callback; +}; + +napi_value GetCallbackByPublish( + ParseParametersPublish &parseParameters, const napi_value &value, napi_valuetype &valuetype) +{ + 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); + ANS_LOGI("end"); + return Common::NapiGetNull(parseParameters.env); +} + +napi_value ParseParametersByPublish(ParseParametersPublish &parseParameters, + const napi_value (&argv)[PUBLISH_NOTIFICATION_MAX], NotificationRequest ¬ificationRequest) +{ + ANS_LOGI("enter"); + + NAPI_ASSERT(parseParameters.env, parseParameters.argc >= 1, "Wrong number of arguments"); + napi_valuetype valuetype; + + NAPI_CALL(parseParameters.env, napi_typeof(parseParameters.env, argv[0], &valuetype)); + NAPI_ASSERT(parseParameters.env, valuetype == napi_object, "Wrong argument type. Object expected."); + + // argv[0]----NotificationRequest + if (Common::GetNotificationRequest(parseParameters.env, argv[0], notificationRequest) == nullptr) { + return nullptr; + } + + // argv[1] : callback + if (parseParameters.argc >= PUBLISH_NOTIFICATION_MAX) { + GetCallbackByPublish(parseParameters, argv[1], valuetype); + } + + 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; +} napi_value Publish(napi_env env, napi_callback_info info) { @@ -32,14 +136,14 @@ napi_value Publish(napi_env env, napi_callback_info info) size_t argc = PUBLISH_NOTIFICATION_MAX; napi_value argv[PUBLISH_NOTIFICATION_MAX]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); ParseParametersPublish parseParameters = {env, argc, false, "", nullptr}; NotificationRequest notificationRequest; if (ParseParametersByPublish(parseParameters, argv, notificationRequest) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, parseParameters.callback); } - AsyncCallbackInfoPublish *asynccallbackinfo = new AsyncCallbackInfoPublish{.env = env, .asyncWork = nullptr}; + AsyncCallbackInfoPublish *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoPublish{.env = env, .asyncWork = nullptr}; napi_value promise = 0; PaddingCallbackInfoInfoPublish(asynccallbackinfo, parseParameters, notificationRequest); @@ -92,71 +196,5 @@ napi_value Publish(napi_env env, napi_callback_info info) return promise; } } - -napi_value ParseParametersByPublish(ParseParametersPublish &parseParameters, - const napi_value (&argv)[PUBLISH_NOTIFICATION_MAX], NotificationRequest ¬ificationRequest) -{ - ANS_LOGI("enter"); - - napi_valuetype valuetype; - - NAPI_CALL(parseParameters.env, napi_typeof(parseParameters.env, argv[0], &valuetype)); - NAPI_ASSERT(parseParameters.env, valuetype == napi_object, "Wrong argument type. Object expected."); - - // argv[0]----NotificationRequest - if (Common::GetNotificationRequest(parseParameters.env, argv[0], notificationRequest) == nullptr) { - return nullptr; - } - - // argv[1] : callback - if (parseParameters.argc == PUBLISH_NOTIFICATION_MAX) { - GetCallbackByPublish(parseParameters, argv[1], valuetype); - } - - ANS_LOGI("end"); - return Common::NapiGetNull(parseParameters.env); -} - -napi_value GetCallbackByPublish( - ParseParametersPublish &parseParameters, const napi_value &value, napi_valuetype &valuetype) -{ - 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); - 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; -} - } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/kits/napi/src/remove.cpp b/interfaces/kits/napi/ans/src/remove.cpp similarity index 92% rename from kits/napi/src/remove.cpp rename to interfaces/kits/napi/ans/src/remove.cpp index e1c4ec600f66e4f275ec80fc42ed2f0acf598e35..a3f01f9241aca8905301247b39e13f04319552c4 100644 --- a/kits/napi/src/remove.cpp +++ b/interfaces/kits/napi/ans/src/remove.cpp @@ -17,9 +17,24 @@ namespace OHOS { namespace NotificationNapi { +const int REMOVE_OR_BUNDLE_MAX_PARA = 2; +const int REMOVE_ALL_MAX_PARA = 1; + +struct AsyncCallbackInfoRemove { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + std::string strValue; + bool isCallback = false; + int errorCode = 0; +}; + napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[REMOVE_OR_BUNDLE_MAX_PARA], const size_t &argc, std::string &strValue, napi_ref &callback) { + + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); // argv[0]: hashCode/bundleName size_t strLen; char str[STR_MAX_SIZE] = {0}; @@ -74,17 +89,16 @@ napi_value Remove(napi_env env, napi_callback_info info) 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_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_ref callback = nullptr; std::string hashCode; if (ParseParameters(env, argv, argc, hashCode, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } ANS_LOGI("Remove hashCode = %{public}s", hashCode.c_str()); AsyncCallbackInfoRemove *asynccallbackinfo = - new AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .strValue = hashCode}; + new (std::nothrow) AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .strValue = hashCode}; napi_value promise = 0; PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); @@ -136,17 +150,17 @@ napi_value RemoveAsBundle(napi_env env, napi_callback_info info) 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_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; std::string bundleName; if (ParseParameters(env, argv, argc, bundleName, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } ANS_LOGI("RemoveAsBundle bundleName = %{public}s", bundleName.c_str()); AsyncCallbackInfoRemove *asynccallbackinfo = - new AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .strValue = bundleName}; + new (std::nothrow) AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .strValue = bundleName}; napi_value promise = 0; PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); @@ -198,14 +212,14 @@ napi_value RemoveAll(napi_env env, napi_callback_info info) 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_ASSERT(env, argc >= 0, "Wrong number of arguments"); napi_ref callback = nullptr; if (ParseParametersByRemoveAll(env, argv, argc, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } - AsyncCallbackInfoRemove *asynccallbackinfo = new AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr}; + AsyncCallbackInfoRemove *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr}; napi_value promise = 0; PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); diff --git a/kits/napi/src/slot.cpp b/interfaces/kits/napi/ans/src/slot.cpp similarity index 85% rename from kits/napi/src/slot.cpp rename to interfaces/kits/napi/ans/src/slot.cpp index d5c8b571bf2334263e84fe5f21d5045d357db42c..99864d9d271ead2390170f185187dcb6e954aff3 100644 --- a/kits/napi/src/slot.cpp +++ b/interfaces/kits/napi/ans/src/slot.cpp @@ -17,9 +17,67 @@ namespace OHOS { namespace NotificationNapi { +const int ADD_SLOT_MAX_PARA = 2; +const int ADD_SLOTS_MAX_PARA = 2; +const int GET_SLOT_MAX_PARA = 2; +const int GET_SLOTS_MAX_PARA = 1; +const int REMOVE_SLOT_MAX_PARA = 2; + +struct AsyncCallbackInfoAddSlot { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + NotificationSlot slot; + bool isCallback = false; + int errorCode = 0; +}; + +struct AsyncCallbackInfoAddSlots { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + std::vector slots; + bool isCallback = false; + int errorCode = 0; +}; + +struct AsyncCallbackInfoGetSlot { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + enum NotificationConstant::SlotType outType; + bool isCallback = false; + napi_value result = nullptr; + int errorCode = 0; +}; + +struct AsyncCallbackInfoGetSlots { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + bool isCallback = false; + napi_value result = nullptr; + int errorCode = 0; +}; + +struct AsyncCallbackInfoRemoveSlot { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + enum NotificationConstant::SlotType outType; + bool isCallback = false; + int errorCode = 0; +}; + napi_value ParseParametersByAddSlot(const napi_env &env, const napi_value (&argv)[ADD_SLOT_MAX_PARA], const size_t &argc, NotificationSlot &slot, napi_ref &callback) { + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype; // argv[0]: NotificationSlot NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); @@ -55,6 +113,7 @@ void PaddingAsyncCallbackInfoIsByAddSlot( 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_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype; // argv[0]: Array bool isArray = false; @@ -68,7 +127,7 @@ napi_value ParseParametersByAddSlots(const napi_env &env, const napi_value (&arg 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, argv[0])) { + if (!Common::GetNotificationSlot(env, slot, nSlot)) { return nullptr; } slots.emplace_back(slot); @@ -106,6 +165,7 @@ void PaddingAsyncCallbackInfoIsByAddSlots( 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_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype; // argv[0]: SlotType NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); @@ -175,6 +235,7 @@ void PaddingAsyncCallbackInfoIsByGetSlots( 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_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype; // argv[0]: SlotType NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); @@ -220,16 +281,16 @@ napi_value AddSlot(napi_env env, napi_callback_info info) napi_value argv[ADD_SLOT_MAX_PARA]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; NotificationSlot slot; if (ParseParametersByAddSlot(env, argv, argc, slot, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } AsyncCallbackInfoAddSlot *asynccallbackinfo = - new AsyncCallbackInfoAddSlot{.env = env, .asyncWork = nullptr, .slot = slot}; + new (std::nothrow) AsyncCallbackInfoAddSlot{.env = env, .asyncWork = nullptr, .slot = slot}; napi_value promise = 0; PaddingAsyncCallbackInfoIsByAddSlot(env, asynccallbackinfo, callback, promise); @@ -281,16 +342,16 @@ napi_value AddSlots(napi_env env, napi_callback_info info) napi_value argv[ADD_SLOTS_MAX_PARA]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; std::vector slots; if (ParseParametersByAddSlots(env, argv, argc, slots, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } AsyncCallbackInfoAddSlots *asynccallbackinfo = - new AsyncCallbackInfoAddSlots{.env = env, .asyncWork = nullptr, .slots = slots}; + new (std::nothrow) AsyncCallbackInfoAddSlots{.env = env, .asyncWork = nullptr, .slots = slots}; napi_value promise = 0; PaddingAsyncCallbackInfoIsByAddSlots(env, asynccallbackinfo, callback, promise); @@ -342,16 +403,16 @@ napi_value GetSlot(napi_env env, napi_callback_info info) napi_value argv[GET_SLOT_MAX_PARA]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; enum NotificationConstant::SlotType outType; if (ParseParametersByGetSlot(env, argv, argc, outType, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } AsyncCallbackInfoGetSlot *asynccallbackinfo = - new AsyncCallbackInfoGetSlot{.env = env, .asyncWork = nullptr, .outType = outType}; + new (std::nothrow) AsyncCallbackInfoGetSlot{.env = env, .asyncWork = nullptr, .outType = outType}; napi_value promise = 0; PaddingAsyncCallbackInfoIsByGetSlot(env, asynccallbackinfo, callback, promise); @@ -366,11 +427,12 @@ napi_value GetSlot(napi_env env, napi_callback_info info) ANS_LOGI("GetSlot napi_create_async_work start"); AsyncCallbackInfoGetSlot *asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; - sptr slot; + sptr slot = nullptr; asynccallbackinfo->errorCode = NotificationHelper::GetNotificationSlot(asynccallbackinfo->outType, slot); - if (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 { @@ -414,14 +476,14 @@ napi_value GetSlots(napi_env env, napi_callback_info info) 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_ASSERT(env, argc >= 0, "Wrong number of arguments"); napi_ref callback = nullptr; if (ParseParametersByGetSlots(env, argv, argc, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } - AsyncCallbackInfoGetSlots *asynccallbackinfo = new AsyncCallbackInfoGetSlots{.env = env, .asyncWork = nullptr}; + AsyncCallbackInfoGetSlots *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetSlots{.env = env, .asyncWork = nullptr}; napi_value promise = 0; PaddingAsyncCallbackInfoIsByGetSlots(env, asynccallbackinfo, callback, promise); @@ -438,25 +500,29 @@ napi_value GetSlots(napi_env env, napi_callback_info info) std::vector> slots; asynccallbackinfo->errorCode = NotificationHelper::GetNotificationSlots(slots); - - 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++; + 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++; + } } } - } - ANS_LOGI("getSlots count = %{public}d", count); - if (count == 0) { + ANS_LOGI("getSlots count = %{public}d", count); + if (count == 0) { + asynccallbackinfo->errorCode = ERROR; + asynccallbackinfo->result = Common::NapiGetNull(env); + } + asynccallbackinfo->result = arr; + } else { asynccallbackinfo->result = Common::NapiGetNull(env); } - asynccallbackinfo->result = arr; }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("GetSlots napi_create_async_work end"); @@ -494,16 +560,16 @@ napi_value RemoveSlot(napi_env env, napi_callback_info info) napi_value argv[REMOVE_SLOT_MAX_PARA]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; enum NotificationConstant::SlotType outType; if (ParseParametersByRemoveSlot(env, argv, argc, outType, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } AsyncCallbackInfoRemoveSlot *asynccallbackinfo = - new AsyncCallbackInfoRemoveSlot{.env = env, .asyncWork = nullptr, .outType = outType}; + new (std::nothrow) AsyncCallbackInfoRemoveSlot{.env = env, .asyncWork = nullptr, .outType = outType}; napi_value promise = 0; PaddingAsyncCallbackInfoIsByRemoveSlot(env, asynccallbackinfo, callback, promise); diff --git a/kits/napi/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp similarity index 91% rename from kits/napi/src/subscribe.cpp rename to interfaces/kits/napi/ans/src/subscribe.cpp index 87074cef248b3b93ef653a8e14c558eb1c4a6bca..af36a9452a65bd7b7269e9303ec5cb3ab2dbf8ea 100644 --- a/kits/napi/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -17,9 +17,25 @@ namespace OHOS { namespace NotificationNapi { + +const int SUBSRIBE_MAX_PARA = 3; + +struct AsyncCallbackInfoSubscribe { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = 0; + napi_deferred deferred; + SubscriberInstance *objectInfo = nullptr; + NotificationSubscriberInfo subscriberInfo; + bool isCallback = false; + int errorCode = 0; +}; + 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) { + + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype; // argv[0]:Subscriber @@ -45,7 +61,7 @@ napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[SUBSRIB napi_create_reference(env, argv[1], 1, &callback); } else if (valuetype == napi_object) { if (Common::GetNotificationSubscriberInfo(env, argv[1], subscriberInfo) == nullptr) { - ANS_LOGE("ParseParameters SubscriberInfo parse failed"); + ANS_LOGE("ParseParameters SubscriberInfo parse failed"); return nullptr; } } @@ -86,17 +102,17 @@ napi_value Subscribe(napi_env env, napi_callback_info info) napi_value argv[SUBSRIBE_MAX_PARA]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; SubscriberInstance *objectInfo = nullptr; NotificationSubscriberInfo subscriberInfo; if (ParseParameters(env, argv, argc, subscriberInfo, objectInfo, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } ANS_LOGI("Subscribe objectInfo = %{public}p", objectInfo); - AsyncCallbackInfoSubscribe *asynccallbackinfo = new AsyncCallbackInfoSubscribe{ + AsyncCallbackInfoSubscribe *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoSubscribe{ .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .subscriberInfo = subscriberInfo}; napi_value promise = 0; diff --git a/kits/napi/src/unsubscribe.cpp b/interfaces/kits/napi/ans/src/unsubscribe.cpp similarity index 89% rename from kits/napi/src/unsubscribe.cpp rename to interfaces/kits/napi/ans/src/unsubscribe.cpp index c911bba28d82b1ef11f8396295941b66e7682622..babc54fbfcae8f8f4ae6f8d95102869d644874ed 100644 --- a/kits/napi/src/unsubscribe.cpp +++ b/interfaces/kits/napi/ans/src/unsubscribe.cpp @@ -18,11 +18,25 @@ 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; + SubscriberInstance *objectInfo = nullptr; + bool isCallback = false; + int errorCode = 0; +}; + napi_value ParseParameters(const napi_env &env, const size_t &argc, const napi_value (&argv)[UNSUBSCRIBE_MAX_PARA], SubscriberInstance *&objectInfo, napi_ref &callback) { ANS_LOGI("ParseParameters start"); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_valuetype valuetype; // argv[0]:subscriber NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); @@ -74,16 +88,15 @@ napi_value Unsubscribe(napi_env env, napi_callback_info info) size_t argc = UNSUBSCRIBE_MAX_PARA; napi_value argv[UNSUBSCRIBE_MAX_PARA]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_ref callback = 0; SubscriberInstance *subscriberInstance = nullptr; if (ParseParameters(env, argc, argv, subscriberInstance, callback) == nullptr) { - return Common::NapiGetNull(env); + return Common::JSParaError(env, callback); } - AsyncCallbackInfoUnsubscribe *asynccallbackinfo = - new AsyncCallbackInfoUnsubscribe{.env = env, .asyncWork = nullptr, .objectInfo = subscriberInstance}; + AsyncCallbackInfoUnsubscribe *asynccallbackinfo = new (std::nothrow) + AsyncCallbackInfoUnsubscribe{.env = env, .asyncWork = nullptr, .objectInfo = subscriberInstance}; napi_value promise = 0; PaddingAsyncCallbackInfoIs(env, argc, asynccallbackinfo, callback, promise); @@ -113,7 +126,7 @@ napi_value Unsubscribe(napi_env env, napi_callback_info info) info.errorCode = asynccallbackinfo->errorCode; Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); - DelAsyncCallbackInfoOn(asynccallbackinfo->objectInfo); + DelAsyncCallbackInfo(asynccallbackinfo->objectInfo); napi_delete_async_work(env, asynccallbackinfo->asyncWork); if (asynccallbackinfo) { diff --git a/kits/wantAgent/BUILD.gn b/interfaces/kits/napi/wantagent/BUILD.gn similarity index 83% rename from kits/wantAgent/BUILD.gn rename to interfaces/kits/napi/wantagent/BUILD.gn index f492bb887bcfa2c36b1360f48e7e83dc7292f14d..8e9f83c18b137d5131cf8cbedeca5e3007a70d78 100644 --- a/kits/wantAgent/BUILD.gn +++ b/interfaces/kits/napi/wantagent/BUILD.gn @@ -11,6 +11,7 @@ # 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") ohos_shared_library("wantagent") { @@ -19,31 +20,28 @@ ohos_shared_library("wantagent") { "//third_party/node/src", "//foundation/aafwk/standard/services/common/include", "//utils/system/safwk/native/include", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/", "//foundation/aafwk/standard/interfaces/innerkits/want/include", - "//base/notification/ans_standard/kits/native/wantagent/include", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/context", "//third_party/libuv/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", "//foundation/aafwk/standard/services/common/include", "./", ] sources = [ - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/want_wrapper.cpp", "napi_want_agent.cpp", "native_module.cpp", ] deps = [ - "//base/notification/ans_standard/kits/native:ans_kits", - "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", diff --git a/kits/wantAgent/napi_want_agent.cpp b/interfaces/kits/napi/wantagent/napi_want_agent.cpp similarity index 66% rename from kits/wantAgent/napi_want_agent.cpp rename to interfaces/kits/napi/wantagent/napi_want_agent.cpp index fa5d3de14d8aff874a0b4dac6d188aa9ca719d21..f20c922342dc4b25e74df6a11a4eff992f81528d 100644 --- a/kits/wantAgent/napi_want_agent.cpp +++ b/interfaces/kits/napi/wantagent/napi_want_agent.cpp @@ -22,20 +22,7 @@ #include #include "hilog_wrapper.h" -#include "ohos/aafwk/base/base_interfaces.h" -#include "ohos/aafwk/base/array_wrapper.h" -#include "ohos/aafwk/base/base_object.h" -#include "ohos/aafwk/base/bool_wrapper.h" -#include "ohos/aafwk/base/byte_wrapper.h" -#include "ohos/aafwk/base/short_wrapper.h" -#include "ohos/aafwk/base/int_wrapper.h" -#include "ohos/aafwk/base/long_wrapper.h" -#include "ohos/aafwk/base/float_wrapper.h" -#include "ohos/aafwk/base/double_wrapper.h" -#include "ohos/aafwk/base/string_wrapper.h" -#include "ohos/aafwk/base/zchar_wrapper.h" - -#include "want_wrapper.h" +#include "napi_common.h" #include "want_agent_helper.h" namespace OHOS { @@ -106,7 +93,21 @@ void TriggerCompleteCallBack::OnSendFinished( result[0] = GetCallbackErrorResult(dataWorkerData->env, BUSINESS_ERROR_CODE_OK); napi_create_object(dataWorkerData->env, &result[1]); // wrap wantAgent + napi_value wantAgentClass = nullptr; + napi_define_class(dataWorkerData->env, + "WantAgentClass", + NAPI_AUTO_LENGTH, + [](napi_env env, napi_callback_info info) -> napi_value { + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; + }, + nullptr, + 0, + nullptr, + &wantAgentClass); napi_value jsWantAgent = nullptr; + napi_new_instance(dataWorkerData->env, wantAgentClass, 0, nullptr, &jsWantAgent); napi_wrap(dataWorkerData->env, jsWantAgent, (void *)dataWorkerData->wantAgent.get(), @@ -116,7 +117,7 @@ void TriggerCompleteCallBack::OnSendFinished( napi_set_named_property(dataWorkerData->env, result[1], "wantAgent", jsWantAgent); // wrap want napi_value jsWant; - jsWant = WrapWant(dataWorkerData->want, dataWorkerData->env); + jsWant = WrapWant(dataWorkerData->env, dataWorkerData->want); napi_set_named_property(dataWorkerData->env, result[1], "want", jsWant); // wrap finalCode napi_value jsFinalCode; @@ -129,7 +130,7 @@ void TriggerCompleteCallBack::OnSendFinished( napi_set_named_property(dataWorkerData->env, result[1], "finalData", jsFinalCode); // wrap extraInfo napi_value jsExtraInfo; - jsExtraInfo = WrapWantParam(dataWorkerData->resultExtras, dataWorkerData->env); + jsExtraInfo = WrapWantParams(dataWorkerData->env, dataWorkerData->resultExtras); napi_set_named_property(dataWorkerData->env, result[1], "extraInfo", jsExtraInfo); napi_get_undefined(dataWorkerData->env, &undefined); @@ -250,6 +251,7 @@ napi_value NAPI_GetBundleNameWrap( napi_delete_reference(env, asyncCallbackInfo->callback[0]); } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -283,6 +285,7 @@ napi_value NAPI_GetBundleNameWrap( napi_create_string_utf8(env, asyncCallbackInfo->bundleName.c_str(), NAPI_AUTO_LENGTH, &result); napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -297,16 +300,17 @@ napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) napi_value argv[argc]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}d]", argc); + + napi_valuetype wantAgentType; + napi_typeof(env, argv[0], &wantAgentType); + NAPI_ASSERT(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + Notification::WantAgent::WantAgent *pWantAgent = nullptr; - if (argv[0] == nullptr) { - HILOG_INFO("argv[0] is nullptr"); - } napi_unwrap(env, argv[0], (void **)&(pWantAgent)); if (pWantAgent == nullptr) { HILOG_INFO("Notification::WantAgent::WantAgent napi_unwrap error"); return NapiGetNull(env); } - std::shared_ptr wantAgent(pWantAgent); bool callBackMode = false; if (argc >= 2) { @@ -320,7 +324,7 @@ napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) if (asyncCallbackInfo == nullptr) { return NapiGetNull(env); } - asyncCallbackInfo->wantAgent = wantAgent; + asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); if (callBackMode) { napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); @@ -367,6 +371,7 @@ napi_value NAPI_GetUidWrap( napi_delete_reference(env, asyncCallbackInfo->callback[0]); } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -400,6 +405,7 @@ napi_value NAPI_GetUidWrap( napi_create_int32(env, asyncCallbackInfo->uid, &result); napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -415,12 +421,15 @@ napi_value NAPI_GetUid(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}d]", argc); + napi_valuetype wantAgentType; + napi_typeof(env, argv[0], &wantAgentType); + NAPI_ASSERT(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + Notification::WantAgent::WantAgent *pWantAgent = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgent)); if (pWantAgent == nullptr) { return NapiGetNull(env); } - std::shared_ptr wantAgent(pWantAgent); bool callBackMode = false; if (argc >= 2) { @@ -434,7 +443,7 @@ napi_value NAPI_GetUid(napi_env env, napi_callback_info info) if (asyncCallbackInfo == nullptr) { return NapiGetNull(env); } - asyncCallbackInfo->wantAgent = wantAgent; + asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); if (callBackMode) { napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); @@ -472,7 +481,7 @@ napi_value NAPI_GetWantWrap( napi_value callResult = 0; result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); - result[1] = WrapWant(*(asyncCallbackInfo->want), env); + 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); @@ -480,6 +489,7 @@ napi_value NAPI_GetWantWrap( napi_delete_reference(env, asyncCallbackInfo->callback[0]); } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -510,9 +520,10 @@ napi_value NAPI_GetWantWrap( HILOG_INFO("GetWant compeleted(Promise Mode)..."); AsyncGetWantCallbackInfo *asyncCallbackInfo = (AsyncGetWantCallbackInfo *)data; napi_value result; - result = WrapWant(*(asyncCallbackInfo->want), env); + result = WrapWant(env, *(asyncCallbackInfo->want)); napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -528,12 +539,15 @@ napi_value NAPI_GetWant(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}d]", argc); + napi_valuetype wantAgentType; + napi_typeof(env, argv[0], &wantAgentType); + NAPI_ASSERT(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + Notification::WantAgent::WantAgent *pWantAgent = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgent)); if (pWantAgent == nullptr) { return NapiGetNull(env); } - std::shared_ptr wantAgent(pWantAgent); bool callBackMode = false; if (argc >= 2) { @@ -547,7 +561,7 @@ napi_value NAPI_GetWant(napi_env env, napi_callback_info info) if (asyncCallbackInfo == nullptr) { return NapiGetNull(env); } - asyncCallbackInfo->wantAgent = wantAgent; + asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); if (callBackMode) { napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); @@ -560,6 +574,22 @@ napi_value NAPI_GetWant(napi_env env, napi_callback_info info) return ((callBackMode) ? (NapiGetNull(env)) : (ret)); } +void DeleteRecordByCode(const int32_t code) +{ + std::lock_guard guard(g_mutex); + for (const auto &item : g_WantAgentMap) { + auto code_ = item.second; + auto record = item.first; + if (code_ == code) { + g_WantAgentMap.erase(record); + if (record != nullptr) { + delete record; + record = nullptr; + } + } + } +} + napi_value NAPI_CancelWrap( napi_env env, napi_callback_info info, bool callBackMode, AsyncCancelCallbackInfo *asyncCallbackInfo) { @@ -575,6 +605,8 @@ napi_value NAPI_CancelWrap( HILOG_INFO("Cancel called(CallBack Mode)..."); AsyncCancelCallbackInfo *asyncCallbackInfo = (AsyncCancelCallbackInfo *)data; WantAgentHelper::Cancel(asyncCallbackInfo->wantAgent); + int32_t code = WantAgentHelper::GetHashCode(asyncCallbackInfo->wantAgent); + DeleteRecordByCode(code); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("Cancel compeleted(CallBack Mode)..."); @@ -594,6 +626,7 @@ napi_value NAPI_CancelWrap( napi_delete_reference(env, asyncCallbackInfo->callback[0]); } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -619,6 +652,8 @@ napi_value NAPI_CancelWrap( HILOG_INFO("Cancel called(Promise Mode)..."); AsyncCancelCallbackInfo *asyncCallbackInfo = (AsyncCancelCallbackInfo *)data; WantAgentHelper::Cancel(asyncCallbackInfo->wantAgent); + int32_t code = WantAgentHelper::GetHashCode(asyncCallbackInfo->wantAgent); + DeleteRecordByCode(code); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("Cancel compeleted(Promise Mode)..."); @@ -627,6 +662,7 @@ napi_value NAPI_CancelWrap( napi_get_null(env, &result); napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -642,12 +678,15 @@ napi_value NAPI_Cancel(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}d]", argc); + napi_valuetype wantAgentType; + napi_typeof(env, argv[0], &wantAgentType); + NAPI_ASSERT(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + Notification::WantAgent::WantAgent *pWantAgent = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgent)); if (pWantAgent == nullptr) { return NapiGetNull(env); } - std::shared_ptr wantAgent(pWantAgent); bool callBackMode = false; if (argc >= 2) { @@ -661,7 +700,7 @@ napi_value NAPI_Cancel(napi_env env, napi_callback_info info) if (asyncCallbackInfo == nullptr) { return NapiGetNull(env); } - asyncCallbackInfo->wantAgent = wantAgent; + asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); if (callBackMode) { napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); @@ -697,6 +736,7 @@ napi_value NAPI_TriggerWrap(napi_env env, napi_callback_info info, AsyncTriggerC HILOG_INFO("Trigger compeleted ..."); AsyncTriggerCallbackInfo *asyncCallbackInfo = (AsyncTriggerCallbackInfo *)data; napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -715,12 +755,15 @@ napi_value NAPI_Trigger(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}d]", argc); + napi_valuetype wantAgentType; + napi_typeof(env, argv[0], &wantAgentType); + NAPI_ASSERT(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + Notification::WantAgent::WantAgent *pWantAgent = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgent)); if (pWantAgent == nullptr) { return NapiGetNull(env); } - std::shared_ptr wantAgent(pWantAgent); // Get triggerInfo napi_value jsTriggerInfo = argv[1]; @@ -730,27 +773,31 @@ napi_value NAPI_Trigger(napi_env env, napi_callback_info info) // Get triggerInfo code int32_t code = -1; - if (!GetInt32ByPropertyName(env, jsTriggerInfo, "code", code)) { + if (!UnwrapInt32ByPropertyName(env, jsTriggerInfo, "code", code)) { return NapiGetNull(env); } // Get triggerInfo want napi_value jsWant = nullptr; - jsWant = GetObjectByPropertyName(env, jsTriggerInfo, "want"); + jsWant = GetPropertyValueByPropertyName(env, jsTriggerInfo, "want", napi_object); std::shared_ptr want = nullptr; if (jsWant != nullptr) { want = std::make_shared(); - WantAgentUnwrapWant(*want, env, jsWant); + if (!UnwrapWant(env, jsWant, *want)) { + return NapiGetNull(env); + } } // Get triggerInfo permission std::string permission; - GetStringByPropertyName(env, jsTriggerInfo, "permission", permission); + UnwrapStringByPropertyName(env, jsTriggerInfo, "permission", permission); // Get triggerInfo extraInfo napi_value jsExtraInfo = nullptr; - jsExtraInfo = GetObjectByPropertyName(env, jsTriggerInfo, "extraInfo"); + jsExtraInfo = GetPropertyValueByPropertyName(env, jsTriggerInfo, "extraInfo", napi_object); std::shared_ptr extraInfo = nullptr; if (jsExtraInfo != nullptr) { extraInfo = std::make_shared(); - UnwrapWantParam(*extraInfo, env, jsExtraInfo); + if (!UnwrapWantParams(env, jsExtraInfo, *extraInfo)) { + return NapiGetNull(env); + } } // Get context napi_value global = 0; @@ -774,7 +821,7 @@ napi_value NAPI_Trigger(napi_env env, napi_callback_info info) if (asyncCallbackInfo == nullptr) { return NapiGetNull(env); } - asyncCallbackInfo->wantAgent = wantAgent; + asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); asyncCallbackInfo->context = context; Notification::WantAgent::TriggerInfo triggerInfo(permission, extraInfo, want, code); asyncCallbackInfo->triggerInfo = triggerInfo; @@ -828,6 +875,7 @@ napi_value NAPI_EqualWrap( napi_delete_reference(env, asyncCallbackInfo->callback[0]); } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -862,6 +910,7 @@ napi_value NAPI_EqualWrap( napi_get_boolean(env, asyncCallbackInfo->result, &result); napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -877,19 +926,25 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}d]", argc); + napi_valuetype wantAgentFirstType; + napi_typeof(env, argv[0], &wantAgentFirstType); + NAPI_ASSERT(env, wantAgentFirstType == napi_object, "Wrong argument type. Object expected."); + Notification::WantAgent::WantAgent *pWantAgentFirst = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgentFirst)); if (pWantAgentFirst == nullptr) { return NapiGetNull(env); } - std::shared_ptr wantAgentFirst(pWantAgentFirst); + + napi_valuetype wantAgentSecondType; + napi_typeof(env, argv[1], &wantAgentSecondType); + NAPI_ASSERT(env, wantAgentSecondType == napi_object, "Wrong argument type. Object expected."); Notification::WantAgent::WantAgent *pWantAgentSecond = nullptr; napi_unwrap(env, argv[1], (void **)&(pWantAgentSecond)); if (pWantAgentSecond == nullptr) { return NapiGetNull(env); } - std::shared_ptr wantAgentSecond(pWantAgentSecond); bool callBackMode = false; if (argc >= 3) { @@ -903,8 +958,8 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info) if (asyncCallbackInfo == nullptr) { return NapiGetNull(env); } - asyncCallbackInfo->wantAgentFirst = wantAgentFirst; - asyncCallbackInfo->wantAgentSecond = wantAgentSecond; + asyncCallbackInfo->wantAgentFirst = std::make_shared(*pWantAgentFirst); + asyncCallbackInfo->wantAgentSecond = std::make_shared(*pWantAgentSecond); if (callBackMode) { napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); @@ -917,356 +972,6 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info) return ((callBackMode) ? (NapiGetNull(env)) : (ret)); } -std::string NapiGetStringParam(const AAFwk::WantParams &extraInfo, const std::string &key) -{ - auto value = extraInfo.GetParam(key); - AAFwk::IString *ao = AAFwk::IString::Query(value); - if (ao != nullptr) { - return AAFwk::String::Unbox(ao); - } - return std::string(); -} - -bool NapiGetBoolParam(const AAFwk::WantParams &extraInfo, const std::string &key, bool defaultValue) -{ - auto value = extraInfo.GetParam(key); - AAFwk::IBoolean *bo = AAFwk::IBoolean::Query(value); - if (bo != nullptr) { - return AAFwk::Boolean::Unbox(bo); - } - return defaultValue; -} - -short NapiGetShortParam(const AAFwk::WantParams &extraInfo, const std::string &key, short defaultValue) -{ - auto value = extraInfo.GetParam(key); - AAFwk::IShort *ao = AAFwk::IShort::Query(value); - if (ao != nullptr) { - return AAFwk::Short::Unbox(ao); - } - return defaultValue; -} - -int NapiGetIntParam(const AAFwk::WantParams &extraInfo, const std::string &key, const int defaultValue) -{ - auto value = extraInfo.GetParam(key); - AAFwk::IInteger *ao = AAFwk::IInteger::Query(value); - if (ao != nullptr) { - return AAFwk::Integer::Unbox(ao); - } - return defaultValue; -} - -long NapiGetLongParam(const AAFwk::WantParams &extraInfo, const std::string &key, long defaultValue) -{ - auto value = extraInfo.GetParam(key); - AAFwk::ILong *ao = AAFwk::ILong::Query(value); - if (ao != nullptr) { - return AAFwk::Long::Unbox(ao); - } - return defaultValue; -} - -float NapiGetFloatParam(const AAFwk::WantParams &extraInfo, const std::string &key, float defaultValue) -{ - auto value = extraInfo.GetParam(key); - AAFwk::IFloat *ao = AAFwk::IFloat::Query(value); - if (ao != nullptr) { - return AAFwk::Float::Unbox(ao); - } - return defaultValue; -} - -double NapiGetDoubleParam(const AAFwk::WantParams &extraInfo, const std::string &key, double defaultValue) -{ - auto value = extraInfo.GetParam(key); - AAFwk::IDouble *ao = AAFwk::IDouble::Query(value); - if (ao != nullptr) { - return AAFwk::Double::Unbox(ao); - } - return defaultValue; -} - -napi_value WrapWantParam(const AAFwk::WantParams &extraInfo, napi_env env) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_value jsParam = nullptr; - napi_value proValue = nullptr; - NAPI_CALL(env, napi_create_object(env, &jsParam)); - const std::map> paramList = extraInfo.GetParams(); - for (auto iter = paramList.begin(); iter != paramList.end(); iter++) { - proValue = nullptr; - if (AAFwk::IString::Query(iter->second) != nullptr) { - std::string nativeValue = NapiGetStringParam(extraInfo, iter->first); - HILOG_INFO("%{public}s, %{public}s=%{public}s", __func__, iter->first.c_str(), nativeValue.c_str()); - if (napi_create_string_utf8(env, nativeValue.c_str(), NAPI_AUTO_LENGTH, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::IBoolean::Query(iter->second) != nullptr) { - bool natvieValue = NapiGetBoolParam(extraInfo, iter->first, false); - if (napi_get_boolean(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::IShort::Query(iter->second) != nullptr) { - short natvieValue = NapiGetShortParam(extraInfo, iter->first, 0); - if (napi_create_int32(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::IInteger::Query(iter->second) != nullptr) { - int natvieValue = NapiGetIntParam(extraInfo, iter->first, 0); - if (napi_create_int32(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::ILong::Query(iter->second) != nullptr) { - long natvieValue = NapiGetLongParam(extraInfo, iter->first, 0); - if (napi_create_int64(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::IFloat::Query(iter->second) != nullptr) { - float natvieValue = NapiGetFloatParam(extraInfo, iter->first, 0.0); - if (napi_create_double(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::IDouble::Query(iter->second) != nullptr) { - double natvieValue = NapiGetDoubleParam(extraInfo, iter->first, 0.0); - if (napi_create_double(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else { - AAFwk::IArray *ao = AAFwk::IArray::Query(iter->second); - if (ao != nullptr) { - sptr array(ao); - WrapWantParamArray(extraInfo, env, iter->first, array, jsParam); - } - } - } - return jsParam; -} - -napi_value UnwrapWantParam(AAFwk::WantParams &extraInfo, napi_env env, napi_value JsExtraInfo) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_valuetype valueType = napi_undefined; - napi_value proNameList = 0; - uint32_t proCount = 0; - - NAPI_CALL(env, napi_get_property_names(env, JsExtraInfo, &proNameList)); - NAPI_CALL(env, napi_get_array_length(env, proNameList, &proCount)); - HILOG_INFO("UnwrapWantParam property size=%{public}d", proCount); - - napi_value proName = 0; - napi_value proValue = 0; - for (uint32_t index = 0; index < proCount; index++) { - NAPI_CALL(env, napi_get_element(env, proNameList, index, &proName)); - std::string strProName = NapiValueToStringUtf8(env, proName); - HILOG_INFO("UnwrapWantParam proName=%{public}s", strProName.c_str()); - NAPI_CALL(env, napi_get_named_property(env, JsExtraInfo, strProName.c_str(), &proValue)); - NAPI_CALL(env, napi_typeof(env, proValue, &valueType)); - switch (valueType) { - case napi_string: { - std::string str_pro_value = NapiValueToStringUtf8(env, proValue); - HILOG_INFO("UnwrapWantParam proValue=%{public}s", str_pro_value.c_str()); - extraInfo.SetParam(strProName, AAFwk::String::Box(str_pro_value)); - break; - } - case napi_boolean: { - bool c_pro_value = false; - NAPI_CALL(env, napi_get_value_bool(env, proValue, &c_pro_value)); - HILOG_INFO("UnwrapWantParam proValue=%{public}d", c_pro_value); - extraInfo.SetParam(strProName, AAFwk::Boolean::Box(c_pro_value)); - break; - } - case napi_number: { - int32_t c_pro_value32 = 0; - double c_pro_value_double = 0.0; - - if (napi_get_value_int32(env, proValue, &c_pro_value32) == napi_ok) { - HILOG_INFO("UnwrapWantParam proValue=%{public}d", c_pro_value32); - extraInfo.SetParam(strProName, AAFwk::Integer::Box(c_pro_value32)); - break; - } - if (napi_get_value_double(env, proValue, &c_pro_value_double) == napi_ok) { - HILOG_INFO("UnwrapWantParam proValue=%{public}lf", c_pro_value_double); - extraInfo.SetParam(strProName, AAFwk::Double::Box(c_pro_value_double)); - break; - } - HILOG_INFO("UnwrapWantParam unknown proValue of Number"); - break; - } - default: { - if (UnwrapWantParamArray(extraInfo, env, strProName, proValue) == nullptr) { - return nullptr; - } - } - } - } - napi_value result; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - -void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value) -{ - long size = value.size(); - sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IString); - if (ao == nullptr) { - return; - } - for (long i = 0; i < size; i++) { - ao->Set(i, AAFwk::String::Box(value[i])); - } - extraInfo.SetParam(key, ao); -} - -void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value) -{ - long size = value.size(); - sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IInteger); - if (ao == nullptr) { - return; - } - for (long i = 0; i < size; i++) { - ao->Set(i, AAFwk::Integer::Box(value[i])); - } - extraInfo.SetParam(key, ao); -} - -void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value) -{ - long size = value.size(); - sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_ILong); - if (ao == nullptr) { - return; - } - for (long i = 0; i < size; i++) { - ao->Set(i, AAFwk::Long::Box(value[i])); - } - extraInfo.SetParam(key, ao); -} - -void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value) -{ - long size = value.size(); - sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IBoolean); - if (ao != nullptr) { - for (long i = 0; i < size; i++) { - ao->Set(i, AAFwk::Boolean::Box(value[i])); - } - extraInfo.SetParam(key, ao); - } -} - -void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value) -{ - long size = value.size(); - sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IDouble); - if (ao == nullptr) { - return; - } - for (long i = 0; i < size; i++) { - ao->Set(i, AAFwk::Double::Box(value[i])); - } - extraInfo.SetParam(key, ao); -} - -napi_value UnwrapWantParamArray(AAFwk::WantParams &extraInfo, napi_env env, std::string strProName, napi_value proValue) -{ - HILOG_INFO("%{public}s,called", __func__); - bool isArray = false; - uint32_t arrayLength = 0; - napi_value valueAry = 0; - napi_valuetype valueAryType = napi_undefined; - - NAPI_CALL(env, napi_is_array(env, proValue, &isArray)); - NAPI_CALL(env, napi_get_array_length(env, proValue, &arrayLength)); - HILOG_INFO("UnwrapWantParam proValue is array, length=%{public}d", arrayLength); - - std::vector stringList; - std::vector intList; - std::vector longList; - std::vector boolList; - std::vector doubleList; - bool isDouble = false; - for (uint32_t j = 0; j < arrayLength; j++) { - NAPI_CALL(env, napi_get_element(env, proValue, j, &valueAry)); - NAPI_CALL(env, napi_typeof(env, valueAry, &valueAryType)); - switch (valueAryType) { - case napi_string: { - std::string str_ary_value = NapiValueToStringUtf8(env, valueAry); - HILOG_INFO("UnwrapWantParam string array proValue=%{public}s", str_ary_value.c_str()); - stringList.push_back(str_ary_value); - break; - } - case napi_boolean: { - bool c_ary_value = false; - NAPI_CALL(env, napi_get_value_bool(env, valueAry, &c_ary_value)); - HILOG_INFO("UnwrapWantParam bool array proValue=%{public}d", c_ary_value); - boolList.push_back(c_ary_value); - break; - } - case napi_number: { - int32_t c_ary_value32 = 0; - int64_t c_ary_value64 = 0; - double c_ary_value_double = 0.0; - if (isDouble) { - if (napi_get_value_double(env, valueAry, &c_ary_value_double) == napi_ok) { - HILOG_INFO("UnwrapWantParam double array proValue=%{public}lf", c_ary_value_double); - doubleList.push_back(c_ary_value_double); - } - break; - } else { - if (napi_get_value_int32(env, valueAry, &c_ary_value32) == napi_ok) { - HILOG_INFO("UnwrapWantParam int array proValue=%{public}d", c_ary_value32); - intList.push_back(c_ary_value32); - break; - } - } - - if (napi_get_value_int64(env, valueAry, &c_ary_value64) == napi_ok) { - HILOG_INFO("UnwrapWantParam int64 array proValue=%{public}lld", c_ary_value64); - longList.push_back(c_ary_value64); - break; - } - if (napi_get_value_double(env, valueAry, &c_ary_value_double) == napi_ok) { - HILOG_INFO("UnwrapWantParam double array proValue=%{public}lf", c_ary_value_double); - isDouble = true; - if (intList.size() > 0) { - for (int k = 0; k < (int)intList.size(); k++) { - doubleList.push_back(intList[k]); - } - intList.clear(); - } - doubleList.push_back(c_ary_value_double); - break; - } - HILOG_INFO("UnwrapWantParam array unkown Number"); - break; - } - default: - HILOG_INFO("UnwrapWantParam array unkown"); - break; - } - } - if (stringList.size() > 0) { - SetParam(extraInfo, strProName, stringList); - } - if (intList.size() > 0) { - SetParam(extraInfo, strProName, intList); - } - if (longList.size() > 0) { - SetParam(extraInfo, strProName, longList); - } - if (boolList.size() > 0) { - SetParam(extraInfo, strProName, boolList); - } - if (doubleList.size() > 0) { - SetParam(extraInfo, strProName, doubleList); - } - napi_value result; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - napi_value NAPI_GetWantAgentWrap( napi_env env, napi_callback_info info, bool callBackMode, AsyncGetWantAgentCallbackInfo *asyncCallbackInfo) { @@ -1288,6 +993,12 @@ napi_value NAPI_GetWantAgentWrap( asyncCallbackInfo->extraInfo); asyncCallbackInfo->wantAgent = Notification::WantAgent::WantAgentHelper::GetWantAgent(asyncCallbackInfo->context, wantAgentInfo); + if (asyncCallbackInfo->wantAgent == nullptr) { + HILOG_INFO("GetWantAgent instance is nullptr..."); + } + int32_t code = Notification::WantAgent::WantAgentHelper::GetHashCode(asyncCallbackInfo->wantAgent); + std::lock_guard guard(g_mutex); + g_WantAgentMap.emplace(asyncCallbackInfo, code); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetWantAgent compeleted(CallBack Mode)..."); @@ -1364,9 +1075,10 @@ napi_value NAPI_GetWantAgentWrap( Notification::WantAgent::WantAgentHelper::GetWantAgent(asyncCallbackInfo->context, wantAgentInfo); if (asyncCallbackInfo->wantAgent == nullptr) { HILOG_INFO("GetWantAgent instance is nullptr..."); - } else { - HILOG_INFO("GetWantAgent instance is not nullptr..."); } + int32_t code = Notification::WantAgent::WantAgentHelper::GetHashCode(asyncCallbackInfo->wantAgent); + std::lock_guard guard(g_mutex); + g_WantAgentMap.emplace(asyncCallbackInfo, code); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetWantAgent compeleted(Promise Mode)..."); @@ -1402,45 +1114,6 @@ napi_value NAPI_GetWantAgentWrap( } } -napi_value WantAgentUnwrapWant(Want ¶m, napi_env env, napi_value jsWant) -{ - HILOG_INFO("%{public}s,called", __func__); - // unwrap the param - napi_valuetype valueType = napi_undefined; - NAPI_CALL(env, napi_typeof(env, jsWant, &valueType)); - if (valueType != napi_object) { - return nullptr; - } - std::string strValue; - // get want action property - if (GetStringByPropertyName(env, jsWant, "action", strValue)) { - param.SetAction(strValue); - } - // get want entities property - std::vector nativeStringList; - GetStringArrayByPropertyName(env, jsWant, "entities", nativeStringList); - for (size_t i = 0; i < nativeStringList.size(); i++) { - param.AddEntity(nativeStringList[i]); - } - // get want type property - if (GetStringByPropertyName(env, jsWant, "type", strValue)) { - param.SetType(strValue); - } - // get want flags property(WantOptions in want.d.ts) - GetWantOptions(env, jsWant, "options", param); - // get want uri property - if (GetStringByPropertyName(env, jsWant, "uri", strValue)) { - param.SetUri(strValue); - } - // get elementName property - UnwrapElementName(param, env, jsWant); - // get want param (optional) - UnwrapWantParam(param, env, jsWant); - napi_value result; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) { size_t argc = 2; @@ -1454,7 +1127,7 @@ napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) NAPI_ASSERT(env, jsWantAgentInfoType == napi_object, "param type mismatch!"); napi_value jsWants = nullptr; - jsWants = GetObjectByPropertyName(env, jsWantAgentInfo, "wants"); + jsWants = GetPropertyValueByPropertyName(env, jsWantAgentInfo, "wants", napi_object); if (jsWants == nullptr) { return NapiGetNull(env); } @@ -1475,24 +1148,27 @@ napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) std::shared_ptr want = std::make_shared(); napi_value jsWant; napi_get_element(env, jsWants, i, &jsWant); - WantAgentUnwrapWant(*want, env, jsWant); + if (!UnwrapWant(env, jsWant, *want)) { + return NapiGetNull(env); + } HILOG_INFO("want type is [%{public}s]", want->GetType().c_str()); wants.emplace_back(want); } // Get operationType int32_t operationType = -1; - if (!GetInt32ByPropertyName(env, jsWantAgentInfo, "operationType", operationType)) { + if (!UnwrapInt32ByPropertyName(env, jsWantAgentInfo, "operationType", operationType)) { return NapiGetNull(env); } // Get requestCode int32_t requestCode = -1; - if (!GetInt32ByPropertyName(env, jsWantAgentInfo, "requestCode", requestCode)) { + if (!UnwrapInt32ByPropertyName(env, jsWantAgentInfo, "requestCode", requestCode)) { return NapiGetNull(env); } // Get wantAgentFlags napi_value JsWantAgentFlags = nullptr; std::vector wantAgentFlags; - JsWantAgentFlags = GetObjectByPropertyName(env, jsWantAgentInfo, "wantAgentFlags"); + JsWantAgentFlags = GetPropertyValueByPropertyName(env, jsWantAgentInfo, "wantAgentFlags", napi_object); + HILOG_INFO("NAPI_GetWantAgent8"); if (JsWantAgentFlags != nullptr) { uint32_t arrayLength = 0; NAPI_CALL(env, napi_get_array_length(env, JsWantAgentFlags, &arrayLength)); @@ -1510,10 +1186,12 @@ napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) } // Get extraInfo napi_value JsExtraInfo = nullptr; - JsExtraInfo = GetObjectByPropertyName(env, jsWantAgentInfo, "extraInfo"); + JsExtraInfo = GetPropertyValueByPropertyName(env, jsWantAgentInfo, "extraInfo", napi_object); AAFwk::WantParams extraInfo; if (JsExtraInfo != nullptr) { - UnwrapWantParam(extraInfo, env, JsExtraInfo); + if (!UnwrapWantParams(env, JsExtraInfo, extraInfo)) { + return NapiGetNull(env); + } } // Get context napi_value global = 0; @@ -1575,168 +1253,4 @@ napi_value NapiGetNull(napi_env env) return result; } -std::vector GetStringArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key) -{ - std::vector array; - auto value = extraInfo.GetParam(key); - AAFwk::IArray *ao = AAFwk::IArray::Query(value); - if (ao != nullptr && AAFwk::Array::IsStringArray(ao)) { - auto func = [&](AAFwk::IInterface *object) { - if (object != nullptr) { - AAFwk::IString *value = AAFwk::IString::Query(object); - if (value != nullptr) { - array.push_back(AAFwk::String::Unbox(value)); - } - } - }; - AAFwk::Array::ForEach(ao, func); - } - return array; -} - -std::vector GetBoolArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key) -{ - std::vector array; - auto value = extraInfo.GetParam(key); - AAFwk::IArray *ao = AAFwk::IArray::Query(value); - if (ao != nullptr && AAFwk::Array::IsBooleanArray(ao)) { - auto func = [&](AAFwk::IInterface *object) { - if (object != nullptr) { - AAFwk::IBoolean *value = AAFwk::IBoolean::Query(object); - if (value != nullptr) { - array.push_back(AAFwk::Boolean::Unbox(value)); - } - } - }; - - AAFwk::Array::ForEach(ao, func); - } - return array; -} - -std::vector GetIntArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key) -{ - std::vector array; - auto value = extraInfo.GetParam(key); - AAFwk::IArray *ao = AAFwk::IArray::Query(value); - if (ao != nullptr && AAFwk::Array::IsIntegerArray(ao)) { - auto func = [&](AAFwk::IInterface *object) { - if (object != nullptr) { - AAFwk::IInteger *value = AAFwk::IInteger::Query(object); - if (value != nullptr) { - array.push_back(AAFwk::Integer::Unbox(value)); - } - } - }; - AAFwk::Array::ForEach(ao, func); - } - return array; -} - -std::vector GetLongArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key) -{ - std::vector array; - auto value = extraInfo.GetParam(key); - AAFwk::IArray *ao = AAFwk::IArray::Query(value); - if (ao != nullptr && AAFwk::Array::IsLongArray(ao)) { - auto func = [&](AAFwk::IInterface *object) { - if (object != nullptr) { - AAFwk::ILong *value = AAFwk::ILong::Query(object); - if (value != nullptr) { - array.push_back(AAFwk::Long::Unbox(value)); - } - } - }; - AAFwk::Array::ForEach(ao, func); - } - return array; -} - -std::vector GetDoubleArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key) -{ - std::vector array; - auto value = extraInfo.GetParam(key); - AAFwk::IArray *ao = AAFwk::IArray::Query(value); - if (ao != nullptr && AAFwk::Array::IsDoubleArray(ao)) { - auto func = [&](AAFwk::IInterface *object) { - if (object != nullptr) { - AAFwk::IDouble *value = AAFwk::IDouble::Query(object); - if (value != nullptr) { - array.push_back(AAFwk::Double::Unbox(value)); - } - } - }; - AAFwk::Array::ForEach(ao, func); - } - return array; -} - -void WrapWantParamArray(const AAFwk::WantParams &extraInfo, napi_env env, const std::string &key, - sptr &ao, napi_value jsObject) -{ - napi_value jsArray = nullptr; - napi_value proValue = nullptr; - if (AAFwk::Array::IsStringArray(ao)) { - std::vector nativeValue = GetStringArrayParam(extraInfo, key); - if (napi_create_array(env, &jsArray) != napi_ok) { - return; - } - for (uint32_t i = 0; i < nativeValue.size(); i++) { - proValue = nullptr; - if (napi_create_string_utf8(env, nativeValue[i].c_str(), NAPI_AUTO_LENGTH, &proValue) == napi_ok) { - napi_set_element(env, jsArray, i, proValue); - } - } - napi_set_named_property(env, jsObject, key.c_str(), jsArray); - } else if (AAFwk::Array::IsBooleanArray(ao)) { - std::vector nativeValue = GetBoolArrayParam(extraInfo, key); - if (napi_create_array(env, &jsArray) != napi_ok) { - return; - } - for (uint32_t i = 0; i < nativeValue.size(); i++) { - proValue = nullptr; - if (napi_get_boolean(env, nativeValue[i], &proValue) == napi_ok) { - napi_set_element(env, jsArray, i, proValue); - } - } - napi_set_named_property(env, jsObject, key.c_str(), jsArray); - } else if (AAFwk::Array::IsIntegerArray(ao)) { - std::vector nativeValue = GetIntArrayParam(extraInfo, key); - if (napi_create_array(env, &jsArray) != napi_ok) { - return; - } - for (uint32_t i = 0; i < nativeValue.size(); i++) { - proValue = nullptr; - if (napi_create_int32(env, nativeValue[i], &proValue) == napi_ok) { - napi_set_element(env, jsArray, i, proValue); - } - } - napi_set_named_property(env, jsObject, key.c_str(), jsArray); - } else if (AAFwk::Array::IsLongArray(ao)) { - std::vector nativeValue = GetLongArrayParam(extraInfo, key); - if (napi_create_array(env, &jsArray) != napi_ok) { - return; - } - for (uint32_t i = 0; i < nativeValue.size(); i++) { - proValue = nullptr; - if (napi_create_int64(env, nativeValue[i], &proValue) == napi_ok) { - napi_set_element(env, jsArray, i, proValue); - } - } - napi_set_named_property(env, jsObject, key.c_str(), jsArray); - } else if (AAFwk::Array::IsDoubleArray(ao)) { - std::vector nativeValue = GetDoubleArrayParam(extraInfo, key); - if (napi_create_array(env, &jsArray) != napi_ok) { - return; - } - for (uint32_t i = 0; i < nativeValue.size(); i++) { - proValue = nullptr; - if (napi_create_double(env, nativeValue[i], &proValue) == napi_ok) { - napi_set_element(env, jsArray, i, proValue); - } - } - napi_set_named_property(env, jsObject, key.c_str(), jsArray); - } -} - } // namespace OHOS \ No newline at end of file diff --git a/kits/wantAgent/napi_want_agent.h b/interfaces/kits/napi/wantagent/napi_want_agent.h similarity index 69% rename from kits/wantAgent/napi_want_agent.h rename to interfaces/kits/napi/wantagent/napi_want_agent.h index 1bc73ad7c1bdf648ef15e54e65211c5db663b1ef..90b67e8e97b31fe8d546b49ba421d6fe4d8e5ca3 100644 --- a/kits/wantAgent/napi_want_agent.h +++ b/interfaces/kits/napi/wantagent/napi_want_agent.h @@ -16,6 +16,10 @@ #ifndef NAPI_WANT_AGENT_H #define NAPI_WANT_AGENT_H +#include +#include +#include + #include "napi/native_common.h" #include "napi/native_node_api.h" @@ -153,33 +157,11 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info); napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info); napi_value GetCallbackErrorResult(napi_env env, int errCode); -napi_value WrapWantParam(const AAFwk::WantParams &extraInfo, napi_env env); -napi_value UnwrapWantParamArray( - AAFwk::WantParams &extraInfo, napi_env env, std::string strProName, napi_value proValue); -napi_value UnwrapWantParam(AAFwk::WantParams &extraInfo, napi_env env, napi_value JsExtraInfo); napi_value NapiGetNull(napi_env env); -napi_value WantAgentUnwrapWant(Want ¶m, napi_env env, napi_value jsWant); - -std::string NapiGetStringParam(const AAFwk::WantParams &extraInfo, const std::string &key); -bool NapiGetBoolParam(const AAFwk::WantParams &extraInfo, const std::string &key, bool defaultValue); -short NapiGetShortParam(const AAFwk::WantParams &extraInfo, const std::string &key, short defaultValue); -int NapiGetIntParam(const AAFwk::WantParams &extraInfo, const std::string &key, const int defaultValue); -long NapiGetLongParam(const AAFwk::WantParams &extraInfo, const std::string &key, long defaultValue); -float NapiGetFloatParam(const AAFwk::WantParams &extraInfo, const std::string &key, float defaultValue); -double NapiGetDoubleParam(const AAFwk::WantParams &extraInfo, const std::string &key, double defaultValue); - -void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value); -void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value); -void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value); -void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value); -void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value); -void WrapWantParamArray(const AAFwk::WantParams &extraInfo, napi_env env, const std::string &key, - sptr &ao, napi_value jsObject); -std::vector GetStringArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key); -std::vector GetBoolArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key); -std::vector GetIntArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key); -std::vector GetLongArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key); -std::vector GetDoubleArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key); + +void DeleteRecordByCode(const int32_t code); +static std::map g_WantAgentMap; +static std::recursive_mutex g_mutex; } // namespace OHOS #endif // NAPI_WANT_AGENT_H diff --git a/kits/wantAgent/native_module.cpp b/interfaces/kits/napi/wantagent/native_module.cpp similarity index 100% rename from kits/wantAgent/native_module.cpp rename to interfaces/kits/napi/wantagent/native_module.cpp diff --git a/kits/napi/include/publish.h b/kits/napi/include/publish.h deleted file mode 100644 index 69f94d70fad7089d713498e9f84a0204f45253fa..0000000000000000000000000000000000000000 --- a/kits/napi/include/publish.h +++ /dev/null @@ -1,75 +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_PUBLISH_H -#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H - -#include -#include "common.h" - -static const int32_t PUBLISH_NOTIFICATION_MAX = 2; - -namespace OHOS { -namespace NotificationNapi { -struct AsyncCallbackInfoPublish { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = 0; - napi_deferred deferred; - NotificationRequest notificationRequest; - std::string lable; - bool isCallback = false; - bool isPublishNotificationTwoPara = false; - int errorCode = 0; -}; - -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; - std::string lable; - napi_ref callback; -}; - -napi_value ParseParametersByPublish(ParseParametersPublish &parseParameters, - const napi_value (&argv)[PUBLISH_NOTIFICATION_MAX], NotificationRequest ¬ificationRequest); -void PaddingCallbackInfoInfoPublish(AsyncCallbackInfoPublish *&asynccallbackinfo, - const ParseParametersPublish &parseParameters, const NotificationRequest ¬ificationRequest); -void PaddingPublishCallbackPromise(const napi_env &env, const ParseParametersPublish &parseParameters, - AsyncCallbackInfoPublish *&asynccallbackinfo, napi_value &promise); -napi_value Publish(napi_env env, napi_callback_info info); -} // namespace NotificationNapi -} // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H \ No newline at end of file diff --git a/kits/napi/include/slot.h b/kits/napi/include/slot.h deleted file mode 100644 index 8644cb2e465294ed3ac7bbc334e67f6c2edecabd..0000000000000000000000000000000000000000 --- a/kits/napi/include/slot.h +++ /dev/null @@ -1,120 +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_SLOT_H -#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SLOT_H - -#include "common.h" - -namespace OHOS { -namespace NotificationNapi { -using namespace OHOS::Notification; - -const int ADD_SLOT_MAX_PARA = 2; -const int ADD_SLOTS_MAX_PARA = 2; -const int GET_SLOT_MAX_PARA = 2; -const int GET_SLOTS_MAX_PARA = 1; -const int REMOVE_SLOT_MAX_PARA = 2; - -struct AsyncCallbackInfoAddSlot { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - NotificationSlot slot; - bool isCallback = false; - int errorCode = 0; -}; - -struct AsyncCallbackInfoAddSlots { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - std::vector slots; - bool isCallback = false; - int errorCode = 0; -}; - -struct AsyncCallbackInfoGetSlot { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - enum NotificationConstant::SlotType outType; - bool isCallback = false; - napi_value result = nullptr; - int errorCode = 0; -}; - -struct AsyncCallbackInfoGetSlots { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - bool isCallback = false; - napi_value result = nullptr; - int errorCode = 0; -}; - -struct AsyncCallbackInfoRemoveSlot { - napi_env env; - napi_async_work asyncWork; - napi_ref callback = nullptr; - napi_deferred deferred; - enum NotificationConstant::SlotType outType; - bool isCallback = false; - int errorCode = 0; -}; - -napi_value AddSlot(napi_env env, napi_callback_info info); -napi_value AddSlots(napi_env env, napi_callback_info info); -napi_value GetSlot(napi_env env, napi_callback_info info); -napi_value GetSlots(napi_env env, napi_callback_info info); -napi_value RemoveSlot(napi_env env, napi_callback_info info); - -napi_value ParseParametersByAddSlot(const napi_env &env, const napi_value (&argv)[ADD_SLOT_MAX_PARA], - const size_t &argc, NotificationSlot &slot, napi_ref &callback); - -void PaddingAsyncCallbackInfoIsByAddSlot( - const napi_env &env, AsyncCallbackInfoAddSlot *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); - -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); - -void PaddingAsyncCallbackInfoIsByAddSlots( - const napi_env &env, AsyncCallbackInfoAddSlots *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); - -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); - -void PaddingAsyncCallbackInfoIsByGetSlot( - const napi_env &env, AsyncCallbackInfoGetSlot *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); - -napi_value ParseParametersByGetSlots( - const napi_env &env, const napi_value (&argv)[GET_SLOTS_MAX_PARA], const size_t &argc, napi_ref &callback); - -void PaddingAsyncCallbackInfoIsByGetSlots( - const napi_env &env, AsyncCallbackInfoGetSlots *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); - -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); - -void PaddingAsyncCallbackInfoIsByRemoveSlot(const napi_env &env, AsyncCallbackInfoRemoveSlot *&asynccallbackinfo, - const napi_ref &callback, napi_value &promise); - -} // namespace NotificationNapi -} // namespace OHOS - -#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SLOT_H \ No newline at end of file diff --git a/notification.gni b/notification.gni index 27ba0928e828874edea500e93ede29c05708c450..54fa4469fc4810380c4d1e4c2e64d1a2b8053dda 100644 --- a/notification.gni +++ b/notification.gni @@ -15,20 +15,25 @@ ans_standard_path = "//base/notification/ans_standard" services_path = "${ans_standard_path}/services" -kits_path = "${ans_standard_path}/kits" +frameworks_path = "${ans_standard_path}/frameworks" -innerkits_path = "${ans_standard_path}/innerkits" +interfaces_path = "${ans_standard_path}/interfaces" + +core_path = "${frameworks_path}/ans/core" test_path = "${ans_standard_path}/test" tools_path = "${ans_standard_path}/tools" +aafwk_path = "//foundation/aafwk/standard" + ans_standard_external_deps = [ "aafwk_standard:base", "aafwk_standard:want", "appexecfwk_standard:appexecfwk_base", "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/ohos.build b/ohos.build index d9e509b7c1e4a19e12089544e2ff5291f9f81ae8..c196545802adf69d99def0adf86ffbc64d21cf73 100644 --- a/ohos.build +++ b/ohos.build @@ -2,8 +2,8 @@ "parts": { "ans_standard": { "module_list": [ - "//base/notification/ans_standard/innerkits:innerkits_target", - "//base/notification/ans_standard/kits:kits_target", + "//base/notification/ans_standard/frameworks:frameworks_target", + "//base/notification/ans_standard/interfaces:interfaces_target", "//base/notification/ans_standard/sa_profile:ans_sa_profile", "//base/notification/ans_standard/services:services_target", "//base/notification/ans_standard/tools:tools_target" @@ -13,7 +13,7 @@ "test_list": [ "//base/notification/ans_standard/services/ans/test/unittest:ans_unit_test", "//base/notification/ans_standard/services/test/moduletest:ans_module_test", - "//base/notification/ans_standard/kits/native/wantagent/test/:unittest" + "//base/notification/ans_standard/frameworks/wantagent/test/:unittest" ] } }, diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index c91ddc50fefc758f92d794135e71966b3f1fe02f..a062596c39e5a827eb83b04780c0fe7fd57e8c65 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -38,9 +38,6 @@ config("json_config") { ohos_shared_library("libans") { include_dirs = [ "include", - "${innerkits_path}/base/include", - "${innerkits_path}/core/include", - "${kits_path}/native/include", "//third_party/json/include", ] @@ -50,24 +47,26 @@ ohos_shared_library("libans") { "src/bundle_manager_helper.cpp", "src/disturb_filter.cpp", "src/notification_preferences.cpp", + "src/notification_preferences_database.cpp", + "src/notification_preferences_info.cpp", "src/notification_slot_filter.cpp", "src/notification_subscriber_manager.cpp", "src/permission_filter.cpp", + "src/system_event_observer.cpp", ] configs = [ ":public_ans_config", "//utils/native/base:utils_config", - "${innerkits_path}:public_ans_innerkits_config", ":json_config", ] deps = [ - "${innerkits_path}:ans_innerkits", - "${kits_path}/native:ans_kits", - "${kits_path}/native/wantagent:wantagent_kits", - "${kits_path}/native/wantagent:wantagent_kits", + "${core_path}:ans_core", + "${frameworks_path}/ans/native:ans_innerkits", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//utils/native/base:utils", ] diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 123d5152ce9e747c86f01c47436f80ac888e6c84..8bd0738dffb4555a410cebb8d9ad2a3fc21815f3 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -16,6 +16,7 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H #define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H +#include #include #include #include @@ -25,8 +26,12 @@ #include "refbase.h" #include "ans_manager_stub.h" +#include "distributed_kv_data_manager.h" +#include "distributed_kvstore_death_recipient.h" #include "notification.h" +#include "notification_record.h" #include "notification_sorting_map.h" +#include "system_event_observer.h" namespace OHOS { namespace Notification { @@ -38,6 +43,7 @@ public: static sptr GetInstance(); + // AnsManagerStub ErrCode Publish(const std::string &label, const sptr &request) override; ErrCode Cancel(int notificationId, const std::string &label) override; ErrCode CancelAll() override; @@ -84,27 +90,42 @@ public: ErrCode IsAllowedNotify(bool &allowed) override; ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) override; + ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; + + // SystemEvent + void OnBundleRemoved(const std::string &bundle); + + // Distributed KvStore + void OnDistributedKvStoreDeathRecipient(); + private: + struct RecentInfo; AdvancedNotificationService(); void StartFilters(); void StopFilters(); - ErrCode Filter(const sptr ¬ification); - - void AddToNotificationList(const sptr ¬ification); - void UpdateInNotificationList(const sptr ¬ification); - ErrCode RemoveFromNotificationList( - const std::string &bundle, const std::string &label, int notificationId, sptr ¬ification); - ErrCode RemoveFromNotificationList(const std::string &key, sptr ¬ification); - std::vector GetRemovableNotificationKeys(const std::string &bundle); + ErrCode Filter(const std::shared_ptr &record); + + 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 std::string &key, sptr ¬ification, bool isCancel = false); + std::vector GetNotificationKeys(const std::string &bundle); bool IsNotificationExists(const std::string &key); void SortNotificationList(); - static bool NotificationCompare(const sptr &first, const sptr &second); + static bool NotificationCompare( + const std::shared_ptr &first, const std::shared_ptr &second); + ErrCode FlowControl(const std::shared_ptr &record); sptr GenerateSortingMap(); - std::string GetClientBundleName(); - bool IsSystemApp(); + std::string TimeToString(int64_t time); + int64_t GetNowSysTime(); + ErrCode ActiveNotificationDump(std::vector &dumpInfo); + ErrCode RecentNotificationDump(std::vector &dumpInfo); + ErrCode SetRecentNotificationCount(const std::string arg); + void UpdateRecentNotification(sptr ¬ification, bool isDelete, int reason); private: static sptr instance_; @@ -112,7 +133,12 @@ private: std::shared_ptr runner_ = nullptr; std::shared_ptr handler_ = nullptr; - std::list> notificationList_; + std::list> notificationList_; + std::list flowControlTimestampList_; + std::shared_ptr recentInfo_ = nullptr; + std::shared_ptr distributedKvStoreDeathRecipient_ = nullptr; + SystemEventObserver systemEventObserver_; + DistributedKv::DistributedKvDataManager dataManager_; }; } // namespace Notification diff --git a/services/ans/include/distributed_kvstore_death_recipient.h b/services/ans/include/distributed_kvstore_death_recipient.h new file mode 100644 index 0000000000000000000000000000000000000000..d5960480143d54ad5727d664162023f7ccdd2429 --- /dev/null +++ b/services/ans/include/distributed_kvstore_death_recipient.h @@ -0,0 +1,49 @@ +/* + * 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_INCLUDE_DISTRIBUTED_KVSTORE_DEATH_RECIPIENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_DISTRIBUTED_KVSTORE_DEATH_RECIPIENT_H + +#include + +#include "kvstore_death_recipient.h" + +namespace OHOS { +namespace Notification { + +class DistributedKvStoreDeathRecipient : public DistributedKv::KvStoreDeathRecipient { +public: + DistributedKvStoreDeathRecipient(const std::function &callback) + { + callback_ = callback; + } + + virtual ~DistributedKvStoreDeathRecipient() + {} + + void OnRemoteDied() override + { + if (callback_ != nullptr) { + callback_(); + } + } + +private: + std::function callback_; +}; + +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_DISTRIBUTED_KVSTORE_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/services/ans/include/disturb_filter.h b/services/ans/include/disturb_filter.h index a38dcfa1c2e4733fe85961487673e41a91794c62..7ced699c5dc4e37b7bbd775a2dd0eadf9ef98744 100644 --- a/services/ans/include/disturb_filter.h +++ b/services/ans/include/disturb_filter.h @@ -29,7 +29,7 @@ public: void OnStart() override; void OnStop() override; - ErrCode OnPublish(const sptr ¬ification) override; + ErrCode OnPublish(const std::shared_ptr &record) override; }; } // namespace Notification diff --git a/services/ans/include/interface_system_event.h b/services/ans/include/interface_system_event.h new file mode 100644 index 0000000000000000000000000000000000000000..52075fded1c02d063669f756e728439df0fe48f9 --- /dev/null +++ b/services/ans/include/interface_system_event.h @@ -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. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_INTERFACE_SYSTEM_EVENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_INTERFACE_SYSTEM_EVENT_H + +#include +#include + +namespace OHOS { +namespace Notification { + +struct ISystemEvent { + std::function onBundleRemoved; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_INTERFACE_SYSTEM_EVENT_H \ No newline at end of file diff --git a/services/ans/include/notification_filter.h b/services/ans/include/notification_filter.h index 2773c920540dc2c3c37f6fef7b0d844acb6102b2..30dc7b90205adf2f8ce107c7d51e8ba19574db0e 100644 --- a/services/ans/include/notification_filter.h +++ b/services/ans/include/notification_filter.h @@ -16,10 +16,11 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_NOTIFICATION_FILTER_H #define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_NOTIFICATION_FILTER_H +#include + #include "errors.h" -#include "refbase.h" -#include "notification.h" +#include "notification_record.h" namespace OHOS { namespace Notification { @@ -32,7 +33,7 @@ public: virtual void OnStart() = 0; virtual void OnStop() = 0; - virtual ErrCode OnPublish(const sptr ¬ification) = 0; + virtual ErrCode OnPublish(const std::shared_ptr &record) = 0; }; } // namespace Notification diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index e0c6732076a6cf9cc141b6f2398f43479d2381cd..c2d476978cfe76982811916b929e3a0643bde0a8 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -13,26 +13,16 @@ * limitations under the License. */ -#ifndef NOTIFICATION_PREFERENCES_H -#define NOTIFICATION_PREFERENCES_H +#ifndef BASE_NOTIFICATION_ANS_STANDARD_SERVICES_NOTIFICATION_PREFERENCES_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_NOTIFICATION_PREFERENCES_H -#include -#include -#include -#include -#include - -#include "nlohmann/json.hpp" #include "refbase.h" #include "singleton.h" -#include "ans_inner_errors.h" -#include "notification_slot.h" -#include "notification_slot_group.h" +#include "notification_preferences_database.h" namespace OHOS { namespace Notification { - class NotificationPreferences final { public: DISALLOW_COPY_AND_MOVE(NotificationPreferences); @@ -58,7 +48,7 @@ public: 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 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); @@ -71,91 +61,35 @@ public: ErrCode SetDisturbMode(const NotificationConstant::DisturbMode &mode); ErrCode ClearNotificationInRestoreFactorySettings(); + void OnDistributedKvStoreDeathRecipient(); + private: - struct BundleInfo { - std::string bundleName {}; - int importance = NotificationSlot::NotificationLevel::LEVEL_DEFAULT; - bool isShowBadge = false; - int badgeTotalNum = 0; - bool isPrivateAllowed = false; - bool isEnabledNotification = true; - std::map> groups {}; - std::map> slots {}; - }; - struct PreferencesInfo { - bool isEnabledAllNotification = true; - NotificationConstant::DisturbMode disturbMode = NotificationConstant::DisturbMode::ALLOW_ALL; - std::map infos {}; - }; - enum class BundlePropertyType; + // enum class BundlePropertyType; - ErrCode CreateSlot( - const std::string &bundleName, const NotificationConstant::SlotType &type, sptr &slot); ErrCode CheckSlotForCreateSlot(const std::string &bundleName, const sptr &slot, - PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; + NotificationPreferencesInfo &preferencesInfo) const; ErrCode CheckGroupForCreateSlotGroup(const std::string &bundleName, const sptr &group, - PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; + NotificationPreferencesInfo &preferencesInfo) const; ErrCode CheckSlotForRemoveSlot(const std::string &bundleName, const NotificationConstant::SlotType &slotType, - PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; - ErrCode CheckGroupForRemoveSlotGroup(const std::string &bundleName, const std::string &groupId, - PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; + 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, - PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; + NotificationPreferencesInfo &preferencesInfo) const; ErrCode CheckGroupForUpdateSlotGroup(const std::string &bundleName, const sptr &group, - PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; - template - void SetBundleProperty(PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson, const std::string &bundleName, - const BundlePropertyType &type, const T &value); + NotificationPreferencesInfo &preferencesInfo) const; template - void CreateBundleProperty(PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson, - const std::string &bundleName, const BundlePropertyType &type, const T &value); + ErrCode SetBundleProperty(NotificationPreferencesInfo &preferencesInfo, const std::string &bundleName, + const BundleType &type, const T &value); template - void UpdateBundleProperty(BundleInfo &bundleInfo, nlohmann::json ¶seJson, const std::string &bundleName, - const BundlePropertyType &type, const T &value); + ErrCode SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleName, + const BundleType &type, const T &value); template - ErrCode GetBundleProperty(const std::string &bundleName, const BundlePropertyType &type, T &value); - - void AddSlotToJson(nlohmann::json &json, const std::string &bundleName, const sptr &slot) const; - void AddSlotGroupToJson( - nlohmann::json &json, const std::string &bundleName, const sptr &group) const; - void UpdateExsitSlotTypeInJson( - nlohmann::json &json, const std::string &bundleName, const sptr &slot) const; - void RemoveSlotInJson( - nlohmann::json &json, const std::string &bundleName, const NotificationConstant::SlotType &type) const; - void UpdateSlotInJson( - nlohmann::json &json, const std::string &bundleName, const sptr &slot) const; - void RemoveSlotGroupInJson(nlohmann::json &json, const std::string &bundleName, const std::string &groupId) const; - void UpdateSlotGroupInJson( - nlohmann::json &json, const std::string &bundleName, const sptr &slot) const; - void RemoveBundleInJson(nlohmann::json &json, const std::string &bundleName); - void AddJson(nlohmann::json &json, const BundleInfo &info, const NotificationConstant::DisturbMode &mode, - const bool &enable) const; - void ParseFromJson(); - ErrCode ParseNotification(); - ErrCode StoreNotification(const nlohmann::json &json) const; - ErrCode CommitNotification(const nlohmann::json ¶seJson, const PreferencesInfo &preferencesInfo); - - template - void CheckInvalidPath(T &t) const; - void InitDir() const; - void InitFile() const; - bool IsEmptyInputFile(std::ifstream &inputFile) const; - bool IsExistDir(const std::string &path) const; - bool IsExistFile(const std::string &dirPath, const std::string &filePath) const; - bool CreateDirectory(const std::string &path) const; - bool CreateAndChangeFileAttr(const std::string &filePath) const; - - nlohmann::json BundlePropertyToJson(const BundleInfo &bundleInfo) const; - nlohmann::json GroupToJson(const sptr &group) const; - nlohmann::json SlotToJson(const sptr &slot) const; - void JsonToBundleProperty(nlohmann::json &json, BundleInfo &bundleInfo) const; - void JsonToGroup(nlohmann::json &json, sptr &group) const; - void JsonToSlot(nlohmann::json &json, sptr &slot) const; + ErrCode GetBundleProperty(const std::string &bundleName, const BundleType &type, T &value) const; private: - PreferencesInfo preferencesInfo_ {}; - nlohmann::json paraseJson_ {}; - + NotificationPreferencesInfo preferencesInfo_ {}; + std::unique_ptr preferncesDB_ = nullptr; DECLARE_DELAYED_REF_SINGLETON(NotificationPreferences); }; diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h new file mode 100644 index 0000000000000000000000000000000000000000..411098a4a1163a802af3b04d6cbbba54ac52f1cf --- /dev/null +++ b/services/ans/include/notification_preferences_database.h @@ -0,0 +1,140 @@ +/* + * 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_NOTIFICATION_PREFERENCES_DATABASE_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_NOTIFICATION_PREFERENCES_DATABASE_H + +#include +#include + +#include "distributed_kv_data_manager.h" +#include "notification_preferences_info.h" + +namespace OHOS { +namespace Notification { + +class NotificationPreferencesDatabase { +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 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); + + void SubscribeDeathRecipient(const std::shared_ptr &callback); + void UnsubscribeDeathRecipient(const std::shared_ptr &callback); + bool StoreDeathRecipient(NotificationPreferencesInfo &info); + +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); + template + OHOS::DistributedKv::Status PutBundlePropertyToDisturbeDB( + const std::string &bundleName, const BundleType &type, const T &t); + bool PutBundleToDisturbeDB(const std::string &bundleName); + + 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); + + bool SlotToEntry(const std::string &bundleName, 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, + std::vector &entries); + void GenerateEntry( + const std::string &key, const std::string &value, std::vector &entry); + + std::string FindLastString(const std::string &inputString) const; + std::string SubUniqueIdentifyFromString(const std::string &keyStr) const; + std::string VectorToString(const std::vector &data) const; + void StringToVector(const std::string &str, std::vector &data) 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; + + void ParseBundleFromDistureDB( + NotificationPreferencesInfo &info, const std::vector &entries); + void ParseSlotFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleName, + const OHOS::DistributedKv::Entry &entry); + void ParseGroupFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleName, + const OHOS::DistributedKv::Entry &entry); + void ParseBundlePropertyFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, + const OHOS::DistributedKv::Key &key, const OHOS::DistributedKv::Value &value); + void ParseDisturbeMode(NotificationPreferencesInfo &info); + void ParseEnableAllNotification(NotificationPreferencesInfo &info); + void ParseGroupDescription(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; + void ParseBundleBadgeNum(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; + 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 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; + void ParseSlotShowBadge(sptr &slot, const std::string &value) const; + void ParseSlotEnableLight(sptr &slot, const std::string &value) const; + void ParseSlotEnableVrbration(sptr &slot, const std::string &value) const; + void ParseSlotLedLightColor(sptr &slot, const std::string &kevaluey) const; + void ParseSlotLockscreenVisibleness(sptr &slot, const std::string &value) const; + void ParseSlotSound(sptr &slot, const std::string &value) const; + void ParseSlotVibrationSytle(sptr &slot, const std::string &value) const; + void ParseSlotEnableBypassDnd(sptr &slot, const std::string &value) const; + + static const std::map &, std::string &)>> + slotMap_; + static const std::map> + bundleMap_; + + const DistributedKv::AppId appId_ {APP_ID}; + const DistributedKv::StoreId storeId_ {STORE_ID}; + std::unique_ptr kvStorePtr_ = nullptr; + DistributedKv::DistributedKvDataManager dataManager_; +}; + +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_NOTIFICATION_PREFERENCES_DATABASE_H \ No newline at end of file diff --git a/services/ans/include/notification_preferences_info.h b/services/ans/include/notification_preferences_info.h new file mode 100644 index 0000000000000000000000000000000000000000..611a9d713ecb62ba0f93fda8343431205d800027 --- /dev/null +++ b/services/ans/include/notification_preferences_info.h @@ -0,0 +1,92 @@ +/* + * 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_NOTIFICATION_PREFERENCES_INFO_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_NOTIFICATION_PREFERENCES_INFO_H + +#include +#include +#include + +#include "notification_slot.h" +#include "notification_slot_group.h" +#include "preferences_constant.h" + +namespace OHOS { +namespace Notification { +class NotificationPreferencesInfo { +public: + class BundleInfo { + public: + BundleInfo(); + ~BundleInfo(); + void SetBundleName(const std::string &name); + std::string GetBundleName() const; + void SetImportance(const int &level); + int GetImportance() const; + void SetIsShowBadge(const bool &isShowBadge); + bool GetIsShowBadge() const; + void SetBadgeTotalNum(const int &num); + int GetBadgeTotalNum() const; + void SetIsPrivateAllowed(const bool &isPrivateAllowed); + bool GetIsPrivateAllowed() const; + void SetEnableNotification(const bool &enable); + bool GetEnableNotification() const; + 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); + void SetGroup(const sptr &group); + bool GetGroup(const std::string &groupId, sptr &group) const; + 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); + bool RemoveSlotGroup(const std::string &groupId); + + private: + std::string bundleName_{}; + int importance_ = BUNDLE_IMPORTANCE; + bool isShowBadge_ = BUNDLE_SHOW_BADGE; + int badgeTotalNum_ = BUNDLE_BADGE_TOTAL_NUM; + bool isPrivateAllowed_ = BUNDLE_PRIVATE_ALLOWED; + bool isEnabledNotification_ = BUNDLE_ENABLE_NOTIFICATION; + std::map> slots_{}; + std::map> groups_{}; + }; + + NotificationPreferencesInfo() + {} + ~NotificationPreferencesInfo() + {} + void SetEnabledAllNotification(const bool &value); + bool GetEnabledAllNotification() const; + 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; + void ClearBundleInfo(); + +private: + bool isEnabledAllNotification_ = true; + NotificationConstant::DisturbMode disturbMode_ = NotificationConstant::DisturbMode::ALLOW_ALL; + std::map infos_ {}; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_NOTIFICATION_PREFERENCES_INFO_H \ No newline at end of file diff --git a/services/ans/include/notification_record.h b/services/ans/include/notification_record.h new file mode 100644 index 0000000000000000000000000000000000000000..5fd3f4ee7896d7827524cd69910e5d340d1b92fb --- /dev/null +++ b/services/ans/include/notification_record.h @@ -0,0 +1,37 @@ +/* + * 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_INCLUDE_NOTIFICATION_RECORD_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_NOTIFICATION_RECORD_H + +#include "refbase.h" + +#include "notification.h" +#include "notification_request.h" +#include "notification_slot.h" + +namespace OHOS { +namespace Notification { + +struct NotificationRecord { + sptr request; + sptr notification; + sptr slot; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_NOTIFICATION_RECORD_H \ No newline at end of file diff --git a/services/ans/include/notification_slot_filter.h b/services/ans/include/notification_slot_filter.h index 238fed9ca579dec3c68bfd038bfb6fd62be9e5f9..45092a2bc17a5b32e160ef01f914003d5941b3d4 100644 --- a/services/ans/include/notification_slot_filter.h +++ b/services/ans/include/notification_slot_filter.h @@ -29,7 +29,7 @@ public: void OnStart() override; void OnStop() override; - ErrCode OnPublish(const sptr ¬ification) override; + ErrCode OnPublish(const std::shared_ptr &record) override; }; } // namespace Notification diff --git a/services/ans/include/permission_filter.h b/services/ans/include/permission_filter.h index 00af78530fb3b17f054bcf4dcfaca27afba907dc..850069cc8ce2a7a2425fda46887324b1246ae541 100644 --- a/services/ans/include/permission_filter.h +++ b/services/ans/include/permission_filter.h @@ -29,7 +29,7 @@ public: void OnStart() override; void OnStop() override; - ErrCode OnPublish(const sptr ¬ification) override; + ErrCode OnPublish(const std::shared_ptr &record) override; }; } // namespace Notification diff --git a/services/ans/include/preferences_constant.h b/services/ans/include/preferences_constant.h new file mode 100644 index 0000000000000000000000000000000000000000..1923774bab5a3f2199c5f449b40642b8c89d1dbe --- /dev/null +++ b/services/ans/include/preferences_constant.h @@ -0,0 +1,83 @@ +/* + * 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_PREFERENCES_CONSTANT_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_PREFERENCES_CONSTANT_H + +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 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 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 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 + +// 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_ENABLE_NOTIFICATION = true; + +enum class BundleType { + kBundleNameType = 1, + kBundleImportanceType, + kBundleShowBadgeType, + kBundleBadgeTotalNumType, + kBundlePrivateAllowedType, + kBundleEnableNotificationType, +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_PREFERENCES_CONSTANT_H \ No newline at end of file diff --git a/services/ans/include/system_event_observer.h b/services/ans/include/system_event_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..7fc8cd4fece62a6763e06ce43474d0b955e55552 --- /dev/null +++ b/services/ans/include/system_event_observer.h @@ -0,0 +1,46 @@ +/* + * 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_INCLUDE_SYSTEM_EVENT_OBSERVER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_SYSTEM_EVENT_OBSERVER_H + +#include + +#include "common_event_subscriber.h" +#include "refbase.h" + +#include "interface_system_event.h" +#include "system_event_subscriber.h" + +namespace OHOS { +namespace Notification { + +class SystemEventObserver { +public: + SystemEventObserver(const ISystemEvent& callbacks); + ~SystemEventObserver(); + +private: + void OnReceiveEvent(const EventFwk::CommonEventData &data); + +private: + std::shared_ptr subscriber_ = nullptr; + ISystemEvent callbacks_; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_SYSTEM_EVENT_OBSERVER_H \ No newline at end of file diff --git a/services/ans/include/system_event_subscriber.h b/services/ans/include/system_event_subscriber.h new file mode 100644 index 0000000000000000000000000000000000000000..6b9a7a2ecfccea2fe8b5ed0ce6850378da072eca --- /dev/null +++ b/services/ans/include/system_event_subscriber.h @@ -0,0 +1,47 @@ +/* + * 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_INCLUDE_SYSTEM_EVENT_SUBSCRIBER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_SYSTEM_EVENT_SUBSCRIBER_H + +#include + +#include "common_event_subscriber.h" + +namespace OHOS { +namespace Notification { + +class SystemEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + SystemEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + const std::function &callback) + : EventFwk::CommonEventSubscriber(subscribeInfo), callback_(callback) + {} + + void OnReceiveEvent(const EventFwk::CommonEventData &data) override + { + if (callback_ != nullptr) { + callback_(data); + } + } + +private: + std::function callback_; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_SYSTEM_EVENT_SUBSCRIBER_H \ No newline at end of file diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 6d2e05d7b50e7c8ef589298af842ccbffcacfb38..12c76f04978ab2f9e442916e88287c75e211cb71 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -16,7 +16,10 @@ #include "advanced_notification_service.h" #include +#include +#include +#include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" #include "bundle_manager_helper.h" @@ -33,6 +36,26 @@ namespace OHOS { namespace Notification { +namespace { +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 DEFAULT_RECENT_COUNT = 16; + +struct RecentNotification { + 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}; +}; + sptr AdvancedNotificationService::instance_; std::mutex AdvancedNotificationService::instanceMutex_; @@ -42,6 +65,77 @@ static const std::shared_ptr NOTIFICATION_FILTERS[] = { std::make_shared(), }; +inline std::string GetClientBundleName() +{ + std::string bundle; + + uid_t callingUid = IPCSkeleton::GetCallingUid(); + + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager != nullptr) { + bundle = bundleManager->GetBundleNameByUid(callingUid); + } + + return bundle; +} + +inline bool IsSystemApp() +{ + bool isSystemApp = false; + + uid_t callingUid = IPCSkeleton::GetCallingUid(); + + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager != nullptr) { + printf("callingUid : %d\n", callingUid); + isSystemApp = bundleManager->IsSystemApp(callingUid); + } + + return isSystemApp; +} + +inline ErrCode AssignValidNotificationSlot(const std::shared_ptr &record) +{ + sptr slot; + ErrCode result = NotificationPreferences::GetInstance().GetNotificationSlot( + record->notification->GetBundleName(), 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); + 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); + } + } + if (result == ERR_OK) { + record->slot = slot; + } + return result; +} + +inline ErrCode PrepereNotificationRequest(const sptr &request) +{ + std::string bundle = GetClientBundleName(); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + + request->SetOwnerBundleName(bundle); + request->SetCreatorBundleName(bundle); + + int32_t uid = IPCSkeleton::GetCallingUid(); + int32_t pid = IPCSkeleton::GetCallingPid(); + request->SetCreatorUid(uid); + request->SetCreatorPid(pid); + + return ERR_OK; +} + sptr AdvancedNotificationService::GetInstance() { std::lock_guard lock(instanceMutex_); @@ -53,15 +147,23 @@ sptr AdvancedNotificationService::GetInstance() } AdvancedNotificationService::AdvancedNotificationService() + : systemEventObserver_({std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1)}) { runner_ = OHOS::AppExecFwk::EventRunner::Create(); handler_ = std::make_shared(runner_); + recentInfo_ = std::make_shared(); + distributedKvStoreDeathRecipient_ = std::make_shared( + std::bind(&AdvancedNotificationService::OnDistributedKvStoreDeathRecipient, this)); StartFilters(); + + dataManager_.RegisterKvStoreServiceDeathRecipient(distributedKvStoreDeathRecipient_); } AdvancedNotificationService::~AdvancedNotificationService() { + dataManager_.UnRegisterKvStoreServiceDeathRecipient(distributedKvStoreDeathRecipient_); + StopFilters(); } @@ -73,37 +175,42 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt return ERR_ANS_NON_SYSTEM_APP; } - ErrCode result = ERR_OK; + ErrCode result = PrepereNotificationRequest(request); - std::string bundle = GetClientBundleName(); - request->SetOwnerBundleName(bundle); - request->SetCreatorBundleName(bundle); + std::shared_ptr record = std::make_shared(); + record->request = request; + record->notification = new Notification(request); - int32_t uid = IPCSkeleton::GetCallingUid(); - int32_t pid = IPCSkeleton::GetCallingPid(); - request->SetCreatorUid(uid); - request->SetCreatorPid(pid); + handler_->PostSyncTask(std::bind([&]() { + result = AssignValidNotificationSlot(record); + if (result != ERR_OK) { + ANS_LOGE("Can not assign valid slot!"); + return; + } - sptr notification = new Notification(request); - handler_->PostSyncTask(std::bind([this, &label, ¬ification, &result]() { - result = Filter(notification); + result = Filter(record); if (result != ERR_OK) { + ANS_LOGE("Reject by filters: %{public}d", result); return; } - if (!IsNotificationExists(notification->GetKey())) { - AddToNotificationList(notification); + if (!IsNotificationExists(record->notification->GetKey())) { + result = FlowControl(record); + if (result != ERR_OK) { + return; + } } else { - if (notification->request_->IsAlertOneTime()) { - notification->request_->SetColorEnabled(false); - notification->SetSound(Uri(std::string())); - notification->SetVibrationStyle(std::vector()); + if (record->request->IsAlertOneTime()) { + record->notification->SetEnableLight(false); + record->notification->SetEnableSound(false); + record->notification->SetEnableViration(false); } - UpdateInNotificationList(notification); + UpdateInNotificationList(record); } + UpdateRecentNotification(record->notification, false, 0); sptr sortingMap = GenerateSortingMap(); - NotificationSubscriberManager::GetInstance()->NotifyConsumed(notification, sortingMap); + NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap); })); return result; @@ -114,7 +221,7 @@ bool AdvancedNotificationService::IsNotificationExists(const std::string &key) bool isExists = false; for (auto item : notificationList_) { - if (item->GetKey() == key) { + if (item->notification->GetKey() == key) { isExists = true; break; } @@ -123,12 +230,12 @@ bool AdvancedNotificationService::IsNotificationExists(const std::string &key) return isExists; } -ErrCode AdvancedNotificationService::Filter(const sptr ¬ification) +ErrCode AdvancedNotificationService::Filter(const std::shared_ptr &record) { ErrCode result = ERR_OK; for (auto filter : NOTIFICATION_FILTERS) { - result = filter->OnPublish(notification); + result = filter->OnPublish(record); if (result != ERR_OK) { break; } @@ -137,18 +244,18 @@ ErrCode AdvancedNotificationService::Filter(const sptr ¬ificati return result; } -void AdvancedNotificationService::AddToNotificationList(const sptr ¬ification) +void AdvancedNotificationService::AddToNotificationList(const std::shared_ptr &record) { - notificationList_.push_back(notification); + notificationList_.push_back(record); SortNotificationList(); } -void AdvancedNotificationService::UpdateInNotificationList(const sptr ¬ification) +void AdvancedNotificationService::UpdateInNotificationList(const std::shared_ptr &record) { auto iter = notificationList_.begin(); while (iter != notificationList_.end()) { - if ((*iter)->GetKey() == notification->GetKey()) { - *iter = notification; + if ((*iter)->notification->GetKey() == record->notification->GetKey()) { + *iter = record; break; } iter++; @@ -162,21 +269,22 @@ void AdvancedNotificationService::SortNotificationList() notificationList_.sort(AdvancedNotificationService::NotificationCompare); } -bool AdvancedNotificationService::NotificationCompare(const sptr &first, const sptr &second) +bool AdvancedNotificationService::NotificationCompare( + const std::shared_ptr &first, const std::shared_ptr &second) { // sorting notifications by create time - return (first->request_->GetCreateTime() < second->request_->GetCreateTime()); + return (first->request->GetCreateTime() < second->request->GetCreateTime()); } sptr AdvancedNotificationService::GenerateSortingMap() { std::vector sortingList; - for (auto notification : notificationList_) { + for (auto record : notificationList_) { NotificationSorting sorting; - sorting.SetKey(notification->GetKey()); + sorting.SetKey(record->notification->GetKey()); sptr slot; if (NotificationPreferences::GetInstance().GetNotificationSlot( - notification->GetBundleName(), notification->request_->GetSlotType(), slot) == ERR_OK) { + record->notification->GetBundleName(), record->request->GetSlotType(), slot) == ERR_OK) { sorting.SetRanking((int32_t)sortingList.size()); sorting.SetSlot(slot); } @@ -208,17 +316,22 @@ ErrCode AdvancedNotificationService::Cancel(int notificationId, const std::strin ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &label, notificationId, &result]() { + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + + handler_->PostSyncTask(std::bind([&]() { sptr notification = nullptr; - result = RemoveFromNotificationList(bundle, label, notificationId, notification); + result = RemoveFromNotificationList(bundle, label, notificationId, notification, true); if (result != ERR_OK) { return; } if (notification != nullptr) { + int reason = NotificationConstant::APP_CANCEL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); - NotificationSubscriberManager::GetInstance()->NotifyCanceled( - notification, sortingMap, NotificationConstant::CANCEL_REASON_DELETE); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); } })); return result; @@ -230,22 +343,29 @@ ErrCode AdvancedNotificationService::CancelAll() ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &result]() { + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + + handler_->PostSyncTask(std::bind([&]() { sptr notification = nullptr; - std::vector removableList = GetRemovableNotificationKeys(bundle); - for (auto key : removableList) { - result = RemoveFromNotificationList(key, notification); + std::vector keys = GetNotificationKeys(bundle); + for (auto key : keys) { + result = RemoveFromNotificationList(key, notification, true); if (result != ERR_OK) { continue; } if (notification != nullptr) { + int reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); - NotificationSubscriberManager::GetInstance()->NotifyCanceled( - notification, sortingMap, NotificationConstant::CANCEL_REASON_DELETE); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); } } + + result = ERR_OK; })); return result; } @@ -266,15 +386,43 @@ ErrCode AdvancedNotificationService::AddSlots(const std::vectorPostSyncTask(std::bind([this, &bundle, &slots, &result]() { - result = NotificationPreferences::GetInstance().AddNotificationSlots(bundle, slots); - })); + std::vector> innerSlots; + + 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; + } + item = nullptr; + } + + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().AddNotificationSlots(bundle, innerSlots); })); return result; } @@ -282,9 +430,11 @@ ErrCode AdvancedNotificationService::AddSlotGroups(std::vectorPostSyncTask(std::bind([this, &bundle, &groups, &result]() { - result = NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundle, groups); - })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundle, groups); })); return result; } @@ -292,9 +442,11 @@ ErrCode AdvancedNotificationService::GetSlots(std::vector { ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &slots, &result]() { - result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots); - })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots); })); return result; } @@ -302,9 +454,11 @@ ErrCode AdvancedNotificationService::GetSlotGroup(const std::string &groupId, sp { ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &groupId, &group, &result]() { - result = NotificationPreferences::GetInstance().GetNotificationSlotGroup(bundle, groupId, group); - })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().GetNotificationSlotGroup(bundle, groupId, group); })); return result; } @@ -312,9 +466,11 @@ ErrCode AdvancedNotificationService::GetSlotGroups(std::vectorPostSyncTask(std::bind([this, &bundle, &groups, &result]() { - result = NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundle, groups); - })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundle, groups); })); return result; } @@ -322,9 +478,8 @@ ErrCode AdvancedNotificationService::RemoveSlotGroups(const std::vectorPostSyncTask(std::bind([this, &bundle, &groupIds, &result]() { - result = NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundle, groupIds); - })); + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundle, groupIds); })); return result; } @@ -334,10 +489,13 @@ ErrCode AdvancedNotificationService::GetActiveNotifications(std::vectorPostSyncTask(std::bind([this, &bundle, ¬ifications, &result]() { - for (auto notification : notificationList_) { - if (notification->GetBundleName() == bundle) { - notifications.push_back(notification->request_); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind([&]() { + for (auto record : notificationList_) { + if (record->notification->GetBundleName() == bundle) { + notifications.push_back(record->request); } } })); @@ -350,10 +508,13 @@ ErrCode AdvancedNotificationService::GetActiveNotificationNums(int &num) ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &num, &result]() { + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind([&]() { int count = 0; - for (auto notification : notificationList_) { - if (notification->GetBundleName() == bundle) { + for (auto record : notificationList_) { + if (record->notification->GetBundleName() == bundle) { count += 1; } } @@ -384,9 +545,11 @@ ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int num) { ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &num, &result]() { - result = NotificationPreferences::GetInstance().SetTotalBadgeNums(bundle, num); - })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().SetTotalBadgeNums(bundle, num); })); return result; } @@ -394,9 +557,11 @@ ErrCode AdvancedNotificationService::GetBundleImportance(int &importance) { ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &importance, &result]() { - result = NotificationPreferences::GetInstance().GetImportance(bundle, importance); - })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().GetImportance(bundle, importance); })); return result; } @@ -404,14 +569,19 @@ ErrCode AdvancedNotificationService::SetDisturbMode(NotificationConstant::Distur { ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind( - [this, &bundle, mode, &result]() { result = NotificationPreferences::GetInstance().SetDisturbMode(mode); })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind([&]() { result = NotificationPreferences::GetInstance().SetDisturbMode(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; + } handler_->PostSyncTask(std::bind( [this, &bundle, &mode, &result]() { result = NotificationPreferences::GetInstance().GetDisturbMode(mode); })); return result; @@ -425,9 +595,11 @@ ErrCode AdvancedNotificationService::SetPrivateNotificationsAllowed(bool allow) { ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &allow, &result]() { - result = NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundle, allow); - })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundle, allow); })); return result; } @@ -435,9 +607,11 @@ ErrCode AdvancedNotificationService::GetPrivateNotificationsAllowed(bool &allow) { ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &allow, &result]() { - result = NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundle, allow); - })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundle, allow); })); return result; } @@ -451,7 +625,7 @@ ErrCode AdvancedNotificationService::Delete(const std::string &key) ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &key, &result]() { + handler_->PostSyncTask(std::bind([&]() { sptr notification = nullptr; result = RemoveFromNotificationList(key, notification); if (result != ERR_OK) { @@ -459,9 +633,10 @@ ErrCode AdvancedNotificationService::Delete(const std::string &key) } if (notification != nullptr) { + int reason = NotificationConstant::CANCEL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); - NotificationSubscriberManager::GetInstance()->NotifyCanceled( - notification, sortingMap, NotificationConstant::CANCEL_REASON_DELETE); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); } })); @@ -478,22 +653,25 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const std::string &bundle) ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &bundle, &result]() { + handler_->PostSyncTask(std::bind([&]() { sptr notification = nullptr; - std::vector removableList = GetRemovableNotificationKeys(bundle); - for (auto key : removableList) { + std::vector keys = GetNotificationKeys(bundle); + for (auto key : keys) { result = RemoveFromNotificationList(key, notification); if (result != ERR_OK) { continue; } if (notification != nullptr) { + int reason = NotificationConstant::CANCEL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); - NotificationSubscriberManager::GetInstance()->NotifyCanceled( - notification, sortingMap, NotificationConstant::CANCEL_REASON_DELETE); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); } } + + result = ERR_OK; })); return result; @@ -508,38 +686,39 @@ ErrCode AdvancedNotificationService::DeleteAll() } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &result]() { + handler_->PostSyncTask(std::bind([&]() { sptr notification = nullptr; - std::vector removableList = GetRemovableNotificationKeys(std::string()); - for (auto key : removableList) { + std::vector keys = GetNotificationKeys(std::string()); + for (auto key : keys) { result = RemoveFromNotificationList(key, notification); if (result != ERR_OK) { continue; } if (notification != nullptr) { + int reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); - NotificationSubscriberManager::GetInstance()->NotifyCanceled( - notification, sortingMap, NotificationConstant::CANCEL_REASON_DELETE); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); } } + + result = ERR_OK; })); return result; } -std::vector AdvancedNotificationService::GetRemovableNotificationKeys(const std::string &bundle) +std::vector AdvancedNotificationService::GetNotificationKeys(const std::string &bundle) { std::vector keys; - for (auto item : notificationList_) { - if (!bundle.empty() && (item->GetBundleName() != bundle)) { + for (auto record : notificationList_) { + if (!bundle.empty() && (record->notification->GetBundleName() != bundle)) { continue; } - if (!item->GetNotificationRequest().IsUnremovable()) { - keys.push_back(item->GetKey()); - } + keys.push_back(record->notification->GetKey()); } return keys; @@ -555,9 +734,8 @@ ErrCode AdvancedNotificationService::GetSlotsByBundle( } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &bundle, &slots, &result]() { - result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots); - })); + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots); })); return result; } @@ -571,9 +749,8 @@ ErrCode AdvancedNotificationService::UpdateSlots( } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &bundle, &slots, &result]() { - result = NotificationPreferences::GetInstance().UpdateNotificationSlots(bundle, slots); - })); + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().UpdateNotificationSlots(bundle, slots); })); return result; } @@ -587,9 +764,8 @@ ErrCode AdvancedNotificationService::UpdateSlotGroups( } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &bundle, &groups, &result]() { - result = NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundle, groups); - })); + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundle, groups); })); return result; } @@ -602,9 +778,8 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForBundle(const std: } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &bundle, &enabled, &result]() { - result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundle, enabled); - })); + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundle, enabled); })); return result; } @@ -617,9 +792,8 @@ ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle(const std::str } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &bundle, &enabled, &result]() { - result = NotificationPreferences::GetInstance().SetShowBadge(bundle, enabled); - })); + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().SetShowBadge(bundle, enabled); })); return result; } @@ -632,22 +806,22 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle(const std::str } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &bundle, &enabled, &result]() { - result = NotificationPreferences::GetInstance().IsShowBadge(bundle, enabled); - })); + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().IsShowBadge(bundle, enabled); })); return result; } -ErrCode AdvancedNotificationService::RemoveFromNotificationList( - const std::string &bundle, const std::string &label, int notificationId, sptr ¬ification) +ErrCode AdvancedNotificationService::RemoveFromNotificationList(const std::string &bundle, const std::string &label, + int notificationId, sptr ¬ification, bool isCancel) { - for (auto item : notificationList_) { - if (item->GetBundleName() == bundle && item->GetLabel() == label && item->GetId() == notificationId) { - if (item->GetNotificationRequest().IsUnremovable()) { + for (auto record : notificationList_) { + if ((record->notification->GetBundleName() == bundle) && (record->notification->GetLabel() == label) && + (record->notification->GetId() == notificationId)) { + if (!isCancel && record->request->IsUnremovable()) { return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; } - notification = item; - notificationList_.remove(item); + notification = record->notification; + notificationList_.remove(record); return ERR_OK; } } @@ -656,15 +830,15 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( } ErrCode AdvancedNotificationService::RemoveFromNotificationList( - const std::string &key, sptr ¬ification) + const std::string &key, sptr ¬ification, bool isCancel) { - for (auto item : notificationList_) { - if (item->GetKey() == key) { - if (item->GetNotificationRequest().IsUnremovable()) { + for (auto record : notificationList_) { + if (record->notification->GetKey() == key) { + if (!isCancel && record->request->IsUnremovable()) { return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; } - notification = item; - notificationList_.remove(item); + notification = record->notification; + notificationList_.remove(record); return ERR_OK; } } @@ -672,34 +846,6 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( return ERR_ANS_NOTIFICATION_NOT_EXISTS; } -std::string AdvancedNotificationService::GetClientBundleName() -{ - std::string bundle; - - uid_t callingUid = IPCSkeleton::GetCallingUid(); - - std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); - if (bundleManager != nullptr) { - bundle = bundleManager->GetBundleNameByUid(callingUid); - } - - return bundle; -} - -bool AdvancedNotificationService::IsSystemApp() -{ - bool isSystemApp = false; - - uid_t callingUid = IPCSkeleton::GetCallingUid(); - - std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); - if (bundleManager != nullptr) { - isSystemApp = bundleManager->IsSystemApp(callingUid); - } - - return isSystemApp; -} - ErrCode AdvancedNotificationService::Subscribe( const sptr &subscriber, const sptr &info) { @@ -739,9 +885,11 @@ ErrCode AdvancedNotificationService::GetSlotByType( { ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &slotType, &slot, &result]() { - result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot); - })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind( + [&]() { result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot); })); return result; } @@ -749,9 +897,11 @@ ErrCode AdvancedNotificationService::RemoveSlotByType(const NotificationConstant { ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &slotType, &result]() { - result = NotificationPreferences::GetInstance().RemoveNotificationSlot(bundle, slotType); - })); + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask( + std::bind([&]() { result = NotificationPreferences::GetInstance().RemoveNotificationSlot(bundle, slotType); })); return result; } @@ -764,8 +914,10 @@ ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vectorPostSyncTask(std::bind([this, ¬ifications, &result]() { - notifications.assign(notificationList_.begin(), notificationList_.end()); + handler_->PostSyncTask(std::bind([&]() { + for (auto record : notificationList_) { + notifications.push_back(record->notification); + } })); return result; } @@ -796,10 +948,10 @@ ErrCode AdvancedNotificationService::GetSpecialActiveNotifications( } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &key, ¬ifications, &result]() { - for (auto notification : notificationList_) { - if (IsContained(key, notification->GetKey())) { - notifications.push_back(notification); + handler_->PostSyncTask(std::bind([&]() { + for (auto record : notificationList_) { + if (IsContained(key, record->notification->GetKey())) { + notifications.push_back(record->notification); } } })); @@ -815,7 +967,7 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &deviceId, &enabled, &result]() { + handler_->PostSyncTask(std::bind([&]() { if (deviceId.empty()) { // Local device result = NotificationPreferences::GetInstance().SetNotificationsEnabled(enabled); @@ -836,7 +988,7 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &deviceId, &bundleName, &enabled, &result]() { + handler_->PostSyncTask(std::bind([&]() { if (deviceId.empty()) { // Local device result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleName, enabled); @@ -853,7 +1005,10 @@ ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed) ErrCode result = ERR_OK; std::string bundle = GetClientBundleName(); - handler_->PostSyncTask(std::bind([this, &bundle, &allowed, &result]() { + if (bundle.empty()) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind([&]() { allowed = false; result = NotificationPreferences::GetInstance().GetNotificationsEnabled(allowed); if (result == ERR_OK && allowed) { @@ -872,7 +1027,7 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(const std::str } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([this, &bundle, &allowed, &result]() { + handler_->PostSyncTask(std::bind([&]() { allowed = false; result = NotificationPreferences::GetInstance().GetNotificationsEnabled(allowed); if (result == ERR_OK && allowed) { @@ -882,5 +1037,215 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(const std::str return result; } +ErrCode AdvancedNotificationService::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + ErrCode result = ERR_ANS_NOT_ALLOWED; + + handler_->PostSyncTask(std::bind([&]() { + if (dumpOption == ACTIVE_NOTIFICATION_OPTION) { + result = ActiveNotificationDump(dumpInfo); + } else if (dumpOption == RECENT_NOTIFICATION_OPTION) { + result = RecentNotificationDump(dumpInfo); + } else if (dumpOption.substr(0, dumpOption.find_first_of(" ", 0)) == SET_RECENT_COUNT_OPTION) { + result = SetRecentNotificationCount(dumpOption.substr(dumpOption.find_first_of(" ", 0) + 1)); + } else { + result = ERR_ANS_INVALID_PARAM; + } + })); + + return result; +} + +ErrCode AdvancedNotificationService::ActiveNotificationDump(std::vector &dumpInfo) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + std::stringstream stream; + for (auto record : notificationList_) { + stream.clear(); + stream << "\tBundleName: " << record->notification->GetBundleName() << "\n"; + + stream << "\tCreateTime: " << TimeToString(record->notification->GetNotificationRequest().GetCreateTime()) + << "\n"; + + stream << "\tNotification:\n"; + stream << "\t\tId: " << record->notification->GetId() << "\n"; + stream << "\t\tLabel: " << record->notification->GetLabel() << "\n"; + stream << "\t\tClassification: " << record->notification->GetNotificationRequest().GetClassification() << "\n"; + + dumpInfo.push_back(stream.str()); + } + + return ERR_OK; +} + +ErrCode AdvancedNotificationService::RecentNotificationDump(std::vector &dumpInfo) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + std::stringstream stream; + for (auto recentNotification : recentInfo_->list) { + stream.clear(); + stream << "\tBundleName: " << recentNotification->notification->GetBundleName() << "\n"; + + stream << "\tCreateTime: " + << TimeToString(recentNotification->notification->GetNotificationRequest().GetCreateTime()) << "\n"; + + stream << "\tNotification:\n"; + stream << "\t\tId: " << recentNotification->notification->GetId() << "\n"; + stream << "\t\tLabel: " << recentNotification->notification->GetLabel() << "\n"; + stream << "\t\tClassification: " + << recentNotification->notification->GetNotificationRequest().GetClassification() << "\n"; + + if (!recentNotification->isActive) { + stream << "\t DeleteTime: " << TimeToString(recentNotification->deleteTime) << "\n"; + stream << "\t DeleteReason: " << recentNotification->deleteReason << "\n"; + } + + dumpInfo.push_back(stream.str()); + } + return ERR_OK; +} + +ErrCode AdvancedNotificationService::SetRecentNotificationCount(const std::string arg) +{ + ANS_LOGD("%{public}s arg = %{public}s", __FUNCTION__, arg.c_str()); + int count = atoi(arg.c_str()); + + if (count < 0 || count > 1024) { + return ERR_ANS_INVALID_PARAM; + } + + recentInfo_->recentCount = count; + return ERR_OK; +} + +std::string AdvancedNotificationService::TimeToString(int64_t time) +{ + auto timePoint = std::chrono::time_point(std::chrono::milliseconds(time)); + auto timeT = std::chrono::system_clock::to_time_t(timePoint); + + std::stringstream stream; + stream << std::put_time(std::localtime(&timeT), "%F, %T"); + return stream.str(); +} + +int64_t AdvancedNotificationService::GetNowSysTime() +{ + std::chrono::time_point nowSys = std::chrono::system_clock::now(); + auto epoch = nowSys.time_since_epoch(); + auto value = std::chrono::duration_cast(epoch); + int64_t duration = value.count(); + return duration; +} + +void AdvancedNotificationService::UpdateRecentNotification(sptr ¬ification, bool isDelete, int reason) +{ + for (auto recentNotification : recentInfo_->list) { + if (recentNotification->notification->GetKey() == notification->GetKey()) { + if (!isDelete) { + recentInfo_->list.remove(recentNotification); + recentNotification->isActive = true; + recentNotification->notification = notification; + recentInfo_->list.emplace_front(recentNotification); + } else { + recentNotification->isActive = false; + recentNotification->deleteReason = reason; + recentNotification->deleteTime = GetNowSysTime(); + } + return; + } + } + + if (!isDelete) { + if (recentInfo_->list.size() >= recentInfo_->recentCount) { + recentInfo_->list.erase(recentInfo_->list.end()); + } + auto recentNotification = std::make_shared(); + recentNotification->isActive = true; + recentNotification->notification = notification; + recentInfo_->list.emplace_front(recentNotification); + } +} + +inline void RemoveExpired( + std::list &list, const std::chrono::system_clock::time_point &now) +{ + auto iter = list.begin(); + while (iter != list.end()) { + if (now - *iter > std::chrono::seconds(1)) { + iter = list.erase(iter); + } else { + break; + } + } +} + +static bool SortNotificationsByLevelAndTime( + const std::shared_ptr &first, const std::shared_ptr &second) +{ + if (first->slot->GetLevel() != second->slot->GetLevel()) { + return (first->slot->GetLevel() < second->slot->GetLevel()); + } else { + return (first->request->GetCreateTime() < second->request->GetCreateTime()); + } +} + +ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr &record) +{ + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + RemoveExpired(flowControlTimestampList_, now); + if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND) { + return ERR_ANS_OVER_MAX_ACITVE_PERSECOND; + } + + flowControlTimestampList_.push_back(now); + + std::list> bundleList; + for (auto item : notificationList_) { + if (record->notification->GetBundleName() == item->notification->GetBundleName()) { + bundleList.push_back(item); + } + } + + if (bundleList.size() >= MAX_ACTIVE_NUM_PERAPP) { + bundleList.sort(SortNotificationsByLevelAndTime); + notificationList_.remove(bundleList.front()); + } + + if (notificationList_.size() >= MAX_ACTIVE_NUM) { + if (bundleList.size() > 0) { + bundleList.sort(SortNotificationsByLevelAndTime); + notificationList_.remove(bundleList.front()); + } else { + std::list> sorted = notificationList_; + sorted.sort(SortNotificationsByLevelAndTime); + notificationList_.remove(sorted.front()); + } + } + + AddToNotificationList(record); + + return ERR_OK; +} + +void AdvancedNotificationService::OnBundleRemoved(const std::string &bundle) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + handler_->PostTask(std::bind([&]() { + ErrCode result = NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundle); + if (result != ERR_OK) { + ANS_LOGE("NotificationPreferences::RemoveNotificationForBundle failed: %{public}d", result); + } + })); +} + +void AdvancedNotificationService::OnDistributedKvStoreDeathRecipient() +{ + ANS_LOGD("%{public}s", __FUNCTION__); + handler_->PostTask( + std::bind([&]() { NotificationPreferences::GetInstance().OnDistributedKvStoreDeathRecipient(); })); +} + } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/disturb_filter.cpp b/services/ans/src/disturb_filter.cpp index 7bfc34788797c39e3beb8abad157275cee58646f..c6547f08113d8e1016415c55d33f22b4a1adb383 100644 --- a/services/ans/src/disturb_filter.cpp +++ b/services/ans/src/disturb_filter.cpp @@ -15,6 +15,9 @@ #include "disturb_filter.h" +#include "ans_inner_errors.h" +#include "notification_preferences.h" + namespace OHOS { namespace Notification { @@ -24,9 +27,51 @@ void DisturbFilter::OnStart() void DisturbFilter::OnStop() {} -ErrCode DisturbFilter::OnPublish(const sptr ¬ification) +ErrCode DisturbFilter::OnPublish(const std::shared_ptr &record) { - return ERR_OK; + NotificationConstant::DisturbMode mode; + ErrCode result = NotificationPreferences::GetInstance().GetDisturbMode(mode); + if (result != ERR_OK) { + return result; + } + + bool disturb = false; + + switch (mode) { + case NotificationConstant::DisturbMode::ALLOW_ALARMS: + if (record->request->GetClassification() == NotificationRequest::CLASSIFICATION_ALARM) { + disturb = true; + } else { + if (record->slot == nullptr) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; + break; + } + disturb = record->slot->IsEnableBypassDnd(); + } + break; + case NotificationConstant::DisturbMode::ALLOW_ALL: + disturb = true; + break; + case NotificationConstant::DisturbMode::ALLOW_NONE: + if (record->slot == nullptr) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; + break; + } + disturb = record->slot->IsEnableBypassDnd(); + break; + case NotificationConstant::DisturbMode::ALLOW_PRIORITY: + break; + default: + break; + } + + if (!disturb) { + record->notification->SetEnableLight(false); + record->notification->SetEnableSound(false); + record->notification->SetEnableViration(false); + } + + return result; } } // namespace Notification diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index f0e2b499c7a3006cc6c7a2e3b435e3126dca784f..04d67ccf9aed1407161b90e2ce04ce155555f8c2 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -15,77 +15,21 @@ #include "notification_preferences.h" -#include -#include -#include - -#include "directory_ex.h" -#include "uri.h" - #include "ans_const_define.h" +#include "ans_inner_errors.h" #include "ans_log_wrapper.h" namespace OHOS { namespace Notification { -namespace { -const static std::string kStorePath = "/data/ans"; -const static std::string kStoreFile = kStorePath + "/Notification.json"; -const static std::string kDisturbMode = "disturbMode"; -const static std::string kEnable = "enable"; -const static std::string kBundle = "bundle"; -const static std::string kBundleName = "bundleName"; -const static std::string kBundleImportance = "importance"; -const static std::string kBundleShowBadge = "isShowBadge"; -const static std::string kBundleBadgeTotalNum = "badgeTotalNum"; -const static std::string kBundlePrivateAllowed = "isPrivateAllowed"; -const static std::string kBundleEnableNotification = "isEnabledNotification"; - -const static std::string kGroup = "slotGroup"; -const static std::string kGroupId = "groupId"; -const static std::string kGroupName = "groupName"; -const static std::string kGroupDescription = "groupDescription"; -const static std::string kGroupDisable = "isDisable"; - -const static std::string kSlot = "slot"; -const static std::string kSlotGroupId = "groupId"; -const static std::string kSlotId = "slotId"; -const static std::string kSlotType = "slotType"; -const static std::string kSlotName = "slotName"; -const static std::string kSlotDescription = "slotDescription"; -const static std::string kSlotLevel = "slotLevel"; -const static std::string kSlotShowBadge = "isShowBadge"; -const static std::string kSlotEnableLight = "isEnableLight"; -const static std::string kSlotEnableVrbration = "isEnableVibration"; -const static std::string kSlotLedLightColor = "ledLightColor"; -const static std::string kSlotLockscreenVisibleness = "isLockscreenVisibleness"; -const static std::string kSlotSound = "sound"; -const static std::string kSlotVibrationSytle = "vibrationSytle"; -const static std::string kSlotEnableBypassDnd = "isEnableBypassDnd"; - -const static uint8_t kJsonDump = 4; - -} // namespace - -enum class NotificationPreferences::BundlePropertyType { - kBundleImportanceType = 1, - kBundleShowBadgeType, - kBundleBadgeTotalNumType, - kBundlePrivateAllowedType, - kBundleEnableNotificationType, -}; - NotificationPreferences::NotificationPreferences() { - InitDir(); - InitFile(); - ParseNotification(); + preferncesDB_ = std::make_unique(); + preferncesDB_->ParseFromDisturbeDB(preferencesInfo_); } NotificationPreferences::~NotificationPreferences() -{ - StoreNotification(paraseJson_); -} +{} NotificationPreferences &NotificationPreferences::GetInstance() { @@ -95,161 +39,207 @@ NotificationPreferences &NotificationPreferences::GetInstance() ErrCode NotificationPreferences::AddNotificationSlots( const std::string &bundleName, const std::vector> &slots) { + + ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty() || slots.empty()) { return ERR_ANS_INVALID_PARAM; } - - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; for (auto slot : slots) { - result = CheckSlotForCreateSlot(bundleName, slot, preferencesInfo, paraseJson); + result = CheckSlotForCreateSlot(bundleName, slot, preferencesInfo); if (result != ERR_OK) { return result; } } - result = CommitNotification(paraseJson, preferencesInfo); + + if (result == ERR_OK && (!preferncesDB_->PutSlotsToDisturbeDB(bundleName, slots))) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } return result; } ErrCode NotificationPreferences::AddNotificationSlotGroups( const std::string &bundleName, const std::vector> &groups) { + ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty() || groups.empty()) { return ERR_ANS_INVALID_PARAM; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; for (auto group : groups) { - result = CheckGroupForCreateSlotGroup(bundleName, group, preferencesInfo, paraseJson); + result = CheckGroupForCreateSlotGroup(bundleName, group, preferencesInfo); if (result != ERR_OK) { return result; } } - result = CommitNotification(paraseJson, preferencesInfo); + + if (result == ERR_OK && (!preferncesDB_->PutGroupsToDisturbeDB(bundleName, groups))) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + return result; + } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } return result; } ErrCode NotificationPreferences::RemoveNotificationSlot( const std::string &bundleName, const NotificationConstant::SlotType &slotType) { + ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; - result = CheckSlotForRemoveSlot(bundleName, slotType, preferencesInfo, paraseJson); - if (result != ERR_OK) { + result = CheckSlotForRemoveSlot(bundleName, slotType, preferencesInfo); + + if (result == ERR_OK && (!preferncesDB_->RemoveSlotFromDisturbeDB(bundleName, slotType))) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; return result; } - result = CommitNotification(paraseJson, preferencesInfo); + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } return result; } ErrCode NotificationPreferences::RemoveNotificationSlotGroups( const std::string &bundleName, const std::vector &groupIds) { + ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty() || groupIds.empty()) { return ERR_ANS_INVALID_PARAM; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; for (auto groupId : groupIds) { - result = CheckGroupForRemoveSlotGroup(bundleName, groupId, preferencesInfo, paraseJson); + result = CheckGroupForRemoveSlotGroup(bundleName, groupId, preferencesInfo); if (result != ERR_OK) { return result; } } - result = CommitNotification(paraseJson, preferencesInfo); + if (result == ERR_OK && (!preferncesDB_->RemoveGroupsFromDisturbeDB(bundleName, groupIds))) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + return result; + } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } return result; } ErrCode NotificationPreferences::RemoveNotificationForBundle(const std::string &bundleName) { + ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; - auto iter = preferencesInfo.infos.find(bundleName); - if (iter != preferencesInfo.infos.end()) { - preferencesInfo.infos.erase(iter); - RemoveBundleInJson(paraseJson, bundleName); - result = CommitNotification(paraseJson, preferencesInfo); + if (preferencesInfo.IsExsitBundleInfo(bundleName)) { + preferencesInfo.RemoveBundleInfo(bundleName); + if (!preferncesDB_->RemoveBundleFromDisturbeDB(bundleName)) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } } else { result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } + return result; } ErrCode NotificationPreferences::UpdateNotificationSlots( const std::string &bundleName, const std::vector> &slots) { + ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty() || slots.empty()) { return ERR_ANS_INVALID_PARAM; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; for (auto slotIter : slots) { - result = CheckSlotForUpdateSlot(bundleName, slotIter, preferencesInfo, paraseJson); + result = CheckSlotForUpdateSlot(bundleName, slotIter, preferencesInfo); if (result != ERR_OK) { return result; } } - result = CommitNotification(paraseJson, preferencesInfo); + if (result == ERR_OK && (!preferncesDB_->PutSlotsToDisturbeDB(bundleName, slots))) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + return result; + } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } + return result; } ErrCode NotificationPreferences::UpdateNotificationSlotGroups( const std::string &bundleName, const std::vector> &groups) { + ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty() || groups.empty()) { return ERR_ANS_INVALID_PARAM; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; for (auto groupIter : groups) { - result = CheckGroupForUpdateSlotGroup(bundleName, groupIter, preferencesInfo, paraseJson); + result = CheckGroupForUpdateSlotGroup(bundleName, groupIter, preferencesInfo); if (result != ERR_OK) { return result; } } - result = CommitNotification(paraseJson, preferencesInfo); + if (result == ERR_OK && (!preferncesDB_->PutGroupsToDisturbeDB(bundleName, groups))) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + return result; + } + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } return result; } ErrCode NotificationPreferences::GetNotificationSlot( const std::string &bundleName, const NotificationConstant::SlotType &type, sptr &slot) { + ANS_LOGD("%{public}s", __FUNCTION__); if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo_.infos.find(bundleName); - if (preferencesIter != preferencesInfo_.infos.end()) { - auto slotIter = preferencesIter->second.slots.find(type); - if (slotIter != preferencesIter->second.slots.end()) { - slot = slotIter->second; - } else { - result = CreateSlot(bundleName, type, slot); + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + if (!bundleInfo.GetSlot(type, slot)) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; } } else { - result = CreateSlot(bundleName, type, slot); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } + ANS_LOGD("%{public}s status = %{public}d ", __FUNCTION__, result); return result; } @@ -261,13 +251,9 @@ ErrCode NotificationPreferences::GetNotificationAllSlots( } ErrCode result = ERR_OK; - auto iter = preferencesInfo_.infos.find(bundleName); - if (iter != preferencesInfo_.infos.end()) { - std::for_each(iter->second.slots.begin(), - iter->second.slots.end(), - [&](std::map>::reference slot) { - slots.emplace_back(slot.second); - }); + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + bundleInfo.GetAllSlots(slots); } else { ANS_LOGE("Notification bundle does not exsit."); result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; @@ -284,15 +270,10 @@ ErrCode NotificationPreferences::GetNotificationSlotGroup( } ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo_.infos.find(bundleName); - if (preferencesIter != preferencesInfo_.infos.end()) { - auto groupIter = preferencesIter->second.groups.begin(); - while (groupIter != preferencesIter->second.groups.end()) { - if (!groupId.compare(groupIter->first)) { - group = groupIter->second; - break; - } - ++groupIter; + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + if (!bundleInfo.GetGroup(groupId, group)) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST; } } else { ANS_LOGE("Notification bundle does not exsit."); @@ -309,13 +290,9 @@ ErrCode NotificationPreferences::GetNotificationAllSlotGroups( } ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo_.infos.find(bundleName); - if (preferencesIter != preferencesInfo_.infos.end()) { - std::for_each(preferencesIter->second.groups.begin(), - preferencesIter->second.groups.end(), - [&](std::map>::reference group) { - groups.emplace_back(group.second); - }); + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + bundleInfo.GetAllGroups(groups); } else { ANS_LOGE("Notification bundle does not exsit."); result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; @@ -331,15 +308,9 @@ ErrCode NotificationPreferences::GetNotificationAllSlotInSlotGroup( } ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo_.infos.find(bundleName); - if (preferencesIter != preferencesInfo_.infos.end()) { - auto slotIter = preferencesIter->second.slots.begin(); - while (slotIter != preferencesIter->second.slots.end()) { - if ((slotIter->second != nullptr) && (!groupId.compare(slotIter->second->GetSlotGroup()))) { - slots.emplace_back(slotIter->second); - } - ++slotIter; - } + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + bundleInfo.GetAllSlotsInGroup(groupId, slots); } else { ANS_LOGE("Notification bundle does not exsit."); result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; @@ -353,7 +324,7 @@ ErrCode NotificationPreferences::IsShowBadge(const std::string &bundleName, bool if (bundleName.empty()) { return result; } - result = GetBundleProperty(bundleName, BundlePropertyType::kBundleShowBadgeType, enable); + result = GetBundleProperty(bundleName, BundleType::kBundleShowBadgeType, enable); return result; } @@ -363,11 +334,12 @@ ErrCode NotificationPreferences::SetShowBadge(const std::string &bundleName, con return ERR_ANS_INVALID_PARAM; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; - - SetBundleProperty(preferencesInfo, paraseJson, bundleName, BundlePropertyType::kBundleShowBadgeType, enable); - return CommitNotification(paraseJson, preferencesInfo); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleShowBadgeType, enable); + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } + return result; } ErrCode NotificationPreferences::GetImportance(const std::string &bundleName, int &importance) @@ -376,19 +348,21 @@ ErrCode NotificationPreferences::GetImportance(const std::string &bundleName, in return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundlePropertyType::kBundleImportanceType, importance); + ErrCode result = GetBundleProperty(bundleName, BundleType::kBundleImportanceType, importance); return result; } -ErrCode NotificationPreferences::SetImportance(const std::string &bundleName, const int importance) +ErrCode NotificationPreferences::SetImportance(const std::string &bundleName, const int &importance) { if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; - SetBundleProperty(preferencesInfo, paraseJson, bundleName, BundlePropertyType::kBundleImportanceType, importance); - return CommitNotification(paraseJson, preferencesInfo); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleImportanceType, importance); + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } + return result; } ErrCode NotificationPreferences::GetTotalBadgeNums(const std::string &bundleName, int &totalBadgeNum) @@ -396,7 +370,7 @@ ErrCode NotificationPreferences::GetTotalBadgeNums(const std::string &bundleName if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundlePropertyType::kBundleBadgeTotalNumType, totalBadgeNum); + ErrCode result = GetBundleProperty(bundleName, BundleType::kBundleBadgeTotalNumType, totalBadgeNum); return result; } @@ -405,10 +379,12 @@ ErrCode NotificationPreferences::SetTotalBadgeNums(const std::string &bundleName if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; - SetBundleProperty(preferencesInfo, paraseJson, bundleName, BundlePropertyType::kBundleBadgeTotalNumType, num); - return CommitNotification(paraseJson, preferencesInfo); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleBadgeTotalNumType, num); + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } + return result; } ErrCode NotificationPreferences::GetPrivateNotificationsAllowed(const std::string &bundleName, bool &allow) @@ -416,7 +392,7 @@ ErrCode NotificationPreferences::GetPrivateNotificationsAllowed(const std::strin if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundlePropertyType::kBundlePrivateAllowedType, allow); + ErrCode result = GetBundleProperty(bundleName, BundleType::kBundlePrivateAllowedType, allow); return result; } @@ -425,10 +401,12 @@ ErrCode NotificationPreferences::SetPrivateNotificationsAllowed(const std::strin if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; - SetBundleProperty(preferencesInfo, paraseJson, bundleName, BundlePropertyType::kBundlePrivateAllowedType, allow); - return CommitNotification(paraseJson, preferencesInfo); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundlePrivateAllowedType, allow); + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } + return result; } ErrCode NotificationPreferences::GetNotificationsEnabledForBundle(const std::string &bundleName, bool &enabled) @@ -436,7 +414,7 @@ ErrCode NotificationPreferences::GetNotificationsEnabledForBundle(const std::str if (bundleName.empty()) { return ERR_ANS_INVALID_PARAM; } - ErrCode result = GetBundleProperty(bundleName, BundlePropertyType::kBundleEnableNotificationType, enabled); + ErrCode result = GetBundleProperty(bundleName, BundleType::kBundleEnableNotificationType, enabled); return result; } @@ -445,86 +423,62 @@ ErrCode NotificationPreferences::SetNotificationsEnabledForBundle(const std::str if (bundleName.empty()) { return ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; - SetBundleProperty( - preferencesInfo, paraseJson, bundleName, BundlePropertyType::kBundleEnableNotificationType, enabled); - return CommitNotification(paraseJson, preferencesInfo); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + ErrCode result = SetBundleProperty(preferencesInfo, bundleName, BundleType::kBundleEnableNotificationType, enabled); + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + } + return result; } ErrCode NotificationPreferences::GetNotificationsEnabled(bool &enabled) { - enabled = preferencesInfo_.isEnabledAllNotification; + enabled = preferencesInfo_.GetEnabledAllNotification(); return ERR_OK; } ErrCode NotificationPreferences::SetNotificationsEnabled(const bool &enabled) { - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; - preferencesInfo.isEnabledAllNotification = enabled; - paraseJson[kEnable] = enabled; - return CommitNotification(paraseJson, preferencesInfo); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + preferencesInfo.SetEnabledAllNotification(enabled); + ErrCode result = ERR_OK; + if (!preferncesDB_->PutNotificationsEnabled(enabled)) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + return result; } ErrCode NotificationPreferences::GetDisturbMode(NotificationConstant::DisturbMode &mode) { - mode = preferencesInfo_.disturbMode; + mode = preferencesInfo_.GetDisturbMode(); return ERR_OK; } ErrCode NotificationPreferences::SetDisturbMode(const NotificationConstant::DisturbMode &mode) { - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; - preferencesInfo.disturbMode = mode; - paraseJson[kDisturbMode] = mode; - return CommitNotification(paraseJson, preferencesInfo); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + preferencesInfo.SetDisturbMode(mode); + ErrCode result = ERR_OK; + if (!preferncesDB_->PutDisturbMode(mode)) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + return result; } ErrCode NotificationPreferences::ClearNotificationInRestoreFactorySettings() { - PreferencesInfo preferencesInfo = preferencesInfo_; - nlohmann::json paraseJson = paraseJson_; - preferencesInfo.disturbMode = NotificationConstant::DisturbMode::ALLOW_ALL; - preferencesInfo.isEnabledAllNotification = true; - preferencesInfo.infos.clear(); - paraseJson.clear(); - return CommitNotification(paraseJson, preferencesInfo); -} - -ErrCode NotificationPreferences::CreateSlot( - const std::string &bundleName, const NotificationConstant::SlotType &type, sptr &slot) -{ - sptr tmpSlot; - switch (type) { - case NotificationConstant::SlotType::SOCIAL_COMMUNICATION: - tmpSlot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - break; - case NotificationConstant::SlotType::SERVICE_REMINDER: - tmpSlot = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); - break; - case NotificationConstant::SlotType::CONTENT_INFORMATION: - tmpSlot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); - break; - case NotificationConstant::SlotType::OTHER: - case NotificationConstant::SlotType::CUSTOM: - tmpSlot = new NotificationSlot(NotificationConstant::SlotType::OTHER); - break; - default: - break; - } - std::vector> slots; - slots.push_back(tmpSlot); - ErrCode result = AddNotificationSlots(bundleName, slots); - if (result == ERR_OK) { - slot = tmpSlot; + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + preferencesInfo.ClearBundleInfo(); + ErrCode result = ERR_OK; + if (!preferncesDB_->RemoveAllBundleFromDisturbeDB()) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } return result; } ErrCode NotificationPreferences::CheckSlotForCreateSlot(const std::string &bundleName, - const sptr &slot, PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const + const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const { if (slot == nullptr) { ANS_LOGE("Notification slot is nullptr."); @@ -532,28 +486,18 @@ ErrCode NotificationPreferences::CheckSlotForCreateSlot(const std::string &bundl } ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo.infos.find(bundleName); - if (preferencesIter != preferencesInfo.infos.end()) { - if (preferencesIter->second.slots.find(slot->GetType()) != preferencesIter->second.slots.end()) { - preferencesIter->second.slots.insert_or_assign(slot->GetType(), slot); - UpdateExsitSlotTypeInJson(paraseJson, bundleName, slot); - } else { - preferencesIter->second.slots.insert_or_assign(slot->GetType(), slot); - AddSlotToJson(paraseJson, bundleName, slot); - } - } else { - BundleInfo bundle; - bundle.bundleName = bundleName; - bundle.slots.insert_or_assign(slot->GetType(), slot); - preferencesInfo.infos.insert_or_assign(bundleName, bundle); - AddJson(paraseJson, bundle, preferencesInfo.disturbMode, preferencesInfo.isEnabledAllNotification); + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (!preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + bundleInfo.SetBundleName(bundleName); } + bundleInfo.SetSlot(slot); + preferencesInfo.SetBundleInfo(bundleInfo); return result; } ErrCode NotificationPreferences::CheckGroupForCreateSlotGroup(const std::string &bundleName, - const sptr &group, PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const + const sptr &group, NotificationPreferencesInfo &preferencesInfo) const { if (group == nullptr) { ANS_LOGE("Notification slot group is nullptr."); @@ -566,45 +510,34 @@ ErrCode NotificationPreferences::CheckGroupForCreateSlotGroup(const std::string } ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo.infos.find(bundleName); - if (preferencesIter != preferencesInfo.infos.end()) { - if (preferencesIter->second.groups.find(group->GetId()) != preferencesIter->second.groups.end()) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_HAS_EXISTED; - } else { - if (preferencesIter->second.groups.size() >= MAX_SLOT_GROUP_NUM) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM; - } else { - preferencesIter->second.groups.insert_or_assign(group->GetId(), group); - AddSlotGroupToJson(paraseJson, bundleName, group); - } - } + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (!preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + bundleInfo.SetBundleName(bundleName); } else { - BundleInfo bundle; - bundle.bundleName = bundleName; - bundle.groups.insert_or_assign(group->GetId(), group); - preferencesInfo.infos.insert_or_assign(bundleName, bundle); - AddJson(paraseJson, bundle, preferencesInfo.disturbMode, preferencesInfo.isEnabledAllNotification); + if (bundleInfo.GetGroupSize() >= MAX_SLOT_GROUP_NUM) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM; + return result; + } } + bundleInfo.SetGroup(group); + preferencesInfo.SetBundleInfo(bundleInfo); + return result; } ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const std::string &bundleName, - const NotificationConstant::SlotType &slotType, PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const + const NotificationConstant::SlotType &slotType, NotificationPreferencesInfo &preferencesInfo) const { ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo.infos.find(bundleName); - if (preferencesIter != preferencesInfo.infos.end()) { - if (preferencesIter->second.slots.empty()) { - return ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; - } - auto slotIter = preferencesIter->second.slots.find(slotType); - if (slotIter != preferencesIter->second.slots.end()) { - preferencesIter->second.slots.erase(slotIter); - RemoveSlotInJson(paraseJson, bundleName, slotType); + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + if (bundleInfo.IsExsitSlot(slotType)) { + bundleInfo.RemoveSlot(slotType); + preferencesInfo.SetBundleInfo(bundleInfo); } else { - ANS_LOGE("Notification slot id is invalid."); - result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ID_INVALID; + ANS_LOGE("Notification slot type does not exsited."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; } } else { ANS_LOGE("Notification bundle does not exsit."); @@ -613,21 +546,17 @@ ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const std::string &bundl return result; } -ErrCode NotificationPreferences::CheckGroupForRemoveSlotGroup(const std::string &bundleName, const std::string &groupId, - PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const +ErrCode NotificationPreferences::CheckGroupForRemoveSlotGroup( + const std::string &bundleName, const std::string &groupId, NotificationPreferencesInfo &preferencesInfo) const { ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo.infos.find(bundleName); - if (preferencesIter != preferencesInfo.infos.end()) { - if (preferencesIter->second.groups.empty()) { - return ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST; - } - auto groupIter = preferencesIter->second.groups.find(groupId); - if (groupIter != preferencesIter->second.groups.end()) { - preferencesIter->second.groups.erase(groupIter); - RemoveSlotGroupInJson(paraseJson, bundleName, groupId); + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + if (bundleInfo.IsExsitSlotGroup(groupId)) { + bundleInfo.RemoveSlotGroup(groupId); + preferencesInfo.SetBundleInfo(bundleInfo); } else { - ANS_LOGE("Notification slot id is invalid."); + ANS_LOGE("Notification slot group id is invalid."); result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID; } } else { @@ -638,7 +567,7 @@ ErrCode NotificationPreferences::CheckGroupForRemoveSlotGroup(const std::string } ErrCode NotificationPreferences::CheckSlotForUpdateSlot(const std::string &bundleName, - const sptr &slot, PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const + const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const { if (slot == nullptr) { ANS_LOGE("Notification slot is nullptr."); @@ -646,150 +575,117 @@ ErrCode NotificationPreferences::CheckSlotForUpdateSlot(const std::string &bundl } ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo.infos.find(bundleName); - if (preferencesIter != preferencesInfo.infos.end()) { - if (preferencesIter->second.slots.empty()) { - return ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; - } - auto slotIter = preferencesIter->second.slots.find(slot->GetType()); - if (slotIter != preferencesIter->second.slots.end()) { - preferencesIter->second.slots.insert_or_assign(slot->GetType(), slot); - UpdateSlotInJson(paraseJson, bundleName, slot); + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + if (bundleInfo.IsExsitSlot(slot->GetType())) { + bundleInfo.SetBundleName(bundleName); + bundleInfo.SetSlot(slot); + preferencesInfo.SetBundleInfo(bundleInfo); } else { - ANS_LOGE("Notification slot id is invalid."); - result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ID_INVALID; + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; } } else { - ANS_LOGE("Notification bundle does not exsit."); - result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + ANS_LOGE("Notification slot is nullptr."); + return ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } + return result; } ErrCode NotificationPreferences::CheckGroupForUpdateSlotGroup(const std::string &bundleName, - const sptr &group, PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const + const sptr &group, NotificationPreferencesInfo &preferencesInfo) const { ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo.infos.find(bundleName); - if (preferencesIter != preferencesInfo.infos.end()) { - if (preferencesIter->second.groups.empty()) { - return ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST; - } - auto groupIter = preferencesIter->second.groups.find(group->GetId()); - if (groupIter != preferencesIter->second.groups.end()) { - preferencesIter->second.groups.insert_or_assign(group->GetId(), group); - UpdateSlotGroupInJson(paraseJson, bundleName, group); + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo.GetBundleInfo(bundleName, bundleInfo)) { + if (bundleInfo.IsExsitSlotGroup(group->GetId())) { + bundleInfo.SetBundleName(bundleName); + bundleInfo.SetGroup(group); + preferencesInfo.SetBundleInfo(bundleInfo); } else { - ANS_LOGE("Notification slot group id is invalid."); - result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID; + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST; } } else { - ANS_LOGE("Notification bundle does not exsit."); - result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + ANS_LOGE("Notification slot is nullptr."); + return ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } return result; } template -void NotificationPreferences::SetBundleProperty(PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson, - const std::string &bundleName, const BundlePropertyType &type, const T &value) +ErrCode NotificationPreferences::SetBundleProperty( + NotificationPreferencesInfo &preferencesInfo, const std::string &bundleName, const BundleType &type, const T &value) { - auto preferencesIter = preferencesInfo.infos.find(bundleName); - if (preferencesIter != preferencesInfo.infos.end()) { - UpdateBundleProperty(preferencesIter->second, paraseJson, bundleName, type, value); - } else { - CreateBundleProperty(preferencesInfo, paraseJson, bundleName, type, value); + ErrCode result = ERR_OK; + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (!preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { + bundleInfo.SetBundleName(bundleName); } -} -template -void NotificationPreferences::CreateBundleProperty(PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson, - const std::string &bundleName, const BundlePropertyType &type, const T &value) -{ - BundleInfo bundle; - bundle.bundleName = bundleName; - switch (type) { - case BundlePropertyType::kBundleImportanceType: - bundle.importance = value; - break; - case BundlePropertyType::kBundleBadgeTotalNumType: - bundle.badgeTotalNum = value; - break; - case BundlePropertyType::kBundleShowBadgeType: - bundle.isShowBadge = value; - break; - case BundlePropertyType::kBundlePrivateAllowedType: - bundle.isPrivateAllowed = value; - break; - case BundlePropertyType::kBundleEnableNotificationType: - bundle.isEnabledNotification = value; - break; - default: - break; - } - preferencesInfo.infos.emplace(bundleName, bundle); - AddJson(paraseJson, bundle, preferencesInfo.disturbMode, preferencesInfo.isEnabledAllNotification); + result = SaveBundleProperty(bundleInfo, bundleName, type, value); + preferencesInfo.SetBundleInfo(bundleInfo); + + return result; } template -void NotificationPreferences::UpdateBundleProperty(BundleInfo &bundleInfo, nlohmann::json ¶seJson, - const std::string &bundleName, const BundlePropertyType &type, const T &value) +ErrCode NotificationPreferences::SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, + const std::string &bundleName, const BundleType &type, const T &value) { - auto packageJsonIter = paraseJson[kBundle].begin(); - while (packageJsonIter != paraseJson[kBundle].end()) { - if (!bundleName.compare((*packageJsonIter)[kBundleName].get())) { - break; - } - ++packageJsonIter; - } + bool storeDBResult = true; switch (type) { - case BundlePropertyType::kBundleImportanceType: - bundleInfo.importance = value; - packageJsonIter->at(kBundleImportance) = value; + case BundleType::kBundleImportanceType: + bundleInfo.SetImportance(value); + storeDBResult = preferncesDB_->PutImportance(bundleName, value); break; - case BundlePropertyType::kBundleBadgeTotalNumType: - bundleInfo.badgeTotalNum = value; - packageJsonIter->at(kBundleBadgeTotalNum) = value; + case BundleType::kBundleBadgeTotalNumType: + bundleInfo.SetBadgeTotalNum(value); + storeDBResult = preferncesDB_->PutTotalBadgeNums(bundleName, value); break; - case BundlePropertyType::kBundleShowBadgeType: - bundleInfo.isShowBadge = value; - packageJsonIter->at(kBundleShowBadge) = value; + case BundleType::kBundleShowBadgeType: + bundleInfo.SetIsShowBadge(value); + storeDBResult = preferncesDB_->PutShowBadge(bundleName, value); break; - case BundlePropertyType::kBundlePrivateAllowedType: - bundleInfo.isPrivateAllowed = value; - packageJsonIter->at(kBundlePrivateAllowed) = value; + case BundleType::kBundlePrivateAllowedType: + bundleInfo.SetIsPrivateAllowed(value); + storeDBResult = preferncesDB_->PutPrivateNotificationsAllowed(bundleName, value); break; - case BundlePropertyType::kBundleEnableNotificationType: - bundleInfo.isEnabledNotification = value; - packageJsonIter->at(kBundleEnableNotification) = value; + case BundleType::kBundleEnableNotificationType: + bundleInfo.SetEnableNotification(value); + storeDBResult = preferncesDB_->PutNotificationsEnabledForBundle(bundleName, value); break; default: break; } + ErrCode result = ERR_OK; + if (!storeDBResult) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + return result; } template ErrCode NotificationPreferences::GetBundleProperty( - const std::string &bundleName, const BundlePropertyType &type, T &value) + const std::string &bundleName, const BundleType &type, T &value) const { ErrCode result = ERR_OK; - auto preferencesIter = preferencesInfo_.infos.find(bundleName); - if (preferencesIter != preferencesInfo_.infos.end()) { + NotificationPreferencesInfo::BundleInfo bundleInfo; + if (preferencesInfo_.GetBundleInfo(bundleName, bundleInfo)) { switch (type) { - case BundlePropertyType::kBundleImportanceType: - value = preferencesIter->second.importance; + case BundleType::kBundleImportanceType: + value = bundleInfo.GetImportance(); break; - case BundlePropertyType::kBundleBadgeTotalNumType: - value = preferencesIter->second.badgeTotalNum; + case BundleType::kBundleBadgeTotalNumType: + value = bundleInfo.GetBadgeTotalNum(); break; - case BundlePropertyType::kBundleShowBadgeType: - value = preferencesIter->second.isShowBadge; + case BundleType::kBundleShowBadgeType: + value = bundleInfo.GetIsShowBadge(); break; - case BundlePropertyType::kBundlePrivateAllowedType: - value = preferencesIter->second.isPrivateAllowed; + case BundleType::kBundlePrivateAllowedType: + value = bundleInfo.GetIsPrivateAllowed(); break; - case BundlePropertyType::kBundleEnableNotificationType: - value = preferencesIter->second.isEnabledNotification; + case BundleType::kBundleEnableNotificationType: + value = bundleInfo.GetEnableNotification(); break; default: result = ERR_ANS_INVALID_PARAM; @@ -802,403 +698,12 @@ ErrCode NotificationPreferences::GetBundleProperty( return result; } -void NotificationPreferences::AddSlotToJson( - nlohmann::json &json, const std::string &bundleName, const sptr &slot) const +void NotificationPreferences::OnDistributedKvStoreDeathRecipient() { - auto packageJsonIter = json[kBundle].begin(); - while (packageJsonIter != json[kBundle].end()) { - if (!bundleName.compare((*packageJsonIter)[kBundleName].get())) { - (*packageJsonIter)[kSlot].emplace_back(SlotToJson(slot)); - break; - } - ++packageJsonIter; + if (preferncesDB_ != nullptr) { + preferncesDB_->StoreDeathRecipient(preferencesInfo_); } } -void NotificationPreferences::AddSlotGroupToJson( - nlohmann::json &json, const std::string &bundleName, const sptr &group) const -{ - auto packageJsonIter = json[kBundle].begin(); - while (packageJsonIter != json[kBundle].end()) { - if (!bundleName.compare((*packageJsonIter)[kBundleName].get())) { - (*packageJsonIter)[kGroup].emplace_back(GroupToJson(group)); - break; - } - ++packageJsonIter; - } -} - -void NotificationPreferences::UpdateExsitSlotTypeInJson( - nlohmann::json &json, const std::string &bundleName, const sptr &slot) const -{ - for (auto &packageJsonIter : json[kBundle]) { - if (bundleName.compare(packageJsonIter[kBundleName].get())) { - continue; - } - - for (auto &slotJsonIter : packageJsonIter[kSlot]) { - if (slot->GetType() == slotJsonIter[kSlotType].get()) { - slotJsonIter[kSlotId] = slot->GetId(); - slotJsonIter[kSlotName] = slot->GetName(); - slotJsonIter[kSlotDescription] = slot->GetDescription(); - break; - } - } - } -} - -void NotificationPreferences::RemoveSlotInJson( - nlohmann::json &json, const std::string &bundleName, const NotificationConstant::SlotType &type) const -{ - for (auto &packageJsonIter : json[kBundle]) { - if (bundleName.compare(packageJsonIter[kBundleName].get())) { - continue; - } - - auto slotJsonIter = packageJsonIter[kSlot].begin(); - while (slotJsonIter != packageJsonIter[kSlot].end()) { - if (type == (*slotJsonIter)[kSlotType].get()) { - packageJsonIter[kSlot].erase(slotJsonIter); - break; - } - ++slotJsonIter; - } - } -} - -void NotificationPreferences::UpdateSlotInJson( - nlohmann::json &json, const std::string &bundleName, const sptr &slot) const -{ - for (auto &packageJsonIter : json[kBundle]) { - if (bundleName.compare(packageJsonIter[kBundleName].get())) { - continue; - } - - auto slotJsonIter = packageJsonIter[kSlot].begin(); - while (slotJsonIter != packageJsonIter[kSlot].end()) { - if (!slot->GetId().compare((*slotJsonIter)[kSlotId].get())) { - nlohmann::json tempSlotJson = SlotToJson(slot); - (*slotJsonIter).update(tempSlotJson.begin(), tempSlotJson.end()); - break; - } - ++slotJsonIter; - } - } -} - -void NotificationPreferences::RemoveSlotGroupInJson( - nlohmann::json &json, const std::string &bundleName, const std::string &groupId) const -{ - for (auto &packageJsonIter : json[kBundle]) { - if (bundleName.compare(packageJsonIter[kBundleName].get())) { - continue; - } - - auto groupJsonIter = packageJsonIter[kGroup].begin(); - while (groupJsonIter != packageJsonIter[kGroup].end()) { - if (!groupId.compare((*groupJsonIter)[kGroupId].get())) { - packageJsonIter[kGroup].erase(groupJsonIter); - break; - } - ++groupJsonIter; - } - } -} - -void NotificationPreferences::UpdateSlotGroupInJson( - nlohmann::json &json, const std::string &bundleName, const sptr &group) const -{ - for (auto &packageJsonIter : json[kBundle]) { - if (bundleName.compare(packageJsonIter[kBundleName].get())) { - continue; - } - - auto groupJsonIter = packageJsonIter[kGroup].begin(); - while (groupJsonIter != packageJsonIter[kGroup].end()) { - if (!group->GetId().compare((*groupJsonIter)[kGroupId].get())) { - nlohmann::json tempGroupJson = GroupToJson(group); - (*groupJsonIter).update(tempGroupJson.begin(), tempGroupJson.end()); - break; - } - ++groupJsonIter; - } - } -} - -void NotificationPreferences::RemoveBundleInJson(nlohmann::json &json, const std::string &bundleName) -{ - auto packageJsonIter = json[kBundle].begin(); - while (packageJsonIter != json[kBundle].end()) { - if (!bundleName.compare((*packageJsonIter)[kBundleName].get())) { - json[kBundle].erase(packageJsonIter); - break; - } - ++packageJsonIter; - } -} - -void NotificationPreferences::AddJson(nlohmann::json &json, const BundleInfo &info, - const NotificationConstant::DisturbMode &mode, const bool &enable) const -{ - nlohmann::json preferencesJson = BundlePropertyToJson(info); - if (!info.groups.empty()) { - for (auto groupIter : info.groups) { - preferencesJson[kGroup].emplace_back(GroupToJson(groupIter.second)); - } - } - - if (!info.slots.empty()) { - for (auto slotIter : info.slots) { - preferencesJson[kSlot].emplace_back(SlotToJson(slotIter.second)); - } - } - json[kBundle].emplace_back(preferencesJson); - - if (json[kDisturbMode].is_null()) { - json[kDisturbMode] = mode; - } - - if (json[kEnable].is_null()) { - json[kEnable] = enable; - } -} - -void NotificationPreferences::ParseFromJson() -{ - if (paraseJson_.empty() || !paraseJson_.contains(kBundle)) { - ANS_LOGE("Current file is empty."); - return; - } - preferencesInfo_.disturbMode = paraseJson_[kDisturbMode].get(); - preferencesInfo_.isEnabledAllNotification = paraseJson_[kEnable].get(); - for (auto packageIter : paraseJson_[kBundle]) { - BundleInfo bundleInfo; - JsonToBundleProperty(packageIter, bundleInfo); - preferencesInfo_.infos.emplace(std::make_pair(bundleInfo.bundleName, bundleInfo)); - for (auto groupIter : packageIter[kGroup]) { - sptr group = new NotificationSlotGroup( - groupIter[kGroupId].get(), groupIter[kGroupName].get()); - JsonToGroup(groupIter, group); - preferencesInfo_.infos.at(bundleInfo.bundleName).groups.emplace(std::make_pair(group->GetId(), group)); - } - - for (auto &slotIter : packageIter[kSlot]) { - sptr slot = - new NotificationSlot(slotIter[kSlotType].get()); - JsonToSlot(slotIter, slot); - preferencesInfo_.infos.at(bundleInfo.bundleName).slots.emplace(std::make_pair(slot->GetType(), slot)); - } - } -} - -ErrCode NotificationPreferences::ParseNotification() -{ - std::ifstream inputFile(kStoreFile, std::ifstream::in); - CheckInvalidPath(inputFile); - if (IsEmptyInputFile(inputFile)) { - return ERR_ANS_PREFERENCES_FILE_IS_NULL; - } - - ErrCode result = ERR_OK; - try { - paraseJson_ = nlohmann::json::parse(inputFile); - inputFile.close(); - } catch (const nlohmann::detail::exception &e) { - ANS_LOGE("Exception file error is: %{public}s", e.what()); - paraseJson_.clear(); - result = ERR_ANS_PREFERENCES_FILE_EXCEPTION; - } - if (result == ERR_OK) { - ParseFromJson(); - } - return result; -} - -ErrCode NotificationPreferences::StoreNotification(const nlohmann::json &json) const -{ - std::ofstream outFile(kStoreFile, std::ofstream::out); - CheckInvalidPath(outFile); - - outFile.exceptions(std::ofstream::failbit | std::ofstream::badbit); - ErrCode result = ERR_OK; - try { - outFile << json.dump(kJsonDump); - outFile.flush(); - outFile.close(); - } catch (std::ofstream::failure e) { - ANS_LOGE("Exception file error is: %{public}s", e.what()); - result = ERR_ANS_PREFERENCES_FILE_EXCEPTION; - } - return result; -} - -ErrCode NotificationPreferences::CommitNotification( - const nlohmann::json ¶seJson, const PreferencesInfo &preferencesInfo) -{ - ErrCode result = StoreNotification(paraseJson); - - if (result == ERR_OK) { - preferencesInfo_ = preferencesInfo; - paraseJson_ = paraseJson; - } - return result; -} - -template -void NotificationPreferences::CheckInvalidPath(T &t) const -{ - if (!t.is_open()) { - ANS_LOGI("File does not open, create a new dir"); - InitDir(); - InitFile(); - } -} - -bool NotificationPreferences::IsEmptyInputFile(std::ifstream &inputFile) const -{ - inputFile.seekg(0, inputFile.end); - if (0 == inputFile.tellg()) { - ANS_LOGI("InputFile is empty, does not parase json file."); - return true; - } - inputFile.seekg(0, inputFile.beg); - return false; -} - -void NotificationPreferences::InitDir() const -{ - if (IsExistDir(kStorePath)) { - ANS_LOGI("Path already exists."); - return; - } - - if (!CreateDirectory(kStorePath)) { - ANS_LOGE("create path failed %{public}s", strerror(errno)); - } -} - -void NotificationPreferences::InitFile() const -{ - if (IsExistFile(kStorePath, kStoreFile)) { - ANS_LOGI("File already exists."); - return; - } - - if (!CreateAndChangeFileAttr(kStoreFile)) { - ANS_LOGE("Change file attr failed %{public}s", strerror(errno)); - } -} - -bool NotificationPreferences::IsExistDir(const std::string &path) const -{ - struct stat buf = {}; - if (stat(path.c_str(), &buf) != 0) { - return false; - } - return S_ISDIR(buf.st_mode); -} - -bool NotificationPreferences::IsExistFile(const std::string &dirPath, const std::string &filePath) const -{ - std::vector files; - OHOS::GetDirFiles(dirPath, files); - auto iter = - std::find_if(files.begin(), files.end(), [&filePath](std::string &path) { return !path.compare(filePath); }); - - if (iter != files.end()) { - return true; - } - return false; -} - -bool NotificationPreferences::CreateDirectory(const std::string &path) const -{ - if (!OHOS::ForceCreateDirectory(path)) { - ANS_LOGE("mkdir failed"); - return false; - } - mode_t mode = S_IRWXU | S_IRGRP; - return OHOS::ChangeModeDirectory(path, mode); -} - -bool NotificationPreferences::CreateAndChangeFileAttr(const std::string &filePath) const -{ - std::ofstream outFile(filePath, std::ofstream::out); - if (outFile.is_open()) { - outFile.clear(); - outFile.close(); - ANS_LOGI("Create a json file."); - } - mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP; - return OHOS::ChangeModeFile(filePath, mode); -} - -nlohmann::json NotificationPreferences::BundlePropertyToJson(const BundleInfo &bundleInfo) const -{ - return nlohmann::json{{kBundleName, bundleInfo.bundleName}, - {kBundleImportance, bundleInfo.importance}, - {kBundleShowBadge, bundleInfo.isShowBadge}, - {kBundleBadgeTotalNum, bundleInfo.badgeTotalNum}, - {kBundlePrivateAllowed, bundleInfo.isPrivateAllowed}, - {kBundleEnableNotification, bundleInfo.isEnabledNotification}}; -} - -nlohmann::json NotificationPreferences::GroupToJson(const sptr &group) const -{ - return nlohmann::json{{kGroupId, group->GetId()}, - {kGroupName, group->GetName()}, - {kGroupDescription, group->GetDescription()}, - {kGroupDisable, group->IsDisabled()}}; -} - -nlohmann::json NotificationPreferences::SlotToJson(const sptr &slot) const -{ - return nlohmann::json{{kSlotGroupId, slot->GetSlotGroup()}, - {kSlotId, slot->GetId()}, - {kSlotName, slot->GetName()}, - {kSlotDescription, slot->GetDescription()}, - {kSlotLevel, slot->GetLevel()}, - {kSlotShowBadge, slot->IsShowBadge()}, - {kSlotEnableLight, slot->CanEnableLight()}, - {kSlotEnableVrbration, slot->CanVibrate()}, - {kSlotLedLightColor, slot->GetLedLightColor()}, - {kSlotLockscreenVisibleness, slot->GetLockScreenVisibleness()}, - {kSlotSound, slot->GetSound().ToString()}, - {kSlotVibrationSytle, slot->GetVibrationStyle()}, - {kSlotEnableBypassDnd, slot->IsEnableBypassDnd()}, - {kSlotType, slot->GetType()}}; -} - -void NotificationPreferences::JsonToBundleProperty(nlohmann::json &json, BundleInfo &bundleInfo) const -{ - json.at(kBundleName).get_to(bundleInfo.bundleName); - json.at(kBundleImportance).get_to(bundleInfo.importance); - json.at(kBundleShowBadge).get_to(bundleInfo.isShowBadge); - json.at(kBundleBadgeTotalNum).get_to(bundleInfo.badgeTotalNum); - json.at(kBundlePrivateAllowed).get_to(bundleInfo.isPrivateAllowed); - json.at(kBundleEnableNotification).get_to(bundleInfo.isEnabledNotification); -} - -void NotificationPreferences::JsonToGroup(nlohmann::json &json, sptr &group) const -{ - group->SetDescription(json[kGroupDescription].get()); -} - -void NotificationPreferences::JsonToSlot(nlohmann::json &json, sptr &slot) const -{ - slot->SetSlotGroup(json[kSlotGroupId].get()); - slot->SetDescription(json[kSlotDescription].get()); - slot->SetLevel(json[kSlotLevel].get()); - slot->EnableBadge(json[kSlotShowBadge].get()); - slot->SetEnableLight(json[kSlotEnableLight].get()); - slot->SetLedLightColor(json[kSlotLedLightColor].get()); - slot->SetLockscreenVisibleness(json[kSlotLockscreenVisibleness].get()); - Uri uri(json[kSlotSound].get()); - slot->SetSound(uri); - slot->SetVibrationStyle(json[kSlotVibrationSytle].get>()); - slot->EnableBypassDnd(json[kSlotEnableBypassDnd].get()); - slot->SetType(json[kSlotType].get()); -} - } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98c59565439cda6199c88eca298f5af7193306cb --- /dev/null +++ b/services/ans/src/notification_preferences_database.cpp @@ -0,0 +1,1114 @@ +/* + * 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_preferences_database.h" + +#include +#include +#include + +#include "ans_log_wrapper.h" + +#include "uri.h" +namespace OHOS { +namespace Notification { + +const std::map &, std::string &)>> + NotificationPreferencesDatabase::slotMap_ = { + {kSlotGroupId, + std::bind(&NotificationPreferencesDatabase::ParseSlotGroupId, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {kSlotDescription, + std::bind(&NotificationPreferencesDatabase::ParseSlotDescription, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kSlotLevel, + std::bind(&NotificationPreferencesDatabase::ParseSlotLevel, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {kSlotShowBadge, + std::bind(&NotificationPreferencesDatabase::ParseSlotShowBadge, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kSlotEnableLight, + std::bind(&NotificationPreferencesDatabase::ParseSlotEnableLight, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kSlotEnableVrbration, + std::bind(&NotificationPreferencesDatabase::ParseSlotEnableVrbration, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kSlotLedLightColor, + std::bind(&NotificationPreferencesDatabase::ParseSlotLedLightColor, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kSlotLockscreenVisibleness, + std::bind(&NotificationPreferencesDatabase::ParseSlotLockscreenVisibleness, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kSlotSound, + std::bind(&NotificationPreferencesDatabase::ParseSlotSound, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {kSlotVibrationSytle, + std::bind(&NotificationPreferencesDatabase::ParseSlotVibrationSytle, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kSlotEnableBypassDnd, + std::bind(&NotificationPreferencesDatabase::ParseSlotEnableBypassDnd, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}}; + +const std::map> + NotificationPreferencesDatabase::bundleMap_ = { + {kBundleName, + std::bind(&NotificationPreferencesDatabase::ParseBundleName, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {kBundleImportance, + std::bind(&NotificationPreferencesDatabase::ParseBundleImportance, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kBundleShowBadge, + std::bind(&NotificationPreferencesDatabase::ParseBundleShowBadge, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kBundleBadgeTotalNum, + std::bind(&NotificationPreferencesDatabase::ParseBundleBadgeNum, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kBundlePrivateAllowed, + std::bind(&NotificationPreferencesDatabase::ParseBundlePrivateAllowed, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {kBundleEnableNotification, + std::bind(&NotificationPreferencesDatabase::ParseBundleEnableNotification, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}}; + +NotificationPreferencesDatabase::NotificationPreferencesDatabase() +{ + TryTwice([this] { return GetKvStore(); }); +} + +NotificationPreferencesDatabase::~NotificationPreferencesDatabase() +{ + CloseKvStore(); +} + +void NotificationPreferencesDatabase::TryTwice(const std::function &func) const +{ + OHOS::DistributedKv::Status status = func(); + if (status != OHOS::DistributedKv::Status::SUCCESS) { + status = func(); + ANS_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } +} + +OHOS::DistributedKv::Status NotificationPreferencesDatabase::GetKvStore() +{ + OHOS::DistributedKv::Status status; + OHOS::DistributedKv::Options options = {.createIfMissing = true, + .encrypt = false, + .autoSync = true, + .kvStoreType = OHOS::DistributedKv::KvStoreType::SINGLE_VERSION}; + dataManager_.GetSingleKvStore(options, + appId_, + storeId_, + [this, &status](OHOS::DistributedKv::Status paramStatus, + std::unique_ptr + singleKvStore) { + status = paramStatus; + if (status != OHOS::DistributedKv::Status::SUCCESS) { + ANS_LOGE("return error: %{public}d", status); + return; + } + { + kvStorePtr_ = std::move(singleKvStore); + } + ANS_LOGD("get kvStore success"); + }); + return status; +} + +void NotificationPreferencesDatabase::CloseKvStore() +{ + dataManager_.CloseKvStore(appId_, std::move(kvStorePtr_)); +} + +bool NotificationPreferencesDatabase::CheckKvStore() +{ + if (kvStorePtr_ != nullptr) { + return true; + } + TryTwice([this] { return GetKvStore(); }); + return kvStorePtr_ != nullptr; +} + +bool NotificationPreferencesDatabase::ResetStore() +{ + kvStorePtr_ = nullptr; + int32_t tryTimes = MAX_TIMES; + while (tryTimes > 0) { + OHOS::DistributedKv::Status status = GetKvStore(); + if (status == OHOS::DistributedKv::Status::SUCCESS && kvStorePtr_ != nullptr) { + return true; + } + ANS_LOGW("CheckKvStore, Times: %{public}d", tryTimes); + usleep(SLEEP_INTERVAL); + tryTimes--; + } + return false; +} + +bool NotificationPreferencesDatabase::PutSlotsToDisturbeDB( + const std::string &bundleName, const std::vector> &slots) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + if (bundleName.empty()) { + ANS_LOGE("Bundle Name is Null"); + return false; + } + + if (slots.empty()) { + ANS_LOGE("Slot is empty"); + return false; + } + + bool result = true; + std::vector entries; + for (auto iter : slots) { + result = SlotToEntry(bundleName, iter, entries); + if (!result) { + return result; + } + } + + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return false; + } + OHOS::DistributedKv::Status status = kvStorePtr_->PutBatch(entries); + return (status == OHOS::DistributedKv::Status::SUCCESS); +} + +bool NotificationPreferencesDatabase::PutGroupsToDisturbeDB( + const std::string &bundleName, const std::vector> &groups) +{ + if (bundleName.empty()) { + ANS_LOGE("Bundle Name is Null"); + return false; + } + + if (groups.empty()) { + ANS_LOGE("Slot is empty"); + return false; + } + + bool result = true; + std::vector entries; + for (auto iter : groups) { + result = GroupToEntry(bundleName, iter, entries); + if (!result) { + return result; + } + } + + if (!CheckKvStore()) { + 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) +{ + if (bundleName.empty()) { + ANS_LOGE("Bundle Name is Null"); + return false; + } + + if (!CheckBundle(bundleName)) { + return false; + } + OHOS::DistributedKv::Status status = + PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleShowBadgeType, enable); + return (status == OHOS::DistributedKv::Status::SUCCESS); +} + +bool NotificationPreferencesDatabase::PutImportance(const std::string &bundleName, const int &importance) +{ + if (bundleName.empty()) { + ANS_LOGE("Bundle Name is Null"); + return false; + } + + if (!CheckBundle(bundleName)) { + return false; + } + OHOS::DistributedKv::Status status = + PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleImportanceType, importance); + return (status == OHOS::DistributedKv::Status::SUCCESS); +} + +bool NotificationPreferencesDatabase::PutTotalBadgeNums(const std::string &bundleName, const int &totalBadgeNum) +{ + if (bundleName.empty()) { + ANS_LOGE("Bundle Name is Null"); + return false; + } + + if (!CheckBundle(bundleName)) { + return false; + } + + OHOS::DistributedKv::Status status = + PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleBadgeTotalNumType, totalBadgeNum); + return (status == OHOS::DistributedKv::Status::SUCCESS); +} + +bool NotificationPreferencesDatabase::PutPrivateNotificationsAllowed(const std::string &bundleName, const bool &allow) +{ + if (bundleName.empty()) { + ANS_LOGE("Bundle Name is Null"); + return false; + } + + if (!CheckBundle(bundleName)) { + return false; + } + OHOS::DistributedKv::Status status = + PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundlePrivateAllowedType, allow); + + return (status == OHOS::DistributedKv::Status::SUCCESS); +} + +bool NotificationPreferencesDatabase::PutNotificationsEnabledForBundle( + const std::string &bundleName, const bool &enabled) +{ + if (bundleName.empty()) { + ANS_LOGE("Bundle Name is Null"); + return false; + } + + if (!CheckBundle(bundleName)) { + return false; + } + + OHOS::DistributedKv::Status status = + PutBundlePropertyToDisturbeDB(bundleName, BundleType::kBundleEnableNotificationType, enabled); + return (status == OHOS::DistributedKv::Status::SUCCESS); +} + +bool NotificationPreferencesDatabase::PutNotificationsEnabled(const bool &enabled) +{ + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return false; + } + + OHOS::DistributedKv::Key enableKey(kEnable); + OHOS::DistributedKv::Value enableValue(std::to_string(enabled)); + OHOS::DistributedKv::Status status; + status = kvStorePtr_->Put(enableKey, enableValue); + if (status != OHOS::DistributedKv::Status::SUCCESS) { + ANS_LOGE("Store enable notification failed. %{public}d", status); + return false; + } + return true; +} + +bool NotificationPreferencesDatabase::PutDisturbMode(const NotificationConstant::DisturbMode &mode) +{ + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return false; + } + + OHOS::DistributedKv::Key disturbModeKey(kDisturbMode); + OHOS::DistributedKv::Value disturbModeValue(std::to_string(mode)); + OHOS::DistributedKv::Status status; + status = kvStorePtr_->Put(disturbModeKey, disturbModeValue); + if (status != OHOS::DistributedKv::Status::SUCCESS) { + ANS_LOGE("Store disturbe modeFailed. %{public}d", status); + return false; + } + return true; +} + +void NotificationPreferencesDatabase::GetValueFromDisturbeDB( + const std::string &key, std::function funcion) +{ + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return; + } + + OHOS::DistributedKv::Status status; + OHOS::DistributedKv::Value value; + OHOS::DistributedKv::Key getKey(key); + status = kvStorePtr_->Get(getKey, value); + if (status != OHOS::DistributedKv::Status::SUCCESS) { + ANS_LOGE("Get value failed, use defalut value. error code is %{public}d", status); + return; + } + + if (value.Empty()) { + ANS_LOGE("Get value is empty, use defalut value. error code is %{public}d", value.Empty()); + return; + } + funcion(value); +} + +void NotificationPreferencesDatabase::GetValueFromDisturbeDB( + const std::string &key, std::function funcion) +{ + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return; + } + + OHOS::DistributedKv::Status status; + OHOS::DistributedKv::Value value; + OHOS::DistributedKv::Key getKey(key); + status = kvStorePtr_->Get(getKey, value); + funcion(status, value); +} + +bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleName) +{ + std::string bundleKeyStr = kBundleLabel + bundleName; + bool result = true; + GetValueFromDisturbeDB(bundleKeyStr, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { + switch (status) { + case OHOS::DistributedKv::Status::KEY_NOT_FOUND: { + result = PutBundleToDisturbeDB(bundleName); + break; + } + case OHOS::DistributedKv::Status::SUCCESS: { + result = true; + break; + } + default: + result = false; + break; + } + }); + return result; +} + +bool NotificationPreferencesDatabase::InitBundlePropertyValueToDisturbeDB(const std::string &bundleName) +{ + 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); + GenerateEntry( + GenerateBundleKey(bundleName, kBundlePrivateAllowed), std::to_string(BUNDLE_PRIVATE_ALLOWED), entries); + GenerateEntry( + GenerateBundleKey(bundleName, kBundleEnableNotification), std::to_string(BUNDLE_ENABLE_NOTIFICATION), entries); + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return false; + } + OHOS::DistributedKv::Status status = kvStorePtr_->PutBatch(entries); + if (status != OHOS::DistributedKv::Status::SUCCESS) { + ANS_LOGE("Store bundle failed. %{public}d", status); + return false; + } + return true; +} + +bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreferencesInfo &info) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + ParseDisturbeMode(info); + ParseEnableAllNotification(info); + + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return false; + } + OHOS::DistributedKv::Status status; + std::vector entries; + status = kvStorePtr_->GetEntries({kBundleLabel}, entries); + if (status != OHOS::DistributedKv::Status::SUCCESS) { + ANS_LOGE("Get Bundle Info failed."); + return false; + } + ParseBundleFromDistureDB(info, entries); + return true; +} + +bool NotificationPreferencesDatabase::RemoveAllBundleFromDisturbeDB() +{ + ANS_LOGD("%{public}s", __FUNCTION__); + if (!CheckKvStore()) { + 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) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return false; + } + + OHOS::DistributedKv::Status status; + std::vector entries; + status = kvStorePtr_->GetEntries({kAnsBundle + kUnderLine + bundleName + kUnderLine}, entries); + + if (status != OHOS::DistributedKv::Status::SUCCESS) { + ANS_LOGE("Get Bundle Info failed."); + return false; + } + + std::vector keys; + for (auto iter : entries) { + keys.push_back(iter.key); + } + + OHOS::DistributedKv::Key bundleKey({kBundleLabel + kBundleName + kUnderLine + bundleName}); + keys.push_back(bundleKey); + status = kvStorePtr_->DeleteBatch(keys); + if (status != OHOS::DistributedKv::Status::SUCCESS) { + ANS_LOGE("delete bundle Info failed."); + return false; + } + return true; +} + +bool NotificationPreferencesDatabase::RemoveSlotFromDisturbeDB( + const std::string &bundleName, const NotificationConstant::SlotType &type) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + if (bundleName.empty()) { + ANS_LOGE("Bundle Name is Null"); + return false; + } + + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return false; + } + + OHOS::DistributedKv::Status status; + std::vector slotentries; + std::string slotType = kSlotType + std::to_string(type); + status = kvStorePtr_->GetEntries({GenerateSlotKey(bundleName, slotType) + kUnderLine}, slotentries); + if (status != DistributedKv::Status::SUCCESS) { + return false; + } + std::vector keys; + for (auto iter : slotentries) { + 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); + + return true; +} + +bool NotificationPreferencesDatabase::RemoveGroupsFromDisturbeDB( + const std::string &bundleName, const std::vector &groupIds) +{ + if (bundleName.empty()) { + ANS_LOGE("Bundle Name is Null"); + return false; + } + + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return false; + } + + std::vector keys; + bool result = true; + for (auto iter : groupIds) { + result = GetRemoveGroupKeysFromDisturbeDB(bundleName, 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; +} + +bool NotificationPreferencesDatabase::GetRemoveGroupKeysFromDisturbeDB( + const std::string &bundleName, const std::string &groupId, std::vector &keys) +{ + if (!CheckKvStore()) { + 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); + if (status != DistributedKv::Status::SUCCESS) { + return false; + } + for (auto iter : groupentries) { + 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) +{ + ANS_LOGW("distribute remote died"); + bool result = ResetStore(); + if (result) { + ParseFromDisturbeDB(info); + } else { + ANS_LOGE("db try connect failed"); + } + return result; +} + +template +OHOS::DistributedKv::Status NotificationPreferencesDatabase::PutBundlePropertyToDisturbeDB( + const std::string &bundleName, const BundleType &type, const T &t) +{ + std::string keyStr; + switch (type) { + case BundleType::kBundleBadgeTotalNumType: + keyStr = GenerateBundleKey(bundleName, kBundleBadgeTotalNum); + break; + case BundleType::kBundleImportanceType: + keyStr = GenerateBundleKey(bundleName, kBundleImportance); + break; + case BundleType::kBundleShowBadgeType: + keyStr = GenerateBundleKey(bundleName, kBundleShowBadge); + break; + case BundleType::kBundlePrivateAllowedType: + keyStr = GenerateBundleKey(bundleName, kBundlePrivateAllowed); + break; + case BundleType::kBundleEnableNotificationType: + keyStr = GenerateBundleKey(bundleName, kBundleEnableNotification); + 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; + } + status = kvStorePtr_->Put(key, value); + return status; +} + +bool NotificationPreferencesDatabase::PutBundleToDisturbeDB(const std::string &bundleName) +{ + if (!CheckKvStore()) { + 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_LOGE("Store bundle name to db is failed."); + return false; + } + + if (!InitBundlePropertyValueToDisturbeDB(bundleName)) { + return false; + } + + return true; +} + +void NotificationPreferencesDatabase::GenerateEntry( + const std::string &key, const std::string &value, std::vector &entries) +{ + OHOS::DistributedKv::Entry entry; + OHOS::DistributedKv::Key dbKey(key); + OHOS::DistributedKv::Value dbValue(value); + entry.key = dbKey; + entry.value = dbValue; + entries.push_back(entry); +} + +bool NotificationPreferencesDatabase::SlotToEntry( + const std::string &bundleName, const sptr &slot, std::vector &entries) +{ + if (slot == nullptr) { + ANS_LOGE("Notification group is nullptr"); + return false; + } + + if (!CheckBundle(bundleName)) { + return false; + } + + GenerateSlotEntry(bundleName, slot, entries); + return true; +} + +void NotificationPreferencesDatabase::GenerateSlotEntry( + const std::string &bundleName, const sptr &slot, std::vector &entries) +{ + 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); + GenerateEntry( + GenerateSlotKey(bundleName, slotType, kSlotEnableLight), std::to_string(slot->CanEnableLight()), entries); + GenerateEntry( + GenerateSlotKey(bundleName, slotType, kSlotEnableVrbration), std::to_string(slot->CanVibrate()), entries); + GenerateEntry( + GenerateSlotKey(bundleName, slotType, kSlotLedLightColor), std::to_string(slot->GetLedLightColor()), entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotLockscreenVisibleness), + std::to_string(static_cast(slot->GetLockScreenVisibleness())), + entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotSound), slot->GetSound().ToString(), entries); + GenerateEntry(GenerateSlotKey(bundleName, slotType, kSlotEnableBypassDnd), + std::to_string(slot->IsEnableBypassDnd()), + entries); + GenerateEntry( + GenerateSlotKey(bundleName, slotType, kSlotVibrationSytle), VectorToString(slot->GetVibrationStyle()), entries); +} + +bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleName, + const sptr &group, std::vector &entries) +{ + + if (group == nullptr) { + ANS_LOGE("Notification group is nullptr"); + return false; + } + + if (!CheckBundle(bundleName)) { + return false; + } + + GenerateGroupEntry(bundleName, group, entries); + return true; +} + +void NotificationPreferencesDatabase::GenerateGroupEntry(const std::string &bundleName, + const sptr &group, std::vector &entries) +{ + 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); + GenerateEntry( + GenerateGroupKey(bundleName, groupLebal + kGroupDisable), std::to_string(group->IsDisabled()), entries); +} + +void NotificationPreferencesDatabase::ParseBundleFromDistureDB( + NotificationPreferencesInfo &info, const std::vector &entries) +{ + if (!CheckKvStore()) { + 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::vector bundleEntries; + kvStorePtr_->GetEntries({GenerateBundleKey(bundleName)}, bundleEntries); + ANS_LOGD("bundle key is %{public}s", GenerateBundleKey(bundleName).c_str()); + NotificationPreferencesInfo::BundleInfo bunldeInfo; + for (auto bundleEntry : bundleEntries) { + if (bundleEntry.key.ToString().find(kSlot) != std::string::npos) { + ParseSlotFromDisturbeDB(bunldeInfo, bundleName, bundleEntry); + } else if (bundleEntry.key.ToString().find(kGroup) != std::string::npos) { + ParseGroupFromDisturbeDB(bunldeInfo, bundleName, bundleEntry); + } else { + ParseBundlePropertyFromDisturbeDB(bunldeInfo, bundleEntry.key, bundleEntry.value); + } + } + + info.SetBundleInfo(bunldeInfo); + } +} + +void NotificationPreferencesDatabase::ParseSlotFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, + const std::string &bundleName, const OHOS::DistributedKv::Entry &entry) +{ + std::string slotKey = entry.key.ToString(); + + NotificationConstant::SlotType slotType = + static_cast(stoi(SubUniqueIdentifyFromString(slotKey), nullptr)); + sptr slot = nullptr; + if (!bundleInfo.GetSlot(slotType, slot)) { + slot = new NotificationSlot(slotType); + } + ParseSlot(slot, entry); + bundleInfo.SetSlot(slot); +} + +void NotificationPreferencesDatabase::ParseGroupFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, + const std::string &bundleName, const OHOS::DistributedKv::Entry &entry) +{ + if (!CheckKvStore()) { + ANS_LOGE("KvStore is nullptr"); + return; + } + std::string groupKey = entry.key.ToString(); + std::string groupId = SubUniqueIdentifyFromString(groupKey); + sptr group; + if (!bundleInfo.GetGroup(groupId, group)) { + std::string groupName; + std::string groupNameKey = GenerateGroupKey(bundleName, groupId + kUnderLine + kGroupName); + GetValueFromDisturbeDB( + groupNameKey, [&groupName](OHOS::DistributedKv::Value &value) { groupName = value.ToString(); }); + if (groupName.empty()) { + ANS_LOGE("Group name does not exsited."); + return; + } + group = new NotificationSlotGroup(groupId, groupName); + } + + ParseGroupDescription(group, entry); + bundleInfo.SetGroup(group); +} + +void NotificationPreferencesDatabase::ParseBundlePropertyFromDisturbeDB( + NotificationPreferencesInfo::BundleInfo &bundleInfo, const OHOS::DistributedKv::Key &key, + const OHOS::DistributedKv::Value &value) +{ + 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()); + + auto iter = bundleMap_.find(typeStr); + if (iter != bundleMap_.end()) { + auto func = iter->second; + func(this, bundleInfo, valueStr); + } +} + +void NotificationPreferencesDatabase::ParseSlot(sptr &slot, const OHOS::DistributedKv::Entry &entry) +{ + std::string typeStr = FindLastString(entry.key.ToString()); + std::string valueStr = entry.value.ToString(); + ANS_LOGD("db key = %{public}s , type str %{public}s , value is %{public}s ", + entry.key.ToString().c_str(), + typeStr.c_str(), + entry.value.ToString().c_str()); + + auto iter = slotMap_.find(typeStr); + if (iter != slotMap_.end()) { + auto func = iter->second; + func(this, slot, valueStr); + } +} + +std::string NotificationPreferencesDatabase::FindLastString(const std::string &inputString) const +{ + std::string keyStr; + size_t pos = inputString.find_last_of(kUnderLine); + if (pos != std::string::npos) { + keyStr = inputString.substr(pos + 1); + } + return keyStr; +} + +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())); + return streamStr.str(); +} + +void NotificationPreferencesDatabase::StringToVector(const std::string &str, std::vector &data) const +{ + if (str.empty()) { + 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)); + StringToVector(afterStr, data); + } +} + +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 + * + */ + std::string key = GenerateBundleKey(bundleKey).append(kSlot); + if (!type.empty()) { + key.append(kUnderLine).append(type); + } + if (!subType.empty()) { + key.append(kUnderLine).append(subType); + } + ANS_LOGD("Slot key is : %{public}s", key.c_str()); + return key; +} + +std::string NotificationPreferencesDatabase::GenerateGroupKey( + const std::string &bundleKey, const std::string &type) const +{ + /*group key + * + * ans_bundle_bundlename_group_group_id0_name + * ans_bundle_bundlename_group_group_id1_name + * + */ + std::string key = GenerateBundleKey(bundleKey).append(kGroup); + if (!type.empty()) { + key.append(kUnderLine).append(type); + } + 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 +{ + /*bundle key + * + * label_ans_bundle_name = "" + * ans_bundle_bundlename_ + * ans_bundle_bundlename_ + * ans_bundle_bundlename_ + * ans_bundle_bundlename_ + * + */ + std::string key = std::string().append(kAnsBundle).append(kUnderLine).append(bundleName).append(kUnderLine); + if (!type.empty()) { + key.append(type); + } + ANS_LOGD("Bundle key : %{public}s", key.c_str()); + return key; +} + +std::string NotificationPreferencesDatabase::SubUniqueIdentifyFromString(const std::string &keyStr) const +{ + std::string slotType; + size_t pos = keyStr.find_last_of(kUnderLine); + if (pos != std::string::npos) { + slotType = FindLastString(keyStr.substr(0, pos)); + } + + return slotType; +} + +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))); + } + } 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))); + } + } else { + ANS_LOGD("Parse enable all notification failed, use defalut value."); + } + }); +} + +void NotificationPreferencesDatabase::ParseGroupDescription( + sptr &group, const OHOS::DistributedKv::Entry &entry) +{ + std::string typeStr = FindLastString(entry.key.ToString()); + std::string valueStr = entry.value.ToString(); + if (!typeStr.compare(kGroupDescription)) { + ANS_LOGD("SetGroupDescription is %{public}s", valueStr.c_str()); + group->SetDescription(valueStr); + } +} + +void NotificationPreferencesDatabase::ParseBundleName( + NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const +{ + 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))); +} + +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))); +} + +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)); +} + +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))); +} + +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))); +} + +void NotificationPreferencesDatabase::ParseSlotGroupId(sptr &slot, const std::string &value) const +{ + ANS_LOGD("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()); + 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)); + 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)); + 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)); + 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)); + 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)); + slot->SetLedLightColor(ledLightColor); +} + +void NotificationPreferencesDatabase::ParseSlotLockscreenVisibleness( + sptr &slot, const std::string &value) const +{ + + ANS_LOGD("slot visible is %{public}s", value.c_str()); + NotificationConstant::VisiblenessType visible = + static_cast(stoi(value, nullptr)); + slot->SetLockscreenVisibleness(visible); +} + +void NotificationPreferencesDatabase::ParseSlotSound(sptr &slot, const std::string &value) const +{ + std::string slotUri = value; + Uri uri(slotUri); + slot->SetSound(uri); +} + +void NotificationPreferencesDatabase::ParseSlotVibrationSytle( + sptr &slot, const std::string &value) const +{ + std::vector vibrationStyle; + StringToVector(value, vibrationStyle); + slot->SetVibrationStyle(vibrationStyle); +} + +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)); + slot->EnableBypassDnd(enable); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1202b287063c5ea1cb8dea9106de0465fdcd0fe4 --- /dev/null +++ b/services/ans/src/notification_preferences_info.cpp @@ -0,0 +1,252 @@ +/* + * 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_preferences_info.h" + +namespace OHOS { +namespace Notification { + +NotificationPreferencesInfo::BundleInfo::BundleInfo() +{} +NotificationPreferencesInfo::BundleInfo::~BundleInfo() +{} + +void NotificationPreferencesInfo::BundleInfo::SetBundleName(const std::string &name) +{ + bundleName_ = name; +} + +std::string NotificationPreferencesInfo::BundleInfo::GetBundleName() const +{ + return bundleName_; +} + +void NotificationPreferencesInfo::BundleInfo::SetImportance(const int &level) +{ + importance_ = level; +} + +int NotificationPreferencesInfo::BundleInfo::GetImportance() const +{ + return importance_; +} + +void NotificationPreferencesInfo::BundleInfo::SetIsShowBadge(const bool &isShowBadge) +{ + isShowBadge_ = isShowBadge; +} + +bool NotificationPreferencesInfo::BundleInfo::GetIsShowBadge() const +{ + return isShowBadge_; +} + +void NotificationPreferencesInfo::BundleInfo::SetBadgeTotalNum(const int &num) +{ + badgeTotalNum_ = num; +} + +int NotificationPreferencesInfo::BundleInfo::GetBadgeTotalNum() const +{ + return badgeTotalNum_; +} + +void NotificationPreferencesInfo::BundleInfo::SetIsPrivateAllowed(const bool &isPrivateAllowed) +{ + isPrivateAllowed_ = isPrivateAllowed; +} + +bool NotificationPreferencesInfo::BundleInfo::GetIsPrivateAllowed() const +{ + return isPrivateAllowed_; +} + +void NotificationPreferencesInfo::BundleInfo::SetEnableNotification(const bool &enable) +{ + isEnabledNotification_ = enable; +} + +bool NotificationPreferencesInfo::BundleInfo::GetEnableNotification() const +{ + return isEnabledNotification_; +} + +void NotificationPreferencesInfo::BundleInfo::SetSlot(const sptr &slot) +{ + slots_.insert_or_assign(slot->GetType(), slot); +} + +bool NotificationPreferencesInfo::BundleInfo::GetSlot( + const NotificationConstant::SlotType &type, sptr &slot) const +{ + auto iter = slots_.find(type); + if (iter != slots_.end()) { + slot = iter->second; + return true; + } + return false; +} + +bool NotificationPreferencesInfo::BundleInfo::GetAllSlots(std::vector> &slots) +{ + std::for_each(slots_.begin(), + slots_.end(), + [&slots](std::map>::reference iter) { + slots.emplace_back(iter.second); + }); + return true; +} + +bool NotificationPreferencesInfo::BundleInfo::GetAllSlotsInGroup( + const std::string groupId, std::vector> &slots) +{ + std::for_each(slots_.begin(), + slots_.end(), + [&slots, &groupId](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 +{ + auto iter = groups_.find(groupId); + if (iter != groups_.end()) { + group = iter->second; + return true; + } + return false; +} + +bool NotificationPreferencesInfo::BundleInfo::GetAllGroups(std::vector> &group) +{ + std::for_each( + groups_.begin(), groups_.end(), [&group](std::map>::reference &iter) { + group.emplace_back(iter.second); + }); + return true; +} + +uint32_t NotificationPreferencesInfo::BundleInfo::GetGroupSize() const +{ + return groups_.size(); +} + +bool NotificationPreferencesInfo::BundleInfo::IsExsitSlot(const NotificationConstant::SlotType &type) const +{ + auto iter = slots_.find(type); + if (iter != slots_.end()) { + return true; + } + return false; +} + +bool NotificationPreferencesInfo::BundleInfo::IsExsitSlotGroup(const std::string &groupId) const +{ + auto iter = groups_.find(groupId); + if (iter != groups_.end()) { + return true; + } + return false; +} + +bool NotificationPreferencesInfo::BundleInfo::RemoveSlot(const NotificationConstant::SlotType &type) +{ + auto iter = slots_.find(type); + if (iter != slots_.end()) { + slots_.erase(iter); + return true; + } + return false; +} + +bool NotificationPreferencesInfo::BundleInfo::RemoveSlotGroup(const std::string &groupId) +{ + auto iter = groups_.find(groupId); + if (iter != groups_.end()) { + groups_.erase(groupId); + return true; + } + return false; +} + +void NotificationPreferencesInfo::SetEnabledAllNotification(const bool &value) +{ + isEnabledAllNotification_ = value; +} + +bool NotificationPreferencesInfo::GetEnabledAllNotification() const +{ + return isEnabledAllNotification_; +} + +void NotificationPreferencesInfo::SetDisturbMode(const NotificationConstant::DisturbMode &mode) +{ + disturbMode_ = mode; +} + +NotificationConstant::DisturbMode NotificationPreferencesInfo::GetDisturbMode() const +{ + return disturbMode_; +} + +void NotificationPreferencesInfo::SetBundleInfo(const BundleInfo &info) +{ + infos_.insert_or_assign(info.GetBundleName(), info); +} + +bool NotificationPreferencesInfo::GetBundleInfo(const std::string &bundleName, BundleInfo &info) const +{ + auto iter = infos_.find(bundleName); + if (iter != infos_.end()) { + info = iter->second; + return true; + } + return false; +} + +bool NotificationPreferencesInfo::RemoveBundleInfo(const std::string &bundleName) +{ + auto iter = infos_.find(bundleName); + if (iter != infos_.end()) { + infos_.erase(iter); + return true; + } + return false; +} + +bool NotificationPreferencesInfo::IsExsitBundleInfo(const std::string &bundleName) const +{ + auto iter = infos_.find(bundleName); + if (iter != infos_.end()) { + return true; + } + return false; +} + +void NotificationPreferencesInfo::ClearBundleInfo() +{ + infos_.clear(); +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_slot_filter.cpp b/services/ans/src/notification_slot_filter.cpp index 931437b1d651f52a3a08ab36f3817a6a22340c8a..6231cccb2fd67cce5d16540e062ed27db20272be 100644 --- a/services/ans/src/notification_slot_filter.cpp +++ b/services/ans/src/notification_slot_filter.cpp @@ -15,6 +15,8 @@ #include "notification_slot_filter.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" #include "notification_preferences.h" namespace OHOS { @@ -26,26 +28,26 @@ void NotificationSlotFilter::OnStart() void NotificationSlotFilter::OnStop() {} -ErrCode NotificationSlotFilter::OnPublish(const sptr ¬ification) +ErrCode NotificationSlotFilter::OnPublish(const std::shared_ptr &record) { - sptr slot; - ErrCode result = NotificationPreferences::GetInstance().GetNotificationSlot( - notification->GetBundleName(), notification->request_->GetSlotType(), slot); - if (result == ERR_OK && slot != nullptr) { - if (slot->CanEnableLight()) { - notification->SetLedLightColor(slot->GetLedLightColor()); + if (record->slot != nullptr) { + if (record->slot->CanEnableLight()) { + record->notification->SetLedLightColor(record->slot->GetLedLightColor()); } - if (slot->CanVibrate()) { - notification->SetVibrationStyle(slot->GetVibrationStyle()); + if (record->slot->CanVibrate()) { + record->notification->SetVibrationStyle(record->slot->GetVibrationStyle()); } - notification->SetSound(slot->GetSound()); + record->notification->SetSound(record->slot->GetSound()); - notification->request_->SetVisibleness(slot->GetLockScreenVisibleness()); + record->request->SetVisibleness(record->slot->GetLockScreenVisibleness()); + } else { + ANS_LOGE("Non valid slot!"); + return ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; } - return result; + return ERR_OK; } } // namespace Notification diff --git a/services/ans/src/permission_filter.cpp b/services/ans/src/permission_filter.cpp index 794d7bd4a320615461c14f0f47bd811337ebd5d4..9f368e08df56faa8746f8464270ae2f610a20f07 100644 --- a/services/ans/src/permission_filter.cpp +++ b/services/ans/src/permission_filter.cpp @@ -15,6 +15,8 @@ #include "permission_filter.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" #include "notification_preferences.h" namespace OHOS { @@ -26,21 +28,22 @@ void PermissionFilter::OnStart() void PermissionFilter::OnStop() {} -ErrCode PermissionFilter::OnPublish(const sptr ¬ification) +ErrCode PermissionFilter::OnPublish(const std::shared_ptr &record) { bool enable = false; - ErrCode result = - NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(notification->GetBundleName(), enable); + ErrCode result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle( + record->notification->GetBundleName(), enable); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { result = ERR_OK; enable = true; } if (result == ERR_OK) { if (!enable) { - result = ERR_ANS_NOT_ALLOWED; + ANS_LOGE("Enable notifications for bundle is OFF"); + return ERR_ANS_NOT_ALLOWED; } - if (notification->GetBundleName() != notification->GetCreateBundle()) { + if (record->notification->GetBundleName() != record->notification->GetCreateBundle()) { // Publish as bundle } } diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2130524d959a9b4de40fd110b855898c1be613c7 --- /dev/null +++ b/services/ans/src/system_event_observer.cpp @@ -0,0 +1,55 @@ +/* + * 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 "system_event_observer.h" + +#include "common_event_manager.h" +#include "common_event_support.h" + +namespace OHOS { +namespace Notification { + +SystemEventObserver::SystemEventObserver(const ISystemEvent &callbacks) : callbacks_(callbacks) +{ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + EventFwk::CommonEventSubscribeInfo commonEventSubscribeInfo(matchingSkills); + + subscriber_ = std::make_shared( + commonEventSubscribeInfo, std::bind(&SystemEventObserver::OnReceiveEvent, this, std::placeholders::_1)); + + EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +SystemEventObserver::~SystemEventObserver() +{ + EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + auto want = data.GetWant(); + std::string action = want.GetAction(); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + if (callbacks_.onBundleRemoved != nullptr) { + auto element = want.GetElement(); + std::string bundle = element.GetBundleName(); + callbacks_.onBundleRemoved(bundle); + } + } +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 75a29c4d204a8480b2ebba8c178edcc5a2a4da52..a2288126eb9da3d2f46f46702ea6e3262fdf20d3 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -17,16 +17,6 @@ import("//build/test.gni") module_output_path = "ans_standard/unittest" -config("test_ans_config") { - include_dirs = [ - "${services_path}/ans/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "${kits_path}/native/include", - ] -} - config("json_config") { cflags_cc = [ "-fexceptions" ] } @@ -35,39 +25,48 @@ ohos_unittest("ans_unit_test") { module_out_path = module_output_path include_dirs = [ "include", - "${innerkits_path}/base/include", - "${innerkits_path}/core/include", - "${kits_path}/native/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", "//foundation/appexecfwk/standard/libs/libeventhandler/src", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//utils/native/base/include", "//utils/system/safwk/native/include", - "//base/notification/ans_standard/services/ans/include", - "//third_party/json/include", - "//base/notification/ans_standard/services/ans/test/unittest/mock/include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/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 = [ - "//base/notification/ans_standard/innerkits/core/src/ans_manager_stub.cpp", - "//base/notification/ans_standard/kits/native/src/notification.cpp", - "//base/notification/ans_standard/services/ans/src/advanced_notification_service.cpp", - "//base/notification/ans_standard/services/ans/src/advanced_notification_service_ability.cpp", - "//base/notification/ans_standard/services/ans/src/bundle_manager_helper.cpp", - "//base/notification/ans_standard/services/ans/src/disturb_filter.cpp", - "//base/notification/ans_standard/services/ans/src/notification_preferences.cpp", - "//base/notification/ans_standard/services/ans/src/notification_slot_filter.cpp", - "//base/notification/ans_standard/services/ans/src/notification_subscriber_manager.cpp", - "//base/notification/ans_standard/services/ans/src/permission_filter.cpp", + "${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", + "${services_path}/ans/src/notification_preferences_info.cpp", + "${services_path}/ans/src/notification_slot_filter.cpp", + "${services_path}/ans/src/notification_subscriber_manager.cpp", + "${services_path}/ans/src/permission_filter.cpp", + "${services_path}/ans/src/system_event_observer.cpp", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp", + "//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_event_handler.cpp", "mock/mock_ipc.cpp", + "mock/mock_single_kv_store.cpp", + "notification_preferences_database_test.cpp", "notification_preferences_test.cpp", "notification_slot_filter_test.cpp", "notification_subscriber_manager_test.cpp", @@ -76,15 +75,13 @@ ohos_unittest("ans_unit_test") { configs = [ "//utils/native/base:utils_config", - "${innerkits_path}:public_ans_innerkits_config", - ":test_ans_config", ":json_config", ] deps = [ - "${innerkits_path}:ans_innerkits", - "${kits_path}/native:ans_kits", - "${kits_path}/native/wantagent:wantagent_kits", + "${core_path}:ans_core", + "${frameworks_path}/ans/native:ans_innerkits", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", "//utils/native/base:utils", @@ -95,6 +92,7 @@ ohos_unittest("ans_unit_test") { "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", 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 b1518c83119fa856c83ef8bebb7a9e336fd4f95f..553e8fcbe1245ec42d8a0c8a3493acd1e4f185e9 100644 --- a/services/ans/test/unittest/advanced_notification_service_ability_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_ability_test.cpp @@ -13,10 +13,11 @@ * limitations under the License. */ -#include "advanced_notification_service_ability.h" #include #include +#include "advanced_notification_service_ability.h" + using namespace testing::ext; namespace OHOS { namespace Notification { diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index c3cbc03a862fa123910fa3df6814a41b39b65e02..b483171c2118e1e5aeac8423b56fc1d75fd821de 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -13,13 +13,17 @@ * limitations under the License. */ -#include "advanced_notification_service.h" -#include "notification_preferences.h" #include #include + #define private public +#include "advanced_notification_service.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 { @@ -45,11 +49,14 @@ void AdvancedNotificationServiceTest::TearDownTestCase() void AdvancedNotificationServiceTest::SetUp() { NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); + IPCSkeleton::SetCallingUid(1); + g_advancedNotificationService->CancelAll(); } void AdvancedNotificationServiceTest::TearDown() { NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); + sleep(1); } class TestAnsSubscriber : public NotificationSubscriber { @@ -76,11 +83,11 @@ public: {} }; -void TestAddSlots() +void TestAddSlots(NotificationConstant::SlotType type) { std::vector> slots; - sptr slotOther = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slotOther); + sptr slot = new NotificationSlot(type); + slots.push_back(slot); g_advancedNotificationService->AddSlots(slots); } @@ -91,194 +98,271 @@ void TestAddSlotGroups() groups.push_back(group); g_advancedNotificationService->AddSlotGroups(groups); } - /** - * @tc.number : AdvancedNotificationServiceTest_00100 - * @tc.name : AMS_ANS_Publish_0100 - * @tc.desc : Test the branch if notification not exists + * @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. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00100, Function | SmallTest | Level1) { sptr req = new NotificationRequest(); - req->SetSlotType(NotificationConstant::OTHER); - TestAddSlots(); - EXPECT_EQ(g_advancedNotificationService->Publish(std::string(), req), (int)ERR_OK); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_00200 - * @tc.name : AMS_ANS_Publish_0200 - * @tc.desc : Test the branch if notification is exists + * @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. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00200, Function | SmallTest | Level1) { - int32_t notificationId = 1; - sptr req = new NotificationRequest(notificationId); - req->SetSlotType(NotificationConstant::OTHER); - req->SetAlertOneTime(true); - TestAddSlots(); - g_advancedNotificationService->Publish(std::string(), req); - EXPECT_EQ(g_advancedNotificationService->Publish(std::string(), req), (int)ERR_OK); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_00300 - * @tc.name : AMS_ANS_Publish_0300 - * @tc.desc : Publish notification when no slot is set + * @tc.number : AMS_ANS_Publish_00300 + * @tc.name : ANSPublish00300 + * @tc.desc : When slotType is CUSTOM and not systemApp, the notification publish fails, + * and the notification publish interface returns ERR_ANS_NON_SYSTEM_APP. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00300, Function | SmallTest | Level1) { - int32_t notificationId = 1; - sptr req = new NotificationRequest(NULL, notificationId); - req->SetSlotType(NotificationConstant::OTHER); - EXPECT_EQ(g_advancedNotificationService->Publish(std::string(), req), (int)ERR_OK); + IPCSkeleton::SetCallingUid(750); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::CUSTOM); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_00400 - * @tc.name : AMS_ANS_Publish_0400 - * @tc.desc : Test Publish function when no slotType + * @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. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00400, Function | SmallTest | Level1) { - int32_t notificationId = 1; - sptr req = new NotificationRequest(notificationId); - req->SetSlotType(NotificationConstant::CUSTOM); - TestAddSlots(); - EXPECT_EQ((int)g_advancedNotificationService->Publish(std::string(), req), (int)ERR_OK); + IPCSkeleton::SetCallingUid(1250); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_00500 - * @tc.name : AMS_ANS_Publish_0500 - * @tc.desc : publish function when NotificationsEnabled is false + * @tc.number : AMS_ANS_Publish_00500 + * @tc.name : ANSPublish00500 + * @tc.desc : When the obtained bundleName does not have a corresponding slot in the database, + * create the corresponding slot and publish a notification. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00500, Function | SmallTest | Level1) { - int32_t notificationId = 1; - sptr req = new NotificationRequest(notificationId); - req->SetSlotType(NotificationConstant::OTHER); - TestAddSlots(); - g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", false); - EXPECT_EQ(g_advancedNotificationService->Publish(std::string(), req), (int)ERR_ANS_NOT_ALLOWED); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_00600 - * @tc.name : AMS_ANS_Cancel_0100 - * @tc.desc : public two notification to cancel one of them + * @tc.number : AMS_ANS_Publish_00600 + * @tc.name : ANSPublish00600 + * @tc.desc : When the obtained bundleName have a corresponding slot in the database, + * the test publish interface can successfully publish a notification of normal text type. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00600, Function | SmallTest | Level1) { - int32_t notificationId = 2; - std::string label = "testLabel"; - sptr req = new NotificationRequest(NULL, notificationId); - req->SetSlotType(NotificationConstant::OTHER); - req->SetLabel(label); - TestAddSlots(); - g_advancedNotificationService->Publish(label, req); - g_advancedNotificationService->Publish(label, req); - EXPECT_EQ(g_advancedNotificationService->Cancel(notificationId, label), (int)ERR_OK); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + TestAddSlots(NotificationConstant::SlotType::OTHER); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_00700 - * @tc.name : AMS_ANS_Cancel_0200 - * @tc.desc : Test Cancel function when notification no exists + * @tc.number : AMS_ANS_Publish_00700 + * @tc.name : ANSPublish00700 + * @tc.desc : When the obtained bundleName have a corresponding slot in the database, + * create the corresponding slot and publish a notification. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00700, Function | SmallTest | Level1) { - int32_t notificationId = 0; - std::string label = "testLabel"; - EXPECT_EQ((int)g_advancedNotificationService->Cancel(notificationId, label), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + TestAddSlots(NotificationConstant::SlotType::OTHER); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_00800 - * @tc.name : AMS_ANS_CancelAll_0100 - * @tc.desc : Test CancelAll function + * @tc.number : AMS_ANS_Publish_00800 + * @tc.name : ANSPublish00800 + * @tc.desc : Create a slot of type SOCIAL_COMMUNICATION and successfully publish a notification */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00800, Function | SmallTest | Level1) { - EXPECT_EQ(g_advancedNotificationService->CancelAll(), (int)ERR_OK); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_00900 - * @tc.name : AMS_ANS_Cancel_0100 - * @tc.desc : Test Cancel function when unremovable is true + * @tc.number : AMS_ANS_Publish_00900 + * @tc.name : ANSPublish00900 + * @tc.desc : Create a slot of type SERVICE_REMINDER and successfully publish a notification */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00900, Function | SmallTest | Level1) { - int32_t notificationId = 2; - std::string label = "testLabel"; - sptr req = new NotificationRequest(notificationId); - req->SetSlotType(NotificationConstant::OTHER); - req->SetLabel(label); - req->SetUnremovable(true); - TestAddSlots(); - g_advancedNotificationService->Publish(label, req); - g_advancedNotificationService->Publish(label, req); - EXPECT_EQ(g_advancedNotificationService->Cancel(notificationId, label), (int)ERR_ANS_NOTIFICATION_IS_UNREMOVABLE); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::SERVICE_REMINDER); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_01000 - * @tc.name : AMS_ANS_AddSlots_0100 - * @tc.desc : Test AddSlots function + * @tc.number : AMS_ANS_Publish_01000 + * @tc.name : ANSPublish01000 + * @tc.desc : Create a slot of type CONTENT_INFORMATION and successfully publish a notification */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01000, 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(g_advancedNotificationService->AddSlots(slots), ERR_OK); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_01100 - * @tc.name : AMS_ANS_RemoveSlotByType_0100 - * @tc.desc : Test RemoveSlotByType function + * @tc.number : AMS_ANS_Publish_01100 + * @tc.name : ANSPublish01100 + * @tc.desc : Create a slot of type OTHER and successfully publish a notification */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01100, Function | SmallTest | Level1) { - TestAddSlots(); - EXPECT_EQ(g_advancedNotificationService->RemoveSlotByType(NotificationConstant::OTHER), ERR_OK); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_01200 - * @tc.name : AMS_ANS_RemoveSlotByType_0200 - * @tc.desc : Test RemoveSlotByType function when no type + * @tc.number : AMS_ANS_Publish_01200 + * @tc.name : ANSPublish01200 + * @tc.desc : Create a slot of type CUSTOM and successfully publish a notification */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01200, Function | SmallTest | Level1) { - TestAddSlots(); - EXPECT_EQ((int)g_advancedNotificationService->RemoveSlotByType(NotificationConstant::CUSTOM), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ID_INVALID); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::CUSTOM); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } /** - * @tc.number : AdvancedNotificationServiceTest_01300 - * @tc.name : AMS_ANS_AddSlotGroups_0100 - * @tc.desc : Test AddSlotGroups function + * @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 + * ERR_ANS_NOT_ALLOWED */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01300, 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(g_advancedNotificationService->AddSlotGroups(groups), ERR_OK); + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", false); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_ANS_NOT_ALLOWED); } /** - * @tc.number : AdvancedNotificationServiceTest_01400 - * @tc.name : AMS_ANS_RemoveSlotGroups_0100 - * @tc.desc : Test RemoveSlotGroups function + * @tc.number : AMS_ANS_Publish_01400 + * @tc.name : ANSPublish01400 + * @tc.desc : When IsAlertOneTime, reset ColorEnabled, Sound, VibrationStyle, and publish the notification */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01400, Function | SmallTest | Level1) { @@ -288,24 +372,6 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01400, EXPECT_EQ(g_advancedNotificationService->RemoveSlotGroups(groupIds), (int)ERR_OK); } -/** - * @tc.number : AdvancedNotificationServiceTest_01500 - * @tc.name : AMS_ANS_GetSlot_0100 - * @tc.desc : Test GetSlot function for data - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01500, Function | SmallTest | Level1) -{ - std::vector> slots; - sptr slot = new NotificationSlot(NotificationConstant::OTHER); - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - g_advancedNotificationService->AddSlots(slots); - EXPECT_EQ((int)g_advancedNotificationService->GetSlot("id0", slot), ERR_OK); - EXPECT_EQ(slot->GetName(), slot0->GetName()); - EXPECT_EQ(slot->GetId(), slot0->GetId()); - EXPECT_EQ(slot->GetLevel(), slot0->GetLevel()); -} - /** * @tc.number : AdvancedNotificationServiceTest_01600 * @tc.name : AMS_ANS_GetSlot_0200 @@ -351,7 +417,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01700, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01800, Function | SmallTest | Level1) { - TestAddSlots(); + TestAddSlots(NotificationConstant::SlotType::OTHER); EXPECT_EQ((int)g_advancedNotificationService->SetNotificationBadgeNum(2), (int)ERR_OK); } @@ -362,7 +428,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01800, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01900, Function | SmallTest | Level1) { - TestAddSlots(); + TestAddSlots(NotificationConstant::SlotType::OTHER); int importance; EXPECT_EQ((int)g_advancedNotificationService->GetBundleImportance(importance), (int)ERR_OK); } @@ -374,7 +440,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01900, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02000, Function | SmallTest | Level1) { - TestAddSlots(); + TestAddSlots(NotificationConstant::SlotType::OTHER); EXPECT_EQ((int)g_advancedNotificationService->SetPrivateNotificationsAllowed(true), (int)ERR_OK); } @@ -385,27 +451,13 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02000, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02100, Function | SmallTest | Level1) { - TestAddSlots(); + 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); 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) -{ - std::string bundle = "bundleName"; - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - EXPECT_EQ((int)g_advancedNotificationService->UpdateSlots(bundle, slots), (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); -} - /** * @tc.number : AdvancedNotificationServiceTest_02300 * @tc.name : AMS_ANS_UpdateSlots_0200 @@ -415,27 +467,12 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02300, { std::string bundle = "bundleName"; std::vector> slots; - TestAddSlots(); + 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); } -/** - * @tc.number : AdvancedNotificationServiceTest_02400 - * @tc.name : AMS_ANS_UpdateSlotGroups_0100 - * @tc.desc : Test UpdateSlotGroups function when no group - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02400, Function | SmallTest | Level1) -{ - std::string bundle = "bundleName"; - std::vector> groups; - sptr group2 = new NotificationSlotGroup("id2", "name2"); - groups.push_back(group2); - EXPECT_EQ( - (int)g_advancedNotificationService->UpdateSlotGroups(bundle, groups), (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); -} - /** * @tc.number : AdvancedNotificationServiceTest_02500 * @tc.name : AMS_ANS_UpdateSlotGroups_0200 @@ -483,8 +520,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02800, { std::string bundle = "bundleName"; bool allow; - EXPECT_EQ((int)g_advancedNotificationService->GetShowBadgeEnabledForBundle(bundle, allow), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + EXPECT_EQ((int)g_advancedNotificationService->GetShowBadgeEnabledForBundle(bundle, allow), (int)ERR_OK); } /** @@ -562,7 +598,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03400, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03500, Function | SmallTest | Level1) { - TestAddSlots(); + TestAddSlots(NotificationConstant::SlotType::OTHER); NotificationConstant::DisturbMode mode; EXPECT_EQ((int)g_advancedNotificationService->GetDisturbMode(mode), (int)ERR_OK); } @@ -617,7 +653,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03900, */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04000, Function | SmallTest | Level1) { - TestAddSlots(); + TestAddSlots(NotificationConstant::SlotType::OTHER); std::string bundle = "bundleName"; std::vector> slots; EXPECT_EQ(g_advancedNotificationService->GetSlotsByBundle(bundle, slots), ERR_OK); @@ -631,242 +667,19 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04000, HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04100, Function | SmallTest | Level1) { sptr req = new NotificationRequest(); - req->SetSlotType(NotificationConstant::OTHER); - TestAddSlots(); - g_advancedNotificationService->Publish(std::string(), req); - EXPECT_EQ(g_advancedNotificationService->Publish(std::string(), req), (int)ERR_OK); - sptr notification = new Notification(req); - std::vector> notifications; - std::string key1 = notification->GetKey(); - std::string key2 = "key2"; - std::vector keys; - keys.push_back(key1); - keys.push_back(key2); - EXPECT_EQ(g_advancedNotificationService->GetSpecialActiveNotifications(keys, notifications), ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04200 - * @tc.name : AMS_ANS_Subscribe_0100 - * @tc.desc : Test Subscribe function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04200, Function | SmallTest | Level1) -{ - auto subscriber = new TestAnsSubscriber(); - sptr info = new NotificationSubscribeInfo(); - EXPECT_EQ((int)g_advancedNotificationService->Subscribe(subscriber->GetImpl(), info), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04300 - * @tc.name : AMS_ANS_Unsubscribe_0100 - * @tc.desc : Test Unsubscribe function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04300, Function | SmallTest | Level1) -{ - auto subscriber = new TestAnsSubscriber(); - sptr info = new NotificationSubscribeInfo(); - EXPECT_EQ((int)g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), info), (int)ERR_OK); - ; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04400 - * @tc.name : AMS_ANS_SetNotificationsEnabledForBundle_0200 - * @tc.desc : Test SetNotificationsEnabledForBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04400, Function | SmallTest | Level1) -{ - std::string bundle = "bundleName"; - TestAddSlots(); - EXPECT_EQ((int)g_advancedNotificationService->SetNotificationsEnabledForBundle(bundle, true), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04500 - * @tc.name : AMS_ANS_GetShowBadgeEnabledForBundle_0200 - * @tc.desc : Test GetShowBadgeEnabledForBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04500, Function | SmallTest | Level1) -{ - std::string bundle = "bundleName"; - TestAddSlots(); - EXPECT_EQ((int)g_advancedNotificationService->SetShowBadgeEnabledForBundle(bundle, true), (int)ERR_OK); - bool allow; - EXPECT_EQ((int)g_advancedNotificationService->GetShowBadgeEnabledForBundle(bundle, allow), (int)ERR_OK); - EXPECT_TRUE(allow); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04600 - * @tc.name : AMS_ANS_GetSlotByType_0100 - * @tc.desc : Test GetSlotByType function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04600, Function | SmallTest | Level1) -{ - std::string bundle = "bundleName"; - TestAddSlots(); - sptr slot; - EXPECT_EQ((int)g_advancedNotificationService->GetSlotByType(NotificationConstant::OTHER, slot), (int)ERR_OK); - EXPECT_EQ(slot->GetId(), "OTHER"); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04700 - * @tc.name : AMS_ANS_GetSlotByType_0200 - * @tc.desc : Test the CreateSlot branch of the GetSlotByType function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04700, Function | SmallTest | Level1) -{ - std::string bundle = "bundleName"; - sptr slot; - g_advancedNotificationService->GetSlotByType(NotificationConstant::SOCIAL_COMMUNICATION, slot); - g_advancedNotificationService->GetSlotByType(NotificationConstant::SERVICE_REMINDER, slot); - g_advancedNotificationService->GetSlotByType(NotificationConstant::CONTENT_INFORMATION, slot); - g_advancedNotificationService->GetSlotByType(NotificationConstant::OTHER, slot); - EXPECT_EQ((int)g_advancedNotificationService->GetSlotByType(NotificationConstant::CUSTOM, slot), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04800 - * @tc.name : AMS_ANS_GetSlotGroups_0100 - * @tc.desc : Test GetSlotGroups function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04800, Function | SmallTest | Level1) -{ - std::vector> groups; - sptr group2 = new NotificationSlotGroup("id2", "name2"); - group2->SetDescription("Description"); - groups.push_back(group2); - g_advancedNotificationService->AddSlotGroups(groups); - std::vector> group; - EXPECT_EQ(g_advancedNotificationService->GetSlotGroups(group), ERR_OK); - EXPECT_EQ(groups.size(), group.size()); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04900 - * @tc.name : AMS_ANS_GetAllActiveNotifications_0100 - * @tc.desc : Test GetAllActiveNotifications function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04900, Function | SmallTest | Level1) -{ - std::vector> notifications; - EXPECT_EQ(g_advancedNotificationService->GetAllActiveNotifications(notifications), ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05000 - * @tc.name : AMS_ANS_SetNotificationsEnabledForAllBundles_0100 - * @tc.desc : Test SetNotificationsEnabledForAllBundles function for else - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05000, Function | SmallTest | Level1) -{ - std::vector> notifications; - EXPECT_EQ((int)g_advancedNotificationService->SetNotificationsEnabledForAllBundles("test", true), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05100 - * @tc.name : AMS_ANS_SetNotificationsEnabledForAllBundles_0200 - * @tc.desc : Test SetNotificationsEnabledForAllBundles function for if - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05100, Function | SmallTest | Level1) -{ - TestAddSlots(); - std::vector> notifications; - EXPECT_EQ( - (int)g_advancedNotificationService->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05200 - * @tc.name : AMS_ANS_SetNotificationsEnabledForSpecialBundle_0100 - * @tc.desc : Test SetNotificationsEnabledForSpecialBundle function for if - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05200, Function | SmallTest | Level1) -{ - TestAddSlots(); - std::vector> notifications; - EXPECT_EQ( - (int)g_advancedNotificationService->SetNotificationsEnabledForSpecialBundle(std::string(), "bundleName", true), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05300 - * @tc.name : AMS_ANS_SetNotificationsEnabledForSpecialBundle_0200 - * @tc.desc : Test SetNotificationsEnabledForSpecialBundle function for else - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05300, Function | SmallTest | Level1) -{ - std::vector> notifications; - EXPECT_EQ((int)g_advancedNotificationService->SetNotificationsEnabledForSpecialBundle("test", "bundleName", true), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05400 - * @tc.name : AMS_ANS_IsAllowedNotify_0100 - * @tc.desc : Test IsAllowedNotify function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05400, Function | SmallTest | Level1) -{ - bool allowed = true; - EXPECT_EQ((int)g_advancedNotificationService->IsAllowedNotify(allowed), (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05500 - * @tc.name : AMS_ANS_IsAllowedNotify_0200 - * @tc.desc : Test IsAllowedNotify function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05500, Function | SmallTest | Level1) -{ - TestAddSlots(); - bool allowed = true; - EXPECT_EQ((int)g_advancedNotificationService->IsAllowedNotify(allowed), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05600 - * @tc.name : AMS_ANS_IsSpecialBundleAllowedNotify_0100 - * @tc.desc : Test IsSpecialBundleAllowedNotify function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05600, Function | SmallTest | Level1) -{ - TestAddSlots(); - std::vector> notifications; - bool allowed = true; - std::string bundle = "bundleName"; - EXPECT_EQ((int)g_advancedNotificationService->IsSpecialBundleAllowedNotify(bundle, allowed), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05700 - * @tc.name : AMS_ANS_IsSpecialBundleAllowedNotify_0200 - * @tc.desc : Test IsSpecialBundleAllowedNotify function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05700, Function | SmallTest | Level1) -{ - std::vector> notifications; - bool allowed = true; - std::string bundle = "bundleName"; - EXPECT_EQ((int)g_advancedNotificationService->IsSpecialBundleAllowedNotify(bundle, allowed), - (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); + 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(); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", true); + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), (int)ERR_OK); } -/** - * @tc.number : AdvancedNotificationServiceTest_05800 - * @tc.name : AMS_ANS_GetSlotsByBundle_0200 - * @tc.desc : Test GetSlotsByBundle function when no bundle - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05800, Function | SmallTest | Level1) -{ - std::string bundle = "bundleName"; - std::vector> slots; - EXPECT_EQ( - (int)g_advancedNotificationService->GetSlotsByBundle(bundle, slots), (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); -} } // namespace Notification } // namespace OHOS \ 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 aa20d3bec4aeefe80d14af136fdf8d12250a7698..b64140c3f1e163b02e9097b33ba6babaee7d6a8f 100644 --- a/services/ans/test/unittest/bundle_manager_helper_test.cpp +++ b/services/ans/test/unittest/bundle_manager_helper_test.cpp @@ -13,13 +13,14 @@ * limitations under the License. */ +#include +#include + #include "bundle_manager_helper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" #include "system_ability_definition.h" -#include -#include using namespace testing::ext; namespace OHOS { diff --git a/services/ans/test/unittest/disturb_filter_test.cpp b/services/ans/test/unittest/disturb_filter_test.cpp index 5621b5268649ac59ae465daa4d22235bdc4ef531..4c00d8a28c2e7f4e4a4033b80aa75fec23a30628 100644 --- a/services/ans/test/unittest/disturb_filter_test.cpp +++ b/services/ans/test/unittest/disturb_filter_test.cpp @@ -13,10 +13,11 @@ * limitations under the License. */ -#include "disturb_filter.h" #include #include +#include "disturb_filter.h" + using namespace testing::ext; namespace OHOS { namespace Notification { @@ -71,9 +72,11 @@ HWTEST_F(DisturbFilterTest, DisturbFilterTest_00200, Function | SmallTest | Leve HWTEST_F(DisturbFilterTest, DisturbFilterTest_00300, Function | SmallTest | Level1) { DisturbFilter disturbFilter; - sptr request = new NotificationRequest(); - auto objptr = new Notification(request); - disturbFilter.OnPublish(objptr); + 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); + disturbFilter.OnPublish(record); } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/mock/blob.cpp b/services/ans/test/unittest/mock/blob.cpp new file mode 100755 index 0000000000000000000000000000000000000000..93d2c34700f2b1d15a38ad135a6299d3450168bb --- /dev/null +++ b/services/ans/test/unittest/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/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp b/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..33a1c730b25abe5dffc90ad7d709a51105799ba7 --- /dev/null +++ b/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp @@ -0,0 +1,69 @@ +/* + * 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) +{ + 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_ipc_skeleton.h b/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h new file mode 100755 index 0000000000000000000000000000000000000000..39c56acabef2ab760551f9edb59aea969dc902d3 --- /dev/null +++ b/services/ans/test/unittest/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 pid_t GetCallingPid(); + + static pid_t 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(pid_t uid); +}; +} // namespace OHOS +#endif // OHOS_IPC_IPC_SKELETON_H 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 new file mode 100644 index 0000000000000000000000000000000000000000..8a777ea02ea632ddcbd69ebd89a4a6240a9b2a2c --- /dev/null +++ b/services/ans/test/unittest/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/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp index adde06e332a4bc139d62da8bfc8a4677b7ee277f..b7aa3f47499c5fc5c5cf856aa0156de7bd85bf0a 100644 --- a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -33,12 +33,12 @@ void BundleManagerHelper::OnRemoteDied(const wptr &object) std::string BundleManagerHelper::GetBundleNameByUid(uid_t uid) { - return "bundleName"; + return 1000 < uid && uid < 1500 ? "" : "bundleName"; } bool BundleManagerHelper::IsSystemApp(uid_t uid) { - return true; + return 500 < uid && uid < 1000 ? false : true; } void BundleManagerHelper::Connect() diff --git a/services/ans/test/unittest/mock/mock_ipc.cpp b/services/ans/test/unittest/mock/mock_ipc.cpp index 117032cd1aa4603ca2068e107dd497d29a84b940..3c2bc08da34937d5f9bb2ec3c40eff95a87a7e13 100644 --- a/services/ans/test/unittest/mock/mock_ipc.cpp +++ b/services/ans/test/unittest/mock/mock_ipc.cpp @@ -13,21 +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 uid_ = 1; + pid_t IPCSkeleton::GetCallingUid() { - pid_t uid = 1; - return uid; + return uid_; } pid_t IPCSkeleton::GetCallingPid() { - pid_t uid = 1; - return uid; + uid_ = 1; + return uid_; +} + +void IPCSkeleton::SetCallingUid(pid_t 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 new file mode 100644 index 0000000000000000000000000000000000000000..4b580d297471fb6658f861e020621e89b8cb9382 --- /dev/null +++ b/services/ans/test/unittest/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/services/ans/test/unittest/notification_preferences_database_test.cpp b/services/ans/test/unittest/notification_preferences_database_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2ad8c94a5f03aad03556e327bb8a73b18966f30 --- /dev/null +++ b/services/ans/test/unittest/notification_preferences_database_test.cpp @@ -0,0 +1,508 @@ +/* + * 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 private public +#include + +#include "notification_preferences.h" +#include "notification_preferences_database.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +class NotificationPreferencesDatabaseTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void NotificationPreferencesDatabaseTest::SetUpTestCase() +{} + +void NotificationPreferencesDatabaseTest::TearDownTestCase() +{} + +void NotificationPreferencesDatabaseTest::SetUp() +{} + +void NotificationPreferencesDatabaseTest::TearDown() +{} + +std::unique_ptr preferncesDB_ = std::make_unique(); + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutSlotsToDisturbeDB_00100 + */ +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)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutSlotsToDisturbeDB_00200 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutSlotsToDisturbeDB_00200, Function | SmallTest | Level1) +{ + 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(false, preferncesDB_->PutSlotsToDisturbeDB(std::string(), slots)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutSlotsToDisturbeDB_00300 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutSlotsToDisturbeDB_00300, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + std::vector> slots; + EXPECT_EQ(false, preferncesDB_->PutSlotsToDisturbeDB(std::string(), slots)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutGroupsToDisturbeDB_00100 + */ +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)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutGroupsToDisturbeDB_00200 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutGroupsToDisturbeDB_00200, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + + std::vector> groups; + + EXPECT_EQ(false, preferncesDB_->PutGroupsToDisturbeDB(bundleName, groups)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutShowBadge_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutShowBadge_00100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + + EXPECT_EQ(true, preferncesDB_->PutShowBadge(bundleName, true)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutShowBadge_00200 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutShowBadge_00200, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + + EXPECT_EQ(true, preferncesDB_->PutShowBadge(bundleName, false)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutShowBadge_00300 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutShowBadge_00300, Function | SmallTest | Level1) +{ + EXPECT_EQ(false, preferncesDB_->PutShowBadge(std::string(), false)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutImportance_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutImportance_00100, 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)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutTotalBadgeNums_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutTotalBadgeNums_00100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + + EXPECT_EQ(true, preferncesDB_->PutTotalBadgeNums(bundleName, 0)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutTotalBadgeNums_00200 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutTotalBadgeNums_00200, Function | SmallTest | Level1) +{ + EXPECT_EQ(false, preferncesDB_->PutTotalBadgeNums(std::string(), 0)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutPrivateNotificationsAllowed_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutPrivateNotificationsAllowed_00100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + + EXPECT_EQ(true, preferncesDB_->PutPrivateNotificationsAllowed(bundleName, true)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutPrivateNotificationsAllowed_00200 + */ +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)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutNotificationsEnabledForBundle_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabledForBundle_00100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + + EXPECT_EQ(true, preferncesDB_->PutNotificationsEnabledForBundle(bundleName, true)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutNotificationsEnabledForBundle_00200 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabledForBundle_00200, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + + EXPECT_EQ(true, preferncesDB_->PutNotificationsEnabledForBundle(bundleName, false)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutNotificationsEnabledForBundle_00300 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabledForBundle_00300, Function | SmallTest | Level1) +{ + EXPECT_EQ(false, preferncesDB_->PutNotificationsEnabledForBundle(std::string(), false)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutNotificationsEnabled_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabled_00100, Function | SmallTest | Level1) +{ + + EXPECT_EQ(true, preferncesDB_->PutNotificationsEnabled(true)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutNotificationsEnabled_00200 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabled_00200, Function | SmallTest | Level1) +{ + EXPECT_EQ(true, preferncesDB_->PutNotificationsEnabled(false)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : PutDisturbMode_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutDisturbMode_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)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : CreateExsitBundle_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, CreateExsitBundle_00100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + EXPECT_EQ(true, preferncesDB_->CheckBundle(bundleName)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : RemoveAllBundleFromDisturbeDB_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, RemoveAllBundleFromDisturbeDB_00100, Function | SmallTest | Level1) +{ + EXPECT_EQ(true, preferncesDB_->RemoveAllBundleFromDisturbeDB()); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : RemoveBundleFromDisturbeDB_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, RemoveBundleFromDisturbeDB_00100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + EXPECT_EQ(true, preferncesDB_->RemoveBundleFromDisturbeDB(bundleName)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : RemoveSlotFromDisturbeDB_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, RemoveSlotFromDisturbeDB_00100, 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)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : RemoveGroupsFromDisturbeDB_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, RemoveGroupsFromDisturbeDB_00100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + std::vector groupIds; + EXPECT_EQ(true, preferncesDB_->RemoveGroupsFromDisturbeDB(bundleName, groupIds)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : RemoveGroupsFromDisturbeDB_00200 + */ +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)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : GetRemoveGroupKeys_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, GetRemoveGroupKeys_00100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + std::string groupId = ""; + std::vector keys; + EXPECT_EQ(true, preferncesDB_->GetRemoveGroupKeysFromDisturbeDB(bundleName, groupId, keys)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : StoreDeathRecipient_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, StoreDeathRecipient_00100, Function | SmallTest | Level1) +{ + NotificationPreferencesInfo preferencesInfo_{}; + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + EXPECT_EQ(true, preferncesDB_->StoreDeathRecipient(preferencesInfo)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : GetKvStore_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, GetKvStore_00100, Function | SmallTest | Level1) +{ + EXPECT_EQ(OHOS::DistributedKv::Status::SUCCESS, preferncesDB_->GetKvStore()); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : CheckKvStore_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, CheckKvStore_00100, Function | SmallTest | Level1) +{ + EXPECT_EQ(true, preferncesDB_->CheckKvStore()); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : ResetStore_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, ResetStore_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)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : SetSlotEntry_00200 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, SetSlotEntry_00200, 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)); +} + +/** + * @tc.number : + * @tc.name : + * @tc.desc : GetGroupEntry_00100 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, GetGroupEntry_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)); +} + +/** + * @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 + */ +HWTEST_F(NotificationPreferencesDatabaseTest, ParseGroupFromDisturbeDB_00100, Function | SmallTest | Level1) +{ + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName("BundleName"); + // preferncesDB_->ParseGroupFromDisturbeDB(bundleInfo, std::string()); // TODO ‘½—¹˜¢ŽQ” + EXPECT_EQ("BundleName", bundleInfo.GetBundleName()); +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/notification_preferences_test.cpp b/services/ans/test/unittest/notification_preferences_test.cpp index efa4894c6d5d1c2416a385e24ba754f042516169..5c3e5b45da69d743ddc94a58d92e6028d71e2479 100644 --- a/services/ans/test/unittest/notification_preferences_test.cpp +++ b/services/ans/test/unittest/notification_preferences_test.cpp @@ -13,9 +13,11 @@ * limitations under the License. */ -#include "notification_preferences.h" #include +#include "notification_preferences.h" +#include "ans_inner_errors.h" + using namespace testing::ext; namespace OHOS { namespace Notification { @@ -35,9 +37,7 @@ void NotificationPreferencesTest::TearDownTestCase() {} void NotificationPreferencesTest::SetUp() -{ - NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); -} +{} void NotificationPreferencesTest::TearDown() { @@ -63,256 +63,102 @@ void TestAddNotificationSlotGroup() } /** - * @tc.number : NotificationPreferencesTest_00100 - * @tc.name : AMS_ANS_AddNotificationSlots_0100 - * @tc.desc : Test AddNotificationSlots function + * @tc.number : + * @tc.name : + * @tc.desc : AddNotificationSlots_00100 */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00100, Function | SmallTest | Level1) { std::string bundleName = "bundleName"; - sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); - std::vector> spSlots; - spSlots.push_back(spSlot); - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots), (int)ERR_OK); -} - -/** - * @tc.number : NotificationPreferencesTest_00200 - * @tc.name : AMS_ANS_AddNotificationSlots_0200 - * @tc.desc : Test AddNotificationSlots function when add two identical data - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00200, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName1"; - sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); - spSlot->SetSlotGroup("test"); - std::vector> spSlots; - spSlots.push_back(spSlot); - NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots), (int)ERR_OK); + 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); } /** - * @tc.number : NotificationPreferencesTest_00300 - * @tc.name : AMS_ANS_AddNotificationSlots_0300 - * @tc.desc : Test AddNotificationSlots function when the parameter is wrong + * @tc.number : + * @tc.name : + * @tc.desc : AddNotificationSlots_00200 */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00300, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00200, Function | SmallTest | Level1) { - std::vector> spSlots; - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(std::string(), spSlots), - (int)ERR_ANS_INVALID_PARAM); + 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); } /** - * @tc.number : NotificationPreferencesTest_00400 - * @tc.name : AMS_ANS_AddNotificationSlots_0100 - * @tc.desc : Test AddNotificationSlotGroups function + * @tc.number : + * @tc.name : + * @tc.desc : AddNotificationSlots_00300 */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00400, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00300, Function | SmallTest | Level1) { std::string bundleName = "bundleName"; - sptr spSlotGroup = new NotificationSlotGroup("id", "name"); - std::vector> spSlotGroups; - spSlotGroups.push_back(spSlotGroup); - EXPECT_EQ( - (int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, spSlotGroups), (int)ERR_OK); + std::vector> slots; + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots), (int)ERR_ANS_INVALID_PARAM); } /** - * @tc.number : NotificationPreferencesTest_00500 - * @tc.name : AMS_ANS_AddNotificationSlotGroups_0200 - * @tc.desc : Test AddNotificationSlotGroups function when the parameter is wrong + * @tc.number : + * @tc.name : + * @tc.desc : AddNotificationSlots_00400 */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00500, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00400, Function | SmallTest | Level1) { std::string bundleName = "bundleName"; - sptr spSlotGroup = new NotificationSlotGroup("", "name"); - std::vector> spSlotGroups; - spSlotGroups.push_back(spSlotGroup); - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, spSlotGroups), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID); -} - -/** - * @tc.number : NotificationPreferencesTest_00600 - * @tc.name : AMS_ANS_AddNotificationSlotGroups_0300 - * @tc.desc : Test AddNotificationSlotGroups function when bundleName is not set - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00600, Function | SmallTest | Level1) -{ - std::vector> spSlotGroups; - EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(std::string(), spSlotGroups), - (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.number : NotificationPreferencesTest_00700 - * @tc.name : AMS_ANS_RemoveNotificationSlot_0100 - * @tc.desc : Test RemoveNotificationSlot function - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00700, 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 slotIds; - slotIds.push_back(spSlot->GetId()); - EXPECT_EQ( - (int)NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleName, NotificationConstant::OTHER), - (int)ERR_OK); + 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); } /** - * @tc.number : NotificationPreferencesTest_00800 - * @tc.name : AMS_ANS_RemoveNotificationSlot_0200 - * @tc.desc : Test RemoveNotificationSlot function when bundleName is not set + * @tc.number : + * @tc.name : + * @tc.desc : AddNotificationSlots_00500 */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00800, Function | SmallTest | Level1) -{ - std::string bundleName = ""; - std::vector slotIds; - EXPECT_EQ( - (int)NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleName, NotificationConstant::OTHER), - (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.number : NotificationPreferencesTest_00900 - * @tc.name : AMS_ANS_RemoveNotificationSlot_0300 - * @tc.desc : Test RemoveNotificationSlot function when slot not exist - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00900, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00500, Function | SmallTest | Level1) { std::string bundleName = "bundleName"; - std::string slotId = "id"; - std::vector slotIds; - slotIds.push_back(slotId); - TestAddNotificationSlot(); - NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleName, NotificationConstant::OTHER); - EXPECT_EQ( - (int)NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleName, NotificationConstant::OTHER), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST); -} -/** - * @tc.number : NotificationPreferencesTest_01000 - * @tc.name : AMS_ANS_RemoveNotificationSlot_0400 - * @tc.desc : Test RemoveNotificationSlot function when file is null - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01000, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName"; - sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); - std::vector> spSlots; - spSlots.push_back(spSlot); - std::vector slotIds; - slotIds.push_back(spSlot->GetId()); - EXPECT_EQ( - (int)NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleName, NotificationConstant::OTHER), - (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); -} + 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); -/** - * @tc.number : NotificationPreferencesTest_01100 - * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0100 - * @tc.desc : Test RemoveNotificationSlotGroups function when bundle not exist - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01100, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName1"; - sptr spSlotGroup = new NotificationSlotGroup("id1", "name"); - std::vector> spSlotGroups; - spSlotGroups.push_back(spSlotGroup); - NotificationPreferences::GetInstance().AddNotificationSlotGroups("bundleName", spSlotGroups); - std::string groupId = "id1"; - std::vector groupIds; - groupIds.push_back(groupId); - EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + 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); } /** - * @tc.number : NotificationPreferencesTest_01200 - * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0200 - * @tc.desc : Test RemoveNotificationSlotGroups function the parameter is wrong + * @tc.number : + * @tc.name : + * @tc.desc : AddNotificationSlots_00600 */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01200, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00600, Function | SmallTest | Level1) { std::string bundleName = "bundleName"; - std::vector groupIds; - EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), - (int)ERR_ANS_INVALID_PARAM); -} -/** - * @tc.number : NotificationPreferencesTest_01300 - * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0300 - * @tc.desc : Test RemoveNotificationSlotGroups function - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01300, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName"; - std::string groupId = "id"; - std::vector groupIds; - groupIds.push_back(groupId); - TestAddNotificationSlotGroup(); - EXPECT_EQ( - (int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), (int)ERR_OK); -} + sptr slot1 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr slot2 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); -/** - * @tc.number : NotificationPreferencesTest_01400 - * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0400 - * @tc.desc : Test RemoveNotificationSlotGroups function when slotid invalid - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01400, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName"; - std::string groupId = ""; - std::vector groupIds; - groupIds.push_back(groupId); - TestAddNotificationSlotGroup(); - EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ID_INVALID); -} + std::vector> slots; + slots.push_back(slot1); + slots.push_back(slot2); -/** - * @tc.number : NotificationPreferencesTest_01500 - * @tc.name : AMS_ANS_UpdateNotificationSlotGroups_0100 - * @tc.desc : Test UpdateNotificationSlotGroups function - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01500, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName"; - sptr spSlotGroup = new NotificationSlotGroup("id1", "name"); - std::vector> spSlotGroups; - spSlotGroups.push_back(spSlotGroup); - NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, spSlotGroups); - EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleName, spSlotGroups), - (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots), (int)ERR_OK); } -/** - * @tc.number : NotificationPreferencesTest_01600 - * @tc.name : AMS_ANS_GetNotificationSlot_0100 - * @tc.desc : Test GetNotificationSlot function - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01600, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName"; - sptr notificationSlot; - sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); - std::vector> spSlots; - spSlots.push_back(spSlot); - NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationSlot( - bundleName, NotificationConstant::OTHER, notificationSlot), - (int)ERR_OK); - EXPECT_EQ(spSlot->GetName(), notificationSlot->GetName()); -} /** * @tc.number : NotificationPreferencesTest_01700 @@ -329,7 +175,7 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01700, Functio std::vector> slotsResult; EXPECT_EQ( (int)NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleName, slotsResult), (int)ERR_OK); - EXPECT_EQ((int)slotsResult.size(), 1); + EXPECT_EQ((int)slotsResult.size(), 5); } /** @@ -364,7 +210,7 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01900, Functio std::vector> groups; EXPECT_EQ( (int)NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundleName, groups), (int)ERR_OK); - EXPECT_EQ((int)groups.size(), 1); + EXPECT_EQ((int)groups.size(), 3); } /** @@ -419,21 +265,6 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02200, Functio EXPECT_EQ((int)NotificationPreferences::GetInstance().SetShowBadge(bundleName, false), (int)ERR_OK); } -/** - * @tc.number : NotificationPreferencesTest_02300 - * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0200 - * @tc.desc : Test RemoveNotificationSlotGroups function when bundle not exist - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02300, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName"; - std::string groupId = "id1"; - std::vector groupIds; - groupIds.push_back(groupId); - EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), - (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); -} - /** * @tc.number : NotificationPreferencesTest_02400 * @tc.name : AMS_ANS_IsShowBadge_0200 @@ -508,21 +339,6 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02900, Functio EXPECT_FALSE(enabled); } -/** - * @tc.number : NotificationPreferencesTest_03000 - * @tc.name : AMS_ANS_UpdateNotificationSlotGroups_0200 - * @tc.desc : Test UpdateNotificationSlotGroups function when file is null - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03000, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName"; - sptr spGroup = new NotificationSlotGroup("groupId", "name"); - std::vector> groups; - groups.push_back(spGroup); - EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleName, groups), - (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); -} - /** * @tc.number : NotificationPreferencesTest_03100 * @tc.name : AMS_ANS_RemoveNotificationForBundle_0100 @@ -535,17 +351,6 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03100, Functio (int)ERR_ANS_INVALID_PARAM); } -/** - * @tc.number : NotificationPreferencesTest_03200 - * @tc.name : AMS_ANS_ClearNotificationInRestoreFactorySettings_0100 - * @tc.desc : Test ClearNotificationInRestoreFactorySettings function when file is null - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03200, Function | SmallTest | Level1) -{ - EXPECT_EQ((int)NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(), - (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); -} - /** * @tc.number : NotificationPreferencesTest_03300 * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0200 @@ -624,7 +429,7 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03700, Functio std::vector> groups; groups.push_back(spGroup); EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleName, groups), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID); + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST); } /** @@ -663,7 +468,7 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04000, Functio std::string bundleName = "bundleName"; int importanceResult; EXPECT_EQ((int)NotificationPreferences::GetInstance().GetImportance(bundleName, importanceResult), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + (int)ERR_OK); } /** @@ -689,7 +494,7 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04200, Functio std::string bundleName = "bundleName"; int totalBadgeNum; EXPECT_EQ((int)NotificationPreferences::GetInstance().GetTotalBadgeNums(bundleName, totalBadgeNum), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + 0); } /** @@ -713,8 +518,7 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04400, Functio { std::string bundleName = "bundleName"; bool allow; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleName, allow), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleName, allow),0); } /** @@ -738,8 +542,7 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04600, Functio { std::string bundleName = "bundleName"; bool enabled; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleName, enabled), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleName, enabled),0); } /** @@ -777,21 +580,6 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04800, Functio (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM); } -/** - * @tc.number : NotificationPreferencesTest_04900 - * @tc.name : AMS_ANS_UpdateNotificationSlots_0400 - * @tc.desc : Test UpdateNotificationSlots function when file is null - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04900, Function | SmallTest | Level1) -{ - std::string bundleName = "bundleName"; - sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); - std::vector> spSlots; - spSlots.push_back(spSlot); - EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleName, spSlots), - (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); -} - /** * @tc.number : NotificationPreferencesTest_05000 * @tc.name : AMS_ANS_SetDisturbMode_0100 @@ -804,17 +592,6 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_05000, Functio (int)ERR_OK); } -/** - * @tc.number : NotificationPreferencesTest_05100 - * @tc.name : AMS_ANS_GetDisturbMode_0100 - * @tc.desc : Test GetDisturbMode function when file is null - */ -HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_05100, Function | SmallTest | Level1) -{ - NotificationConstant::DisturbMode mode; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDisturbMode(mode), (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); -} - /** * @tc.number : NotificationPreferencesTest_05200 * @tc.name : AMS_ANS_GetDisturbMode_0200 diff --git a/services/ans/test/unittest/notification_slot_filter_test.cpp b/services/ans/test/unittest/notification_slot_filter_test.cpp index c7f9c283b36fde7c872e04191266e30426fb1e5e..376adab031ae2c3834c15ebe7131319f5434c6f2 100644 --- a/services/ans/test/unittest/notification_slot_filter_test.cpp +++ b/services/ans/test/unittest/notification_slot_filter_test.cpp @@ -13,10 +13,11 @@ * limitations under the License. */ -#include "notification_slot_filter.h" #include #include +#include "notification_slot_filter.h" + using namespace testing::ext; namespace OHOS { namespace Notification { @@ -71,9 +72,11 @@ HWTEST_F(NotificationSlotFilterTest, NotificationSlotFilterTest_00200, Function HWTEST_F(NotificationSlotFilterTest, NotificationSlotFilterTest_00300, Function | SmallTest | Level1) { NotificationSlotFilter notificationSlotFilter; - sptr request = new NotificationRequest(); - auto objptr = new Notification(request); - notificationSlotFilter.OnPublish(objptr); + 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); + notificationSlotFilter.OnPublish(record); } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/notification_subscriber_manager_test.cpp b/services/ans/test/unittest/notification_subscriber_manager_test.cpp index 33d5f50064eb8793e1b29e6b0a3acf09dd1e423c..d5a6b3cd52891458352d425f15bd6cae223254cf 100644 --- a/services/ans/test/unittest/notification_subscriber_manager_test.cpp +++ b/services/ans/test/unittest/notification_subscriber_manager_test.cpp @@ -13,11 +13,13 @@ * limitations under the License. */ -#include "notification_subscriber_manager.h" #include #include + #define private public #include "notification_subscriber.h" +#include "notification_subscriber_manager.h" + using namespace testing::ext; namespace OHOS { namespace Notification { diff --git a/services/ans/test/unittest/permission_filter_test.cpp b/services/ans/test/unittest/permission_filter_test.cpp index cf9885c222d9b103930d94ecbd4f4f1875d11d36..e984e5df6f5be22f1f5cc6501e0a78778e531999 100644 --- a/services/ans/test/unittest/permission_filter_test.cpp +++ b/services/ans/test/unittest/permission_filter_test.cpp @@ -13,13 +13,13 @@ * limitations under the License. */ -#include "permission_filter.h" #include #include #include "ans_inner_errors.h" #include "notification_preferences.h" #include "notification_slot.h" +#include "permission_filter.h" #include "string_ex.h" using namespace testing::ext; @@ -80,9 +80,11 @@ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00200, Function | SmallTest HWTEST_F(PermissionFilterTest, PermissionFilterTest_00300, Function | SmallTest | Level1) { PermissionFilter permissionFilter; - sptr request = new NotificationRequest(); - auto objptr = new Notification(request); - EXPECT_EQ(permissionFilter.OnPublish(objptr), (int)ERR_ANS_INVALID_PARAM); + 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); } /** @@ -98,10 +100,12 @@ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00400, Function | SmallTest std::vector> slots; slots.push_back(slot); NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots); - sptr request = new NotificationRequest(); - request->SetOwnerBundleName(bundleName); - sptr notification = new Notification(request); - EXPECT_EQ(permissionFilter.OnPublish(notification), ERR_OK); + std::shared_ptr record = std::make_shared(); + record->request = new NotificationRequest(); + record->request->SetOwnerBundleName(bundleName); + record->notification = new Notification(record->request); + record->slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + EXPECT_EQ(permissionFilter.OnPublish(record), ERR_OK); } /** @@ -117,10 +121,12 @@ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00500, Function | SmallTest std::vector> slots; slots.push_back(slot); NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots); - sptr request = new NotificationRequest(); - request->SetOwnerBundleName("bundleName1"); - sptr notification = new Notification(request); - EXPECT_EQ((int)permissionFilter.OnPublish(notification), (int)ERR_OK); + 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); } /** @@ -137,10 +143,13 @@ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00600, Function | SmallTest slots.push_back(slot); NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots); NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleName, false); - sptr request = new NotificationRequest(); - request->SetOwnerBundleName(bundleName); - sptr notification = new Notification(request); - EXPECT_EQ((int)permissionFilter.OnPublish(notification), (int)ERR_ANS_NOT_ALLOWED); + std::shared_ptr record = std::make_shared(); + record->request = new NotificationRequest(); + record->request->SetOwnerBundleName(bundleName); + record->notification = new Notification(record->request); + record->slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + EXPECT_EQ((int)permissionFilter.OnPublish(record), (int)ERR_ANS_NOT_ALLOWED); } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index c8bbdcf5f53ccb909491dc41e0828d9a984d3e57..740e3b89562c3937fbdef65251285e59b1f3ae42 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -17,17 +17,6 @@ import("//build/test.gni") module_output_path = "ans_standard/moduletest" -config("public_ans_config") { - include_dirs = [ - "${services_path}/ans/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "${kits_path}/native/include", - "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content/", - ] -} - config("json_config") { cflags_cc = [ "-fexceptions" ] } @@ -36,48 +25,54 @@ ohos_moduletest("ans_module_test") { module_out_path = module_output_path include_dirs = [ "include", - "${innerkits_path}/base/include", - "${innerkits_path}/core/include", - "${kits_path}/native/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", "//foundation/appexecfwk/standard/libs/libeventhandler/src", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//utils/native/base/include", "//utils/system/safwk/native/include", - "//base/notification/ans_standard/services/ans/include", - "//third_party/json/include", - "//base/notification/ans_standard/services/test/moduletest/mock/include", + "${services_path}/ans/include", + "${services_path}/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 = [ - "//base/notification/ans_standard/innerkits/core/src/ans_manager_stub.cpp", - "//base/notification/ans_standard/kits/native/src/notification.cpp", - "//base/notification/ans_standard/services/ans/src/advanced_notification_service.cpp", - "//base/notification/ans_standard/services/ans/src/advanced_notification_service_ability.cpp", - "//base/notification/ans_standard/services/ans/src/bundle_manager_helper.cpp", - "//base/notification/ans_standard/services/ans/src/disturb_filter.cpp", - "//base/notification/ans_standard/services/ans/src/notification_preferences.cpp", - "//base/notification/ans_standard/services/ans/src/notification_slot_filter.cpp", - "//base/notification/ans_standard/services/ans/src/notification_subscriber_manager.cpp", - "//base/notification/ans_standard/services/ans/src/permission_filter.cpp", + "${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", + "${services_path}/ans/src/notification_preferences_info.cpp", + "${services_path}/ans/src/notification_slot_filter.cpp", + "${services_path}/ans/src/notification_subscriber_manager.cpp", + "${services_path}/ans/src/permission_filter.cpp", + "${services_path}/ans/src/system_event_observer.cpp", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/autils/src/constant.cpp", "ans_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_single_kv_store.cpp", ] configs = [ "//utils/native/base:utils_config", - "${innerkits_path}:public_ans_innerkits_config", ":json_config", ] deps = [ - "${innerkits_path}:ans_innerkits", - "${kits_path}/native:ans_kits", - "${kits_path}/native/wantagent:wantagent_kits", + "${core_path}:ans_core", + "${frameworks_path}/ans/native:ans_innerkits", + "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", @@ -94,6 +89,7 @@ ohos_moduletest("ans_module_test") { "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", diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp index 7233143555f5fe7750ce9b135150cfc00725ac29..bc99a3773f1abb48f81e44ec1a8297f79aee9a1d 100644 --- a/services/test/moduletest/ans_module_test.cpp +++ b/services/test/moduletest/ans_module_test.cpp @@ -1,41 +1,70 @@ +#include #include -#include "advanced_notification_service.h" + #include "notification_preferences.h" -#include #define private public +#include "advanced_notification_service.h" #include "notification_subscriber.h" using namespace testing::ext; + namespace OHOS { namespace Notification { +typedef std::function, const std::shared_ptr)> + ConsumedFunc; +typedef std::function, const std::shared_ptr, int)> + CanceledFunc; -const int32_t USLEEP_TIME = 300; sptr g_advancedNotificationService; bool passed = false; -class TestAnsSubscriber : public NotificationSubscriber -{ +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 {} + ~TestAnsSubscriber(){}; + + virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override + { + if (subscriberCb_ != nullptr) { + subscriberCb_(result); + } + } + virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override + { + if (unSubscriberCb_ != nullptr) { + unSubscriberCb_(result); + } + } + 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 + const std::shared_ptr &sortingMap, int deleteReason) override { - passed = true; + if (canceledCb_ != nullptr) { + canceledCb_(request, sortingMap, deleteReason); + } } + virtual void OnConsumed(const std::shared_ptr &request) override + {} virtual void OnConsumed(const std::shared_ptr &request, - const std::shared_ptr &sortingMap) override + const std::shared_ptr &sortingMap) override { - passed = true; + if (consumedCb_ != nullptr) { + consumedCb_(request, sortingMap); + } } + + ConsumedFunc consumedCb_{nullptr}; + CanceledFunc canceledCb_{nullptr}; + std::function unSubscriberCb_{nullptr}; + std::function subscriberCb_{nullptr}; }; -class AnsModuleTest : public testing::Test -{ +class AnsModuleTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); @@ -45,22 +74,30 @@ public: void AnsModuleTest::SetUpTestCase() { - g_advancedNotificationService = AdvancedNotificationService::GetInstance(); + passed = false; + g_advancedNotificationService = new AdvancedNotificationService(); + NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); } void AnsModuleTest::TearDownTestCase() { - sptr g_advancedNotificationService = nullptr; + passed = false; + g_advancedNotificationService = new AdvancedNotificationService(); + NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); } void AnsModuleTest::SetUp() { + passed = false; + g_advancedNotificationService = new AdvancedNotificationService(); NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); } void AnsModuleTest::TearDown() { + sptr g_advancedNotificationService = nullptr; NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); + passed = false; } void TestAddSlots() @@ -81,6 +118,9 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_001, Function | SmallTest | Level1) TestAddSlots(); std::string label = "testLabel"; auto subscriber = new TestAnsSubscriber(); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; sptr req = new NotificationRequest(2); sptr req1 = new NotificationRequest(1); req1->SetLabel(label); @@ -90,7 +130,6 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_001, Function | SmallTest | Level1) EXPECT_EQ((int)g_advancedNotificationService->Publish(label, req), (int)ERR_OK); EXPECT_EQ((int)g_advancedNotificationService->Publish(label, req1), (int)ERR_OK); EXPECT_EQ((int)g_advancedNotificationService->Cancel(1, label), (int)ERR_OK); - usleep(USLEEP_TIME); EXPECT_TRUE(passed); g_advancedNotificationService->CancelAll(); EXPECT_EQ((int)g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), info), (int)ERR_OK); @@ -99,7 +138,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_001, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_002 - * @tc.name : AMS_ANS_GetActiveNotifications_0100 + * @tc.name : AMS_ANS_GetActiveNotifications_0200 * @tc.desc : Test the function of getting notifications and getting all notifications */ HWTEST_F(AnsModuleTest, AnsModuleTest_002, Function | SmallTest | Level1) @@ -128,5 +167,2492 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_002, Function | SmallTest | Level1) EXPECT_EQ((int)notifications.size(), (int)2); EXPECT_EQ((int)g_advancedNotificationService->CancelAll(), (int)ERR_OK); } + +/** + * @tc.number : AnsModuleTest_003 + * @tc.name : AMS_ANS_GetActiveNotifications_0300 + * @tc.desc : Test publish notifications when slot are not allowed publish. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_003, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + + g_advancedNotificationService->SetNotificationsEnabledForBundle("", false); + + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(false, passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_004 + * @tc.name : AMS_ANS_GetActiveNotifications_0400 + * @tc.desc : Test publish notifications when Disturb are not allowed publish. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_004, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + + g_advancedNotificationService->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_NONE); + + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(false, passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_005 + * @tc.name : AMS_ANS_GetActiveNotifications_0500 + * @tc.desc : Test publish notifications when Disturb are not allowed publish. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_005, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = + [](const std::shared_ptr notification, const std::shared_ptr sortingMap) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_006 + * @tc.name : AMS_ANS_GetActiveNotifications_0600 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_006, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_007 + * @tc.name : AMS_ANS_GetActiveNotifications_0700 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_007, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = + [](const std::shared_ptr notification, const std::shared_ptr sortingMap) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0013 + * @tc.name : AMS_ANS_GetActiveNotifications_01300 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0013, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0014 + * @tc.name : AMS_ANS_GetActiveNotifications_01400 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0014, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("1"); + normalContent->SetTitle("1"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0015 + * @tc.name : AMS_ANS_GetActiveNotifications_01500 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0015, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("1"); + normalContent->SetTitle("1"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0017 + * @tc.name : AMS_ANS_GetActiveNotifications_01700 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0017, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("1"); + normalContent->SetTitle("1"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0019 + * @tc.name : AMS_ANS_GetActiveNotifications_01900 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0019, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr longTextContent = std::make_shared(); + longTextContent->SetText("1"); + longTextContent->SetTitle("1"); + std::shared_ptr content = std::make_shared(longTextContent); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0021 + * @tc.name : AMS_ANS_GetActiveNotifications_02100 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0021, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = + [](const std::shared_ptr notification, const std::shared_ptr sortingMap) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + std::shared_ptr pictureContent = std::make_shared(); + pictureContent->SetText("1"); + pictureContent->SetTitle("1"); + std::shared_ptr content = std::make_shared(pictureContent); + req->SetContent(content); + req1->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0023 + * @tc.name : AMS_ANS_GetActiveNotifications_02300 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0023, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); } -} \ No newline at end of file + +/** + * @tc.number : AnsModuleTest_0031 + * @tc.name : AMS_ANS_GetActiveNotifications_03100 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0031, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = + [](const std::shared_ptr notification, const std::shared_ptr sortingMap) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req1->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0033 + * @tc.name : AMS_ANS_GetActiveNotifications_03300 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0033, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr notification, + const std::shared_ptr) { + if (notification->EnableVibrate()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slot->SetEnableVibration(true); + slot->SetVibrationStyle(std::vector(1, 1)); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_FALSE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0034 + * @tc.name : AMS_ANS_GetActiveNotifications_03400 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0034, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr notification, + const std::shared_ptr) { + if (notification->EnableSound()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slot->SetEnableVibration(true); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0035 + * @tc.name : AMS_ANS_GetActiveNotifications_03500 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0035, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->canceledCb_ = [](const std::shared_ptr &request, + const std::shared_ptr &sortingMap, + int deleteReason) { passed = true; }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slot->SetEnableVibration(true); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Cancel(0, label); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0036 + * @tc.name : AMS_ANS_GetActiveNotifications_03600 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0036, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->canceledCb_ = [](const std::shared_ptr &request, + const std::shared_ptr &sortingMap, + int deleteReason) { passed = true; }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slot->SetEnableVibration(true); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->CancelAll(); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0039 + * @tc.name : AMS_ANS_GetActiveNotifications_03900 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0039, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = + [](const std::shared_ptr notification, const std::shared_ptr sortingMap) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slot->SetEnableVibration(true); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req1->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0040 + * @tc.name : AMS_ANS_GetActiveNotifications_04000 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0040, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr notification, + const std::shared_ptr) { passed = true; }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); + slot->SetEnableVibration(true); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0041 + * @tc.name : AMS_ANS_GetActiveNotifications_04100 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0041, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr notification, + const std::shared_ptr) { passed = true; }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slot->SetEnableVibration(true); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0042 + * @tc.name : AMS_ANS_GetActiveNotifications_04200 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0042, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr notification, + const std::shared_ptr) { passed = true; }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slot->SetEnableVibration(true); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0043 + * @tc.name : AMS_ANS_GetActiveNotifications_04300 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0043, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr notification, + const std::shared_ptr) { passed = true; }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CUSTOM); + slot->SetEnableVibration(true); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_TRUE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0049 + * @tc.name : AMS_ANS_GetActiveNotifications_04900 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0049, Function | SmallTest | Level1) +{ + // 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); + slots.push_back(socialSlot); + slots.push_back(reminderSlot); + slots.push_back(contentSlot); + slots.push_back(otherSlot); + + g_advancedNotificationService->AddSlots(slots); +} + +/** + * @tc.number : AnsModuleTest_0051 + * @tc.name : AMS_ANS_GetActiveNotifications_05100 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0051, Function | SmallTest | Level1) +{ + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::string slotId = slot->GetId(); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + std::vector> slotsRef{}; + g_advancedNotificationService->GetSlots(slotsRef); + EXPECT_EQ(5, static_cast(slotsRef.size())); + std::vector slotsId{}; + for (const auto &i : slotsRef) { + slotsId.push_back(i->GetId()); + } + g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + g_advancedNotificationService->GetSlots(slotsRef); + EXPECT_EQ(9, static_cast(slotsRef.size())); +} + +/** + * @tc.number : AnsModuleTest_0052 + * @tc.name : AMS_ANS_GetActiveNotifications_05200 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0052, Function | SmallTest | Level1) +{ + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + std::vector> slotsRef{}; + g_advancedNotificationService->GetSlots(slotsRef); + std::vector slotsId{}; + for (const auto &i : slotsRef) { + slotsId.push_back(i->GetId()); + } + g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + g_advancedNotificationService->GetSlots(slotsRef); + EXPECT_EQ(9, static_cast(slotsRef.size())); +} + +/** + * @tc.number : AnsModuleTest_0054 + * @tc.name : AMS_ANS_GetActiveNotifications_05400 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0054, Function | SmallTest | Level1) +{ + // add slot + std::vector> slots; + sptr group = new NotificationSlotGroup(); + 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); + socialSlot->SetSlotGroup(group->GetId()); + reminderSlot->SetSlotGroup(group->GetId()); + contentSlot->SetSlotGroup(group->GetId()); + otherSlot->SetSlotGroup(group->GetId()); + + // add slot group + std::vector> slotGroups; + slotGroups.push_back(group); + g_advancedNotificationService->AddSlotGroups(slotGroups); + + slots.push_back(socialSlot); + slots.push_back(reminderSlot); + slots.push_back(contentSlot); + slots.push_back(otherSlot); + + EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), 0); +} + +/** + * @tc.number : AnsModuleTest_0055 + * @tc.name : AMS_ANS_GetActiveNotifications_05500 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0055, Function | SmallTest | Level1) +{ + // add slot + std::vector> slots; + sptr group = new NotificationSlotGroup(); + sptr socialSlot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + socialSlot->SetSlotGroup(group->GetId()); + slots.push_back(socialSlot); + EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), 0); + + EXPECT_EQ(g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION), 0); +} + +/** + * @tc.number : AnsModuleTest_0056 + * @tc.name : AMS_ANS_GetActiveNotifications_05600 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0056, Function | SmallTest | Level1) +{ + // add slot + std::vector> slots; + sptr group = new NotificationSlotGroup("id", "name"); + sptr socialSlot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + socialSlot->SetSlotGroup(group->GetId()); + slots.push_back(socialSlot); + EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), 0); + + // get slot group by groupId + group = nullptr; + g_advancedNotificationService->GetSlotGroup("id", group); + EXPECT_FALSE(group != nullptr); + + // remove slot group + EXPECT_EQ(g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION), 0); +} + +/** + * @tc.number : AnsModuleTest_0058 + * @tc.name : AMS_ANS_GetActiveNotifications_05800 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0058, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + subscriber->consumedCb_ = [](const std::shared_ptr r, const std::shared_ptr) { + if (r->GetNotificationRequest().GetBadgeNumber() == 1) { + passed = true; + } + }; + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(); + slot->EnableBadge(true); + slots.push_back(slot); + EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), 0); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + req->SetBadgeNumber(1); + + // SetShowBadgeEnabledForBundle true + g_advancedNotificationService->SetShowBadgeEnabledForBundle("bundleName", true); + + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(true, passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0060 + * @tc.name : AMS_ANS_GetActiveNotifications_06000 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0060, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + subscriber->consumedCb_ = [](const std::shared_ptr r, const std::shared_ptr) { + passed = true; + }; + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(); + slot->EnableBadge(true); + slots.push_back(slot); + EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), 0); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + req->SetBadgeNumber(1); + + // not allow publish notification + g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", false); + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(false, passed); + + // allow publish + g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", true); + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(true, passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0061 + * @tc.name : AMS_ANS_GetActiveNotifications_06100 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0061, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + subscriber->consumedCb_ = [](const std::shared_ptr r, const std::shared_ptr) { + passed = true; + }; + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(); + slot->EnableBadge(true); + slots.push_back(slot); + EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), 0); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + req->SetBadgeNumber(1); + + // allow publish notification + g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", true); + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(true, passed); + + // not allow publish + passed = false; + g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", false); + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(false, passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_062 + * @tc.name : AMS_ANS_GetActiveNotifications_06200 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0062, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = + [](const std::shared_ptr notification, const std::shared_ptr sortingMap) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + EXPECT_FALSE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_063 + * @tc.name : AMS_ANS_GetActiveNotifications_06300 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0063, 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) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + EXPECT_FALSE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); +} + +/** + * @tc.number : AnsModuleTest_064 + * @tc.name : AMS_ANS_GetActiveNotifications_06400 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0064, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->unSubscriberCb_ = [](NotificationConstant::SubscribeResult) { passed = true; }; + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); + EXPECT_TRUE(passed); +} + +/** + * @tc.number : AnsModuleTest_065 + * @tc.name : AMS_ANS_GetActiveNotifications_06500 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0065, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr); + subscriber->unSubscriberCb_ = [](NotificationConstant::SubscribeResult) { passed = true; }; + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); + EXPECT_TRUE(passed); +} + +/** + * @tc.number : AnsModuleTest_066 + * @tc.name : AMS_ANS_GetActiveNotifications_06600 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0066, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr); + subscriber->canceledCb_ = [](const std::shared_ptr &request, + const std::shared_ptr &sortingMap, + int deleteReason) { passed = true; }; + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + + // publish request + g_advancedNotificationService->Publish(label, req); + + // remove request + g_advancedNotificationService->Delete("1_testLabel_0"); + EXPECT_FALSE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); +} + +/** + * @tc.number : AnsModuleTest_100 + * @tc.name : AMS_ANS_GetActiveNotifications_10000 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0100, Function | SmallTest | Level1) +{ + // create wantagent + std::shared_ptr agent = std::make_shared(); + + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [&agent](const std::shared_ptr notification, + const std::shared_ptr + sortingMap) { passed = true; }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + + // set content + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("1"); + normalContent->SetTitle("1"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(passed, false); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_101 + * @tc.name : AMS_ANS_GetActiveNotifications_10100 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0101, Function | SmallTest | Level1) +{ + // create wantagent + std::shared_ptr agent = std::make_shared(); + + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [&agent](const std::shared_ptr notification, + const std::shared_ptr + sortingMap) { passed = true; }; + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetWantAgent(agent); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(passed, false); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_102 + * @tc.name : AMS_ANS_GetActiveNotifications_10200 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0102, Function | SmallTest | Level1) +{ + // create wantagent + std::shared_ptr agent = std::make_shared(); + + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [&agent](const std::shared_ptr notification, + const std::shared_ptr + sortingMap) { passed = true; }; + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetWantAgent(agent); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(passed, false); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_103 + * @tc.name : AMS_ANS_GetActiveNotifications_10300 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0103, Function | SmallTest | Level1) +{ + // create wantagent + std::shared_ptr agent = std::make_shared(); + + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("a"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [&agent](const std::shared_ptr notification, + const std::shared_ptr + sortingMap) { passed = true; }; + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetWantAgent(agent); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(passed, false); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_104 + * @tc.name : AMS_ANS_GetActiveNotifications_10400 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0104, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + g_advancedNotificationService->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_NONE); + + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(false, passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_105 + * @tc.name : AMS_ANS_GetActiveNotifications_10500 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0105, Function | SmallTest | Level1) +{ + + 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); + + g_advancedNotificationService->AddSlots(slots); + EXPECT_EQ(0, g_advancedNotificationService->AddSlots(slots)); +} + +/** + * @tc.number : AnsModuleTest_106 + * @tc.name : AMS_ANS_GetActiveNotifications_10600 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0106, Function | SmallTest | Level1) +{ + // create wantagent + std::shared_ptr agent = std::make_shared(); + + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = + [](const std::shared_ptr notification, const std::shared_ptr sortingMap) { + passed = true; + }; + + // set disturb mode + g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", false); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetWantAgent(agent); + + // publish request + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(passed, false); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_107 + * @tc.name : AMS_ANS_GetActiveNotifications_10700 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0107, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + + // set content + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("1"); + normalContent->SetTitle("1"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + req1->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + + // remove request + g_advancedNotificationService->Delete("1_testLabel_0"); + g_advancedNotificationService->Delete("1_testLabel_1"); + int nums = -1; + g_advancedNotificationService->GetActiveNotificationNums(nums); + EXPECT_EQ(nums, 0); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_108 + * @tc.name : AMS_ANS_GetActiveNotifications_10800 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0108, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + + // set content + std::shared_ptr normalContent = std::make_shared(); + normalContent->SetText("1"); + normalContent->SetTitle("1"); + std::shared_ptr content = std::make_shared(normalContent); + req->SetContent(content); + req1->SetContent(content); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + + // remove request + g_advancedNotificationService->DeleteAll(); + int nums = -1; + g_advancedNotificationService->GetActiveNotificationNums(nums); + EXPECT_EQ(nums, 0); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_110 + * @tc.name : AMS_ANS_GetActiveNotifications_11000 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0110, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + subscriber->unSubscriberCb_ = [](NotificationConstant::SubscribeResult) { passed = true; }; + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + + // unsubscriber + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); + EXPECT_EQ(passed, true); +} + +/** + * @tc.number : AnsModuleTest_111 + * @tc.name : AMS_ANS_GetActiveNotifications_11100 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0111, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + subscriberInfo->AddAppName("bundleName"); + subscriber->subscriberCb_ = [](NotificationConstant::SubscribeResult) { passed = true; }; + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); + EXPECT_EQ(passed, true); +} + +/** + * @tc.number : AnsModuleTest_112 + * @tc.name : AMS_ANS_GetActiveNotifications_11200 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0112, 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) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking() && notification->EnableLight() && + notification->EnableSound() && notification->EnableVibrate()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slot->SetSound(Uri(".")); + slot->SetEnableLight(true); + slot->SetEnableVibration(true); + slot->SetVibrationStyle(std::vector(1, 1)); + slot->SetLedLightColor(1); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req1->SetContent(content); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + req1->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + // publish request + EXPECT_FALSE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); +} + +/** + * @tc.number : AnsModuleTest_113 + * @tc.name : AMS_ANS_GetActiveNotifications_11300 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0113, 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) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking() && notification->EnableLight() && + notification->EnableSound() && notification->EnableVibrate()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slot->SetSound(Uri(".")); + slot->SetEnableLight(true); + slot->SetEnableVibration(true); + slot->SetVibrationStyle(std::vector(1, 1)); + slot->SetLedLightColor(1); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req1->SetContent(content); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req1->SetSlotType(NotificationConstant::SlotType::OTHER); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); + EXPECT_FALSE(passed); +} + +/** + * @tc.number : AnsModuleTest_114 + * @tc.name : AMS_ANS_GetActiveNotifications_11400 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0114, 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) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking() && notification->EnableLight() && + notification->EnableSound() && notification->EnableVibrate()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slot->SetSound(Uri(".")); + slot->SetEnableLight(true); + slot->SetEnableVibration(true); + slot->SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PUBLIC); + slot->SetLedLightColor(1); + slot->SetVibrationStyle(std::vector(1, 1)); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req1->SetContent(content); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req1->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); + EXPECT_FALSE(passed); +} + +/** + * @tc.number : AnsModuleTest_116 + * @tc.name : AMS_ANS_GetActiveNotifications_11600 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0116, 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) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking() && notification->EnableLight() && + notification->EnableSound() && notification->EnableVibrate()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); + slot->SetSound(Uri(".")); + slot->SetEnableLight(true); + slot->SetEnableVibration(true); + slot->SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PUBLIC); + slot->SetLedLightColor(1); + slot->SetVibrationStyle(std::vector(1, 1)); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req1->SetContent(content); + req->SetSlotType(NotificationConstant::SlotType::SERVICE_REMINDER); + req1->SetSlotType(NotificationConstant::SlotType::SERVICE_REMINDER); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + EXPECT_FALSE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); +} + +/** + * @tc.number : AnsModuleTest_117 + * @tc.name : AMS_ANS_GetActiveNotifications_11700 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0117, 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) { + std::vector sortingKey = sortingMap->GetKey(); + + NotificationSorting sorting1; + NotificationSorting sorting2; + if (sortingKey.size() == 2) { + sortingMap->GetNotificationSorting("1_testLabel_0", sorting1); + sortingMap->GetNotificationSorting("1_testLabel_1", sorting2); + } + if (sorting1.GetRanking() < sorting2.GetRanking() && notification->EnableLight() && + notification->EnableSound() && notification->EnableVibrate()) { + passed = true; + } + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slot->SetSound(Uri(".")); + slot->SetEnableLight(true); + slot->SetEnableVibration(true); + slot->SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PUBLIC); + slot->SetLedLightColor(1); + slot->SetVibrationStyle(std::vector(1, 1)); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req1->SetContent(content); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + req1->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req1); + EXPECT_FALSE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); +} + +/** + * @tc.number : AnsModuleTest_118 + * @tc.name : AMS_ANS_GetActiveNotifications_11800 + * @tc.desc : Test publish notifications when Disturb are not allowed publish. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0118, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + + g_advancedNotificationService->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_NONE); + + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(false, passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_120 + * @tc.name : AMS_ANS_GetActiveNotifications_12000 + * @tc.desc : Test publish notifications when Disturb are not allowed publish. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0120, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + sptr subscriberInfo = new NotificationSubscribeInfo(); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", false); + + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(false, passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); +} + +/** + * @tc.number : AnsModuleTest_0121 + * @tc.name : AMS_ANS_GetActiveNotifications_12100 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0121, Function | SmallTest | Level1) +{ + // 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); + + EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), 0); + EXPECT_EQ(g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION), 0); + EXPECT_EQ(g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::SERVICE_REMINDER), 0); + EXPECT_EQ(g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::CONTENT_INFORMATION), 0); + EXPECT_EQ(g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::OTHER), 0); + EXPECT_EQ(g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::CUSTOM), 0); +} + +/** + * @tc.number : AnsModuleTest_0122 + * @tc.name : AMS_ANS_GetActiveNotifications_12200 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0122, 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) { + passed = true; + }; + + subscriber->canceledCb_ = [](const std::shared_ptr &request, + const std::shared_ptr &sortingMap, + int deleteReason) { passed = true; }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req1->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + req1->SetSlotType(NotificationConstant::SlotType::OTHER); + + // publish request + + // remove social slot + EXPECT_EQ(0, g_advancedNotificationService->RemoveSlotByType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION)); + + // add slot + std::vector> otherSlots; + slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + otherSlots.push_back(slot); + EXPECT_EQ(0, g_advancedNotificationService->AddSlots(otherSlots)); + + EXPECT_FALSE(passed); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); +} + +/** + * @tc.number : AnsModuleTest_0123 + * @tc.name : AMS_ANS_GetActiveNotifications_12300 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +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); + + 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->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + req1->SetSlotType(NotificationConstant::SlotType::SERVICE_REMINDER); + req2->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req3->SetSlotType(NotificationConstant::SlotType::OTHER); + req4->SetSlotType(NotificationConstant::SlotType::CUSTOM); + + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(ret, 0); + g_advancedNotificationService->Publish(label, req1); + EXPECT_EQ(ret, 0); + g_advancedNotificationService->Publish(label, req2); + EXPECT_EQ(ret, 0); + g_advancedNotificationService->Publish(label, req3); + EXPECT_EQ(ret, 0); + g_advancedNotificationService->Publish(label, req4); + EXPECT_EQ(ret, 0); + + g_advancedNotificationService->DeleteAll(); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); + EXPECT_FALSE(passed); +} + +/** + * @tc.number : AnsModuleTest_0124 + * @tc.name : AMS_ANS_GetActiveNotifications_12400 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0124, 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) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); + EXPECT_FALSE(passed); +} + +/** + * @tc.number : AnsModuleTest_0125 + * @tc.name : AMS_ANS_GetActiveNotifications_12500 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0125, 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) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); + EXPECT_FALSE(passed); +} + +/** + * @tc.number : AnsModuleTest_0126 + * @tc.name : AMS_ANS_GetActiveNotifications_12600 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0126, 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) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); + slots.push_back(slot); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr content = std::make_shared(contentImpl); + req->SetContent(content); + req->SetSlotType(NotificationConstant::SlotType::SERVICE_REMINDER); + + // publish request + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); + EXPECT_FALSE(passed); +} + +/** + * @tc.number : AnsModuleTest_0127 + * @tc.name : AMS_ANS_GetActiveNotifications_12700 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0127, 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++; }; + + // add slot + sptr group = new NotificationSlotGroup("id", "name"); + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr slot1 = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); + slots.push_back(slot); + slots.push_back(slot1); + slot->SetSlotGroup(group->GetId()); + g_advancedNotificationService->AddSlots(slots); + + // add slot group + std::vector> slotGroups; + slotGroups.push_back(group); + g_advancedNotificationService->AddSlotGroups(slotGroups); + + // create content + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr pictureContent = std::make_shared(contentImpl); + + std::shared_ptr contentImpl1 = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr longTextContent = std::make_shared(contentImpl); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req->SetContent(pictureContent); + req1->SetLabel(label); + req1->SetContent(longTextContent); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + req1->SetSlotType(NotificationConstant::SlotType::SERVICE_REMINDER); + + // publish + EXPECT_EQ(0, ret); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); +} + +/** + * @tc.number : AnsModuleTest_0128 + * @tc.name : AMS_ANS_GetActiveNotifications_12800 + * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0128, 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++; }; + + // add slot + sptr group = new NotificationSlotGroup("id", "name"); + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + sptr slot1 = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slots.push_back(slot); + slots.push_back(slot1); + slot->SetSlotGroup(group->GetId()); + g_advancedNotificationService->AddSlots(slots); + + // add slot group + std::vector> slotGroups; + slotGroups.push_back(group); + g_advancedNotificationService->AddSlotGroups(slotGroups); + + // create content + std::shared_ptr contentImpl = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr pictureContent = std::make_shared(contentImpl); + + std::shared_ptr contentImpl1 = std::make_shared(); + contentImpl->SetText("1"); + contentImpl->SetTitle("1"); + std::shared_ptr longTextContent = std::make_shared(contentImpl); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + sptr req1 = new NotificationRequest(1); + req->SetLabel(label); + req->SetContent(pictureContent); + req1->SetLabel(label); + req1->SetContent(longTextContent); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req1->SetSlotType(NotificationConstant::SlotType::OTHER); + + // publish + EXPECT_EQ(0, ret); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); +} + +/** + * @tc.number : AnsModuleTest_0130 + * @tc.name : AMS_ANS_GetActiveNotifications_13000 + * @tc.desc : Test publish notification when slot type is OTHER. + */ +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) + { + EXPECT_EQ(false, notification->EnableVibrate()); + EXPECT_EQ(NotificationConstant::VisiblenessType::PUBLIC,notification->GetLockscreenVisibleness()); + }; + + // add slot + std::vector> slots; + 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); + 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 + auto subscriber = new TestAnsSubscriber(); + 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); + +} + + + + + +} // namespace Notification +} // namespace OHOS + diff --git a/services/test/moduletest/mock/blob.cpp b/services/test/moduletest/mock/blob.cpp new file mode 100755 index 0000000000000000000000000000000000000000..93d2c34700f2b1d15a38ad135a6299d3450168bb --- /dev/null +++ b/services/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/services/test/moduletest/mock/distributed_kv_data_manager.cpp b/services/test/moduletest/mock/distributed_kv_data_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..656932c2043bb1da4c864add54ab2edf13eae208 --- /dev/null +++ b/services/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/services/test/moduletest/mock/include/mock_single_kv_store.h b/services/test/moduletest/mock/include/mock_single_kv_store.h new file mode 100644 index 0000000000000000000000000000000000000000..8a777ea02ea632ddcbd69ebd89a4a6240a9b2a2c --- /dev/null +++ b/services/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/services/test/moduletest/mock/mock_bundle_manager_helper.cpp b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp index afaa94b2b8245ad94e08d9889758c670bdb3c02c..5df99fa52d095ed5f9e4c51929afd1931fe6ca57 100644 --- a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp @@ -21,18 +21,14 @@ namespace OHOS { namespace Notification { - BundleManagerHelper::BundleManagerHelper() -{ -} +{} BundleManagerHelper::~BundleManagerHelper() -{ -} +{} void BundleManagerHelper::OnRemoteDied(const wptr &object) -{ -} +{} std::string BundleManagerHelper::GetBundleNameByUid(uid_t uid) { @@ -45,12 +41,10 @@ bool BundleManagerHelper::IsSystemApp(uid_t uid) } void BundleManagerHelper::Connect() -{ -} +{} void BundleManagerHelper::Disconnect() -{ -} +{} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp index cd58a48388c28f596e09b1eb2933dfb6492ffd46..7654e493fc6f85cba841e3c2740f2cb724f0e241 100644 --- a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -24,14 +24,11 @@ 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) @@ -261,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_single_kv_store.cpp b/services/test/moduletest/mock/mock_single_kv_store.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b580d297471fb6658f861e020621e89b8cb9382 --- /dev/null +++ b/services/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/tools/BUILD.gn b/tools/BUILD.gn index adb8ad2bad0950727d79e06e97d8f7d1f4d9d10b..a123d49460ccb81192e90090765a54a7b429e761 100644 --- a/tools/BUILD.gn +++ b/tools/BUILD.gn @@ -12,5 +12,5 @@ # limitations under the License. group("tools_target") { - deps = [] + deps = [ "dump:anm_target" ] } diff --git a/tools/dump/BUILD.gn b/tools/dump/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a8c2312c09b8d17edd9a753b9d59a4b9a8c74911 --- /dev/null +++ b/tools/dump/BUILD.gn @@ -0,0 +1,53 @@ +# 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") + +group("anm_target") { + deps = [ ":anm" ] +} + +ohos_executable("anm") { + include_dirs = [ "${tools_path}/dump/include" ] + + sources = [ + "${aafwk_path}/tools/aa/src/shell_command.cpp", + "src/main.cpp", + "src/notification_shell_command.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${core_path}:ans_core", + "//utils/native/base:utils", + ] + + configs = [ + "${core_path}:public_ans_core_config", + "${frameworks_path}/wantagent:wantagent_innerkits_public_config", + "${aafwk_path}/tools/aa:ability_command_config", + "${aafwk_path}/services/common:common_config", + ] + + external_deps = [] + external_deps += ans_standard_external_deps + + install_enable = true + part_name = "ans_standard" + subsystem_name = "notification" +} diff --git a/tools/dump/include/notification_shell_command.h b/tools/dump/include/notification_shell_command.h new file mode 100644 index 0000000000000000000000000000000000000000..b881ffacd7b8fd415b082c3c7e6100c25af88f94 --- /dev/null +++ b/tools/dump/include/notification_shell_command.h @@ -0,0 +1,45 @@ +/* + * 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_TOOLS_DUMP_INCLUDE_NOTIFICATION_SHELL_COMMAND_H +#define BASE_NOTIFICATION_ANS_STANDARD_TOOLS_DUMP_INCLUDE_NOTIFICATION_SHELL_COMMAND_H + +#include "shell_command.h" + +#include "ans_manager_interface.h" +#include "ans_notification.h" + +namespace OHOS { +namespace Notification { + +class NotificationShellCommand : public OHOS::AAFwk::ShellCommand { +public: + NotificationShellCommand(int argc, char *argv[]); + ~NotificationShellCommand() override{}; + +private: + ErrCode CreateCommandMap() override; + ErrCode CreateMessageMap() override; + ErrCode init() override; + ErrCode RunAsHelpCommand(); + ErrCode RunAsDumpCommand(); + +private: + std::shared_ptr ans_; +}; + +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_TOOLS_DUMP_INCLUDE_NOTIFICATION_SHELL_COMMAND_H \ No newline at end of file diff --git a/tools/dump/src/main.cpp b/tools/dump/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a650b7e4fd83240780365c8ca85fd893339859d --- /dev/null +++ b/tools/dump/src/main.cpp @@ -0,0 +1,25 @@ +/* + * 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 "notification_shell_command.h" + +int main(int argc, char *argv[]) +{ + OHOS::Notification::NotificationShellCommand cmd(argc, argv); + std::cout << cmd.ExecCommand(); + return 0; +} \ No newline at end of file diff --git a/tools/dump/src/notification_shell_command.cpp b/tools/dump/src/notification_shell_command.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54fa0f5125744134ec7542c3d125c7b451e93d3e --- /dev/null +++ b/tools/dump/src/notification_shell_command.cpp @@ -0,0 +1,144 @@ +/* + * 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_shell_command.h" + +#include +#include + +#include "ans_inner_errors.h" +#include "iservice_registry.h" +#include "singleton.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { +namespace { +static const std::string HELP_MSG = "usage: anm []\n" + "These are common commands list:\n" + " help list available commands\n" + " dump dump the info of notification\n"; +static const std::string DUMP_HELP_MSG = + "usage: anm dump []\n" + "options list:\n" + " --help, -h help menu\n" + " --active, -A list all active notifications\n" + " --recent, -R list recent notifications\n" + " --setRecentCount set the max count of recent notification keeping in memory\n"; +} // namespace + +NotificationShellCommand::NotificationShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, "anm_dump") +{} + +ErrCode NotificationShellCommand::CreateCommandMap() +{ + commandMap_ = { + {"help", std::bind(&NotificationShellCommand::RunAsHelpCommand, this)}, + {"dump", std::bind(&NotificationShellCommand::RunAsDumpCommand, this)}, + }; + + return ERR_OK; +} + +ErrCode NotificationShellCommand::CreateMessageMap() +{ + messageMap_ = {}; + + return ERR_OK; +} + +ErrCode NotificationShellCommand::init() +{ + ErrCode result = OHOS::ERR_OK; + + if (!ans_) { + ans_ = DelayedSingleton::GetInstance(); + } + + if (!ans_) { + result = OHOS::ERR_INVALID_VALUE; + } + + return result; +} + +ErrCode NotificationShellCommand::RunAsHelpCommand() +{ + resultReceiver_.append(HELP_MSG); + return ERR_OK; +} + +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; + int option = getopt_long(argc_, argv_, "hAR", options, &ind); + + ErrCode ret = ERR_OK; + std::vector infos{}; + + switch (option) { + case 'h': + resultReceiver_.append(DUMP_HELP_MSG); + break; + case 'A': + if (ans_ != nullptr) { + ret = ans_->ShellDump("active", infos); + resultReceiver_.append("Total:" + std::to_string(infos.size()) + "\n"); + } else { + ret = ERR_ANS_SERVICE_NOT_CONNECTED; + } + break; + case 'R': + if (ans_ != nullptr) { + ret = ans_->ShellDump("recent", infos); + resultReceiver_.append("Total:" + std::to_string(infos.size()) + "\n"); + } else { + ret = ERR_ANS_SERVICE_NOT_CONNECTED; + } + break; + case 0: + if (ans_ != nullptr) { + ret = ans_->ShellDump(std::string(options[ind].name) + " " + std::string(optarg), infos); + } else { + ret = ERR_ANS_SERVICE_NOT_CONNECTED; + } + break; + default: + std::cout << __LINE__ << " " << option << " " << ind << " " << std::endl; + if (optarg) + std::cout << optarg << std::endl; + resultReceiver_.append(DUMP_HELP_MSG); + break; + } + + int index = 0; + for (auto info : infos) { + resultReceiver_.append("No." + std::to_string(index) + "\n"); + resultReceiver_.append(info); + } + + return ERR_OK; +} + +} // namespace Notification +} // namespace OHOS